views:

541

answers:

2

I have a JavaScript Ajax call (jQuery.ajax), that does not execute the success callback function.

$.ajax({
        url: target,
        contentType: 'application/json; charset=utf-8',
        type: 'POST',
        // type: 'GET',
        dataType: 'jsonp',
        error: function (xhr, status) {
            alert(status);
        },
        success: function (result) {
            alert("Callback done!");
            // grid.dataBind(result.results);
            // grid.dataBind(result);
        }
    });

I see in firebug, that the request is posted and the correct result in terms of the json is returned as expected. What is wrong?

A: 

Your $.ajax call with dataType: 'jsonp' could work in these scenarios:

  1. You are calling a url on the same domain of your page.
  2. You are calling a url out of your domain of your page that supports callback

If you are out of these two cases, you can't do anything since you can’t make cross site XmlHttpRequest calls.

systempuntoout
Actually, you can; at least in modern browsers. I don't think $.ajax handles that, though.
Tgr
Anyway, if it would be a cross-site request, the AJAX call wouldn't return in the first place.
Tgr
@Tgr are you sure?Jquery Ajax cross domain call switches to Jsonp, substitutes callback function name to ? on you callback url parameter and calls the url adding a <script> tag in your page header.
systempuntoout
Adding a script tag to your header is not an AJAX call. (I didn't know jQuery can do that, though - cool.) You can do actual cross-domain AJAX calls in modern browsers. It will depend on the target server authorizing you through a special HTTP header, which they usually don't, so it has little practical application as of yet.
Tgr
I'm talking about Jquery's Ajax call as OP has requested.
systempuntoout
In my scenario it is the same domain.
Frank Michael Kraft
"Adding a script tag to your header is not an AJAX call. (I didn't know jQuery can do that, though - cool.)"The script is executed, if a button is pressed. The AJAX call is executed, I see the result in firebug.
Frank Michael Kraft
@Frank Why are you using dataType: 'jsonp'?
systempuntoout
+1  A: 

For many times I have encountered similar problems and most of the time the reason was a malformed json. Try getting the result as text data type to see whether this is your problem.

Also, I'd like to ask if you're using a parameter like "&jsoncallback=?" in your url, since your data type is jsonp instead of simple json.

Cagdas
I had same type of problems and mostly it is malformed json. Validate your JSON response at jsonlint.com
Adeel
I validated, that it is valid JSON.
Frank Michael Kraft
json instead of jsonp solved it. Thanks.
Frank Michael Kraft