Question

I am doing a cross domain AJAX call with dataType as jsonp. I have set the Jsoncallback querystring parameter in the URL. However, the callback function is not getting called at all and instead the page gets redirected to itself.

The AJAX call is basically hitting a dot CMS service which returns below response when I tested it in browser directly:

myfunction({'state':'MEL', 'plan':'true' })

Here, "myfunction" is the string which I pass as the value of Jsoncallback parameter in URL

Here is my AJAX call

$.ajax({
  url:"http://website.hostname.com/validatepostcode.dot?postcode="+encodeURIComponent(thepostcode)+ "&Jsoncallback=parseResponse",
  dataType: "jsonp",
  async: false,
  crossDomain:true
  });


function parseResponse(data)
{
 alert(data);
}

Am I missing any parameter in AJAX call? Or there may be something wrong at service side?

Was it helpful?

Solution

The $.ajax jQuery function has specific configuration options for supplying the name of the callback function that seem to be missing from the code.

By setting dataType: 'jsonp' jQuery

Adds an extra "?callback=?" to the end of your URL to specify the callback

which is causing a problem as you are also adding a callback function in the url value.

To override this you can add the jsonp option which:

Override the callback function name in a jsonp request. This value will be used instead of 'callback' in the 'callback=?' part of the query string in the url.

You can also specify the data as a separate option (see Sending Data to the server) which I have also added below.

The following code should correctly use parseResponse() as the callback function.

$.ajax({
  url: 'http://website.hostname.com/validatepostcode.dot',
  type: 'get',
  data: {postcode: encodeURIComponent(thepostcode)},
  dataType: 'jsonp',
  jsonp: 'parseResponse'
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top