Callback function for JSONP with jQuery AJAX Callback function for JSONP with jQuery AJAX ajax ajax

Callback function for JSONP with jQuery AJAX


This is what I do on mine

$(document).ready(function() {  if ($('#userForm').valid()) {    var formData = $("#userForm").serializeArray();    $.ajax({      url: 'http://www.example.com/user/' + $('#Id').val() + '?callback=?',      type: "GET",      data: formData,      dataType: "jsonp",      jsonpCallback: "localJsonpCallback"    });  });function localJsonpCallback(json) {  if (!json.Error) {    $('#resultForm').submit();  } else {    $('#loading').hide();    $('#userForm').show();    alert(json.Message);  }}


delete this line:

jsonp: 'jsonp_callback',

Or replace this line:

url: 'http://url.of.my.server/submit?callback=json_callback',

because currently you are asking jQuery to create a random callback function name with callback=? and then telling jQuery that you want to use jsonp_callback instead.


$.ajax({        url: 'http://url.of.my.server/submit',        dataType: "jsonp",        jsonp: 'callback',        jsonpCallback: 'jsonp_callback'    });

jsonp is the querystring parameter name that is defined to be acceptable by the server while the jsonpCallback is the javascript function name to be executed at the client.
When you use such url:

url: 'http://url.of.my.server/submit?callback=?'

the question mark ? at the end instructs jQuery to generate a random function while the predfined behavior of the autogenerated function will just invoke the callback -the sucess function in this case- passing the json data as a parameter.

$.ajax({        url: 'http://url.of.my.server/submit?callback=?',        success: function (data, status) {            mySurvey.closePopup();        },        error: function (xOptions, textStatus) {            mySurvey.closePopup();        }    });


The same goes here if you are using $.getJSON with ? placeholder it will generate a random function while the predfined behavior of the autogenerated function will just invoke the callback:

$.getJSON('http://url.of.my.server/submit?callback=?',function(data){//process data here});