Issue encountered with JavaScript AJAX involving a Cross Domain ASMX Web Service JSONP Request

I have been working on a local web service that I believe fits the criteria for making cross-domain JavaScript calls to access external data within Dynamics CRM. However, I am facing some challenges in creating the JavaScript AJAX code needed to connect with this external web service.

By accessing the web service at , I was able to generate the results displayed in Screen Shot 1 below:

Screen Shot 1

The main issue I'm encountering is figuring out how to correctly write the JavaScript code to fetch the serialized items from the web service mentioned above.

Upon running the page and clicking the "test" button, I receive an error message stating '0x800a1391 - JavaScript runtime error: 'GetJSONP' is undefined.'

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ClientSideGeneralTest._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "www.w3.org/.../xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">


        <script language="JavaScript" type="text/JavaScript" src="Scripts/jquery-3.1.1.min.js">

function GetJSONP() {
  debugger;
 $.ajax({
    url: "aloyegeneraltest1/.../GetPriceJSON",
    type: "POST",
    contentType: "application/json; charset=utf-8",
    data: '{"name":' + JSON.stringify(GetData()) + '}'
  }).done(function(result) {
    alert(result.d);
  }).fail(function(result) {
    alert(result.d);
  });
            }

}


</script>

<head runat="server">


    <title></title>
</head>
<body>
   <form id="form1" runat="server"> 
<div> 
<input id="Button1" type="button" 
  value="Test" onclick="GetJSONP()" /><br /> 

</div> 
</form> 

    &nbsp;
</body>
</html>

If I remove the JQuery reference entirely, it eliminates the undefined function error mentioned earlier, but it leads to a new unhandled exception error: '0x800a1391 - JavaScript runtime error: '$' is undefined.'

This is the modified code snippet that triggers the new error:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ClientSideGeneralTest._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "www.w3.org/.../xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">


        <script language="JavaScript" type="text/JavaScript">

function GetJSONP() {
  debugger;
 $.ajax({
    url: "aloyegeneraltest1/.../GetPriceJSON",
    type: "POST",
    contentType: "application/json; charset=utf-8",
    data: '{"name":' + JSON.stringify(GetData()) + '}'
  }).done(function(result) {
    alert(result.d);
  }).fail(function(result) {
    alert(result.d);
  });

}


</script>

<head runat="server">


    <title></title>
</head>
<body>
   <form id="form1" runat="server"> 
<div> 
<input id="Button1" type="button" 
  value="Test" onclick="GetJSONP()" /><br /> 

</div> 
</form> 

    &nbsp;
</body>
</html>

The issue seems to be related to the use of '$' at the beginning of the Ajax code block.

As someone who is new to AJAX and relatively new to development as a whole, any help or advice offered would be highly appreciated.

Answer №1

If you're facing an issue, these lines of code could potentially help resolve it:


var jsonData = [INSERT YOUR JSON PARAMETER];

$.ajax({
    async: false,
    type: "POST",
    url: [INSERT YOUR WEB SERVICE URL],
    contentType: "application/json; charset=utf-8",                  
    data: JSON.stringify({ json: jsonData }),
    dataType: "json",                
    success: OnSuccess,
    failure: function(err) {
        alert("Error : " + err.d);
    }  
}); 

function OnSuccess(data) {
    alert("Success:" + data.d);                       
}

To enable cross-origin resource sharing (CORS), make sure to set Access-Control-Allow-Origin and Access-Control-Allow-Headers in the CustomHeaders section of your web service's web.config file.


<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />

If you only want to allow access from a specific domain, replace * with the desired domain value.

Answer №2

After some trial and error, I finally found the solution to my issue. Take a look at the two different script lines provided below.

