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

Deselect the checkbox that has been selected using a JavaScript function

I have been searching everywhere for a solution and I am hoping someone in this community can assist me. I am working with a script that triggers when a checkbox is selected from a group of checkboxes. Each checkbox is given a value of "customer id". < ...

Repetitive series of HTTP requests within a looping structure

Within my AngularJS project, I encounter the need to execute a varying number of HTTP requests in sequence. To achieve this, I believe that utilizing a loop is necessary: for (let i = 0; i < $scope.entities.length; i++) { MyService.createFixedValue ...

applying v-bind directive when the variable is null

I am using Vue and have a variable. If the variable has a value, I want to display an image (pic1). However, if the variable is empty, then I want to show another image (pic2). Here's my code... <template v-for="(item, index) in items"> <im ...

What is the best way to differentiate between a JSON object and a Waterline model instance?

Note: I have posted an issue regarding this on the Waterline repo, but unfortunately, I have not received a simpler solution than my current workaround. Within my User model, along with default attributes such as createdDate and modifiedDate, I also have ...

Using jquery mobile to implement an event handler for the close button on a page dialog

Is it possible to trigger a callback before closing a dialog-style page when the close button is clicked? I want to catch and handle the click event of the close button on the dialog page. <div data-role="page" id="page1"> <div data-role="he ...

Reactivity in Vue.js powered by ES6 classes

I am attempting to create a computed property in Vue.js that is associated with an ES6 class. Here is an example of my Vue instance setup: ... props: ['customClass'], computed: { localClass: { get() { return this.custom ...

What are the steps to resolving an Unhandled promise rejection error in a Node.js application?

I encountered an error message that I need help resolving: I am faced with an unhandled promise rejection. This issue likely occurred due to throwing inside an async function without a catch block, or rejecting a promise without handling it using .catch( ...

Service error: The function of "method" is not valid

In one of my Angular 2 applications, I have a class that contains numerous methods for managing authentication. One particular method is responsible for handling errors thrown by the angular/http module. For example, if a response returns a status code o ...

Received an illegal invocation error when attempting to make a POST request to upload

I'm struggling to make a post request with an image. Whenever I try to add the image as a parameter, I receive the error message Uncaught TypeError: Illegal invocation. I have attempted using both .serialize() and other methods, but none of them are w ...

Bring to the front the div altered by a CSS3 animation

Recently, I encountered an issue with a div card that triggers an animation when clicked. The animation involves the card scaling up larger, but the problem arises as its edges get hidden under other cards. To visualize this, take a look at the screenshot ...

How can we store the value of a jQuery UI draggable element?

I am seeking assistance in determining the optimal solution for saving jQuery UI draggable values. My goal is to save these values efficiently. Although I have been researching ajax, I am unsure of how to integrate it with PHP database (I am using WordPre ...

The custom layout in NestJS version 13 failed to display

I have implemented NextJs 13 in my project for building purposes. I am trying to use CustomLayout as the primary layout for my entire website. Even though there are no errors, I am facing an issue where the CustomLayout does not display as expected. ...

What are the recommended margins for various alphabets?

When displaying text, some alphabets take up more space than others. So how can I adjust the white space between elements '#re1' and '#re2' automatically in the scenario described below? In this code snippet, what is the best way to ad ...

Having difficulty saving data in database using Ajax request from a Chrome extension

I am currently working on an extension that captures the page URL and saves it in a database once the user clicks the submit button. However, I have encountered a roadblock and believe there might be a missing piece in the extension setup that I cannot pi ...

What steps do I need to take to adjust this function based on the timezone?

Is there a way to retrieve the current time based on a specific timezone of my choice? let getCurrentTime = () => { var today = new Date(); var hh = String(today.getHours()) var mm = String(today.getMinutes()) //January is 0! var ss = ...

Scrolling to the latest message in Vuejs when a new message is received

I am currently working on a chat application, but I am facing an issue with scrolling to the bottom when new messages are received. I have attempted both methods: document.getElementById('msg_history').scrollTop = document.getElementById('m ...

Utilizing AngularJS: Using ng-click with ng-repeat to retrieve all data simultaneously

Having a simple ng-repeat: <div ng-repeat="x in names"> <h4>{{x.productid}}</h4> <h4>{{x.newquantity}}</h4> <h4>{{x.total}}</h4> <button ng-click="addInfoAboutOrder(x)">Add Info</button> ...

Can the installation of Canvas be done on a device with the M1 chip?

When attempting to install canvas on a MacBook Pro M1 using the command: npm install --save-dev canvas An error is displayed: npm ERR! code 1 npm ERR! path /Users/xiaoqiangjiang/source/reddwarf/frontend/js-wheel/node_modules/canvas ... (error message con ...

AngularJS directive ngShow not working properly

It seems like I'm encountering some scope issues that I can't seem to resolve. Here's a rundown of the problem: I'm trying to create a custom directive called "my-create-content" that will insert an "img" HTML template into the element ...

Having Trouble with Your Instafeed Script

I've been working on a project that involves integrating an Instagram feed into a website. However, I'm facing difficulties getting it to function properly. Here's the code that I have implemented. <script type="text/javascript"> ...