tags:

views:

176

answers:

2
$(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 a button is pressed I get an alert message that says "success" and also one that says undefined, referring to the fact that nothing was returned from the ajax call. I checked the firebug 'net' tab and indeed i get a succesful response from the server of "jsonp1272724228884( {} );" Any ideas?

+1  A: 

If you want to use the result right after making the ajax callback, you have to set the async : false attribute of ajax call to make it synchronous. As this is usually not what you want to do, you should probably process the response in a different (asynchronous) way.

Thomas Wanner
+2  A: 

I would image that alert(json); is showing undefined because it is running before the response is received.

Remember that 'ajax' is 'asynchronous', so that alert will go ahead and execute before your json value has a chance to be assigned a value.

Furthermore, even if it did work, your json variable would simply reference the XMLHttpRequest object that was made. If you want to access the data itself, you need to do so in the 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's also an error: callback that you can assign. The callback will execute if the server returns an error code. I assume that is what you intended to replicate with your try/catch.

patrick dw
That was it! Thank you so much!
Shawn