<html xmlns="http://www.w3.org/1999/xhtml">
<script language="JavaScript" src="Scripts/jquery-1.7.1.min.js"></script>  
<script language="JavaScript" type="text/JavaScript">**
    function GetJSONP() {
        //debugger;
        $.ajax({
            url: "aloyegeneraltest1/.../GetPriceJSON",
            type: "POST",
            contentType: "application/json; charset=utf-8",

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The earlier polity of the web page no longer retains the JQuery callback method upon refreshing

Whenever I hit the refresh button on Chrome before my Ajax request succeeds, the callback function complete: function(data){ doSomething()} does not execute. function startMockServer() { $.ajax({ url: "/mocks/[[${id}]]/start", type: "P ...

How can I substitute a specific capture group instead of the entire match using a regular expression?

I'm struggling with the following code snippet: let x = "the *quick* brown fox"; let y = x.replace(/[^\\](\*)(.*)(\*)/g, "<strong>$2</strong>"); console.log(y); This piece of code replaces *quick* with <strong& ...

Determine the data type of a property within a JavaScript object

I am currently working with a javascript object that looks like this: venue = { id: 0, name: '', venueimage_set: [ { imageurl: '', }, ]... At a later point in my code, I need to modify the object ...

Show the message "No results found" if there are no matches, or hide the DIV displaying search results using AJAX and MySQL

I'm struggling with getting my search bar to display "No matches found" or hide the results div completely when a query doesn’t match any “Name” in the MySQL database. The search bar works for displaying AJAX live search results using MySQL, PHP ...

javascript problem with class method for loading json file

I've encountered an issue with my class setup below. Despite most things working, the console keeps throwing an error when json.onload is triggered. The error message reads "Uncaught TypeError: Cannot read property of 'push' of undefined". ...

Calculate the total amount based on the selected value from the radio button

For example, radiobutton A = value X, radiobutton B = value Y. Below is the code snippet I am utilizing: Javascript file: <script type="text/javascript" $(document).ready(function () { $("div[data-role='footer']").prepend(' ...

Executing Bower installation within a corporate proxy network

Encountering Error : ECONNREFUSED Request to https://bower.herokuapp.com/packages/bootstrap-datepicker failed: connect ECONNREFUSED while attempting Bower Install from Package Manager Console. I came across suggestions in a different discussion on how to ...

AJAX responses sans the use of jQuery

Similar Question: How can I achieve this through AJAX? After my previous attempt at asking this question, where I was not clear enough, I am making another effort to be as specific as possible. To start with, I have my data encoded using the json_enc ...

How can I trigger the rendering of a component by clicking a button in a separate component?

I am currently facing a challenge in rendering a component with an "Edit" button that is nested within the component. I attempted to use conditional rendering in my code, but unfortunately, I am struggling to make it work as expected. Does anyone have any ...

Implement a new list field to an object using javascript

I am facing a challenge in converting a JSON object to a list of JSON objects and then adding it back to JSON. Here is an example: config = { existing_value: 'sample' } addToListing = (field, value, index=0) => { config = { ...confi ...

Tips for transforming a React sign in component into an already existing Material UI sign in component

I am looking to revamp my current sign-in page by transitioning it into a material UI style login page. Displayed below is the code for my existing sign-in component named "Navbar.js". This file handles state management and includes an axios call to an SQ ...

What is the best way to upload an object in React using fetch and form-data?

Currently, I am facing an issue where I need to send a file to my express app as the backend. The problem lies in the fact that my body is being sent as type application/json, but I actually want to send it as form-data so that I can later upload this file ...

Retrieve solely the text content from a JavaScript object

Is there a way to extract only the values associated with each key in the following object? const params = [{"title":"How to code","author":"samuel","category":"categoery","body":"this is the body"}] I'm struggling to figure out how to achieve this. ...

Retrieve information stored within an object's properties

Possible Duplicate: Accessing a JavaScript Object Literal's Value within the Same Object Let's take a closer look at this JavaScript object var settings = { user:"someuser", password:"password", country:"Country", birthplace:countr ...

Tips for designing a versatile component to handle numerous buttons triggering form pop-ups

library used: mui 5.4.1 To implement a TableCell with an IconButton that triggers the opening of a Form, follow this code snippet. const items = [ { id: "001", name: "A", price: 2000 }, { id: "002", name: &q ...

Numerous JSON entities

Curious to know if it's achievable to load more than one JSON file with just a single jQuery.ajax() call. Or do I have to make separate calls for each file? Warm regards, Smccullough ...

"Upon querying with an AJAX POST request, the return value was

I'm encountering an issue where I am attempting to send data from JavaScript to PHP, make a database request, and have the result returned to my JS. However, all I get is "null" as a result. I have verified that my query is correct. Here is the JS cod ...

"Utilize axios in React to interpret and handle error bodies captured through parsing as a ReadableStream

When I sent a post request using axios in a React form to a PHP server, I encountered an issue where the error returned a ReadableStream in its body. However, when I used Postman, I did not have this problem and received readable errors instead. How can I ...

Clear form fields and remove any validation errors upon closing a div with jQuery

A popup div is housing a form that I want to reset both errors and fields when the form is closed. My plan was to add code in the disablePopup function to reset the form. Some important things to mention are that this is a Django project and I am using Aja ...

Combining plugin setups and functionalities into a unified script

When it comes to grouping plugin initializations and scripts in a website, I often have a "tools.js" file that contains various functions, click events, and more. I prefer keeping all these script calls centralized in one file for simplicity, organization, ...