Jquery $ .ajax call succeeds but returns nothing. (Jsonp)

$(document).ready(function() { $('#button').click(function() { try { var json = $.ajax({url : 'http://www.example.com/experimental/service.php', type : 'jsonp', success : function() {alert('success')}}); alert(json); } catch(err) { alert(err.description) } var sjson = JSON.stringify(json); $('#display').html(sjson); }) }) 

After clicking the button, a warning message appears with the message "success", as well as a message that says undefined, referring to the fact that nothing was received from the ajax call. I checked the "net" firebug tab and really received a successful response from the server "jsonp1272724228884 ({});" Any ideas?

0
jquery jsonp ajax
source share
2 answers

I would like to show that alert(json); shows undefined because it is running before receiving a response.

Remember that "ajax" is "asynchronous", so a warning will be executed before your json value gets the opportunity to assign a value.

Also, even if that worked, your json variable would just refer to the XMLHttpRequest object that was created. If you want to access the data itself, you must do this in a callback.

 var json; $.ajax({ url : 'http://www.example.com/experimental/service.php', type : 'jsonp', success : function(data) { alert('success'); json = data; alert(json); } }); 

EDIT:

There is also an error: callback, which you can assign. A callback will be executed if the server returns an error code. I assume this is what you intended to replicate with try / catch.

+2
source share

If you want to use the result immediately after executing the ajax callback, you must set the async : false attribute to call ajax to make it synchronous. Since this is usually not what you want to do, you should probably handle the response in a different (asynchronous) way.

+1
source share

All Articles