30

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?

Frank Michael Kraft
  • 2,302
  • 5
  • 25
  • 30
  • 3
    One problem I've seen that can cause that scenario are if the hosted page and the ajax target are on different domains. – artlung May 07 '10 at 08:30
  • http://stackoverflow.com/questions/21368375/why-does-jquery-ajax-call-only-work-when-im-debugging-in-chrome this works try it it worked for me – Rupesh Terase Apr 25 '14 at 12:12

6 Answers6

60

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
  • 819
  • 6
  • 6
6

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
  • 71,966
  • 47
  • 171
  • 241
  • Actually, you can; at least in modern browsers. I don't think $.ajax handles that, though. – Tgr May 07 '10 at 08:59
  • 1
    Anyway, if it would be a cross-site request, the AJAX call wouldn't return in the first place. – Tgr May 07 '10 at 09:01
  • @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 – systempuntoout May 07 '10 at 09:20
  • 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 May 07 '10 at 09:31
  • I'm talking about Jquery's Ajax call as OP has requested. – systempuntoout May 07 '10 at 09:56
  • In my scenario it is the same domain. – Frank Michael Kraft May 07 '10 at 12:32
  • "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 May 07 '10 at 12:34
  • @Frank Why are you using dataType: 'jsonp'? – systempuntoout May 07 '10 at 12:35
3

This is an old question, but I suspect people still hit this.

I fought this for some time, and eventually gave up and moved to the deferred model. (I've been using jQuery long enough that I was in the "old" way habits still...) As soon as I moved to a deferred model, things started to work. I have no idea why the old way didn't work, but no longer care. (This question pre-dates the new model.)

cf. https://stackoverflow.com/a/14754681/199172

Community
  • 1
  • 1
MikeBaz - MSFT
  • 2,938
  • 4
  • 28
  • 57
1

You need to set async property to false.

$.ajax({
    url: target,
    contentType: 'application/json; charset=utf-8',
    type: 'POST', // or 'GET',
    dataType: 'jsonp',
    async: false,
    error: function (xhr, status) {
        alert(status);
    },
    success: function (result) {
        alert("Callback done!");
        // grid.dataBind(result.results);
        // grid.dataBind(result);
    }
});
Mano Mahe
  • 84
  • 1
  • 17
  • Thanks, this was the case for me. This will happen if the page posts back before the AJAX call is finished. The call will generally fail quickly so I was only seeing the error message before my page did a post back. – DrewB Nov 25 '15 at 21:25
  • if you use a service worker, fast responses can make this happen with much more frequency. The deferred model avoids this. see @MikeBaz 's answer. – Ray Foss Oct 20 '16 at 14:21
0

This just happened to one of my co-workers, so I figure I'd add my solution as well.

We could see the ajax call being made, and could see the proper response coming back in Fiddler (status 200 / completely valid JSON), but it would never hit the error, success, or complete callbacks. Adding async: false to the ajax call would make it work, but that wasn't really a proper solution. Additionally placing an alert directly after the ajax call (without the async: false), and waiting a few seconds once the alert was shown, would somehow force the ajax callbacks to work . Very odd indeed...

Turns out, the function with the ajax call was bound to an input of type="submit", which was the source of this odd behavior. Changing the input to type="button" corrected it.

Xorcist
  • 3,129
  • 3
  • 21
  • 47
-1

Jquery Ajax call to a servlet with mutliple parameters was not calling success or error even though the call was succesfull. It was bound to a submit button. Changing it returned a success event.

Here is my reference code in case someone needs it for reference.

$(document).ready( function () {    
    $("#buttonSave").click(function() {
        alert('incustsave');
        var name = $("#custname").val();
        var gstnumber = $("#gstnumber").val();
        var custbizname = $("#custbizname").val();
        var email = $("#email").val();
        var address = $("#address").val();
        var street = $("#street").val();
        var city = $("#city").val();
        var zip = $("#zip").val();
        var phone = $("#phone").val();
        var country = $("#ctry").val();

        var inputArray = [name, gstnumber, custbizname, email, address, street, city, zip, phone, country];
        var Success = false;
        alert('added_button_and_dt');
        $.ajax({  
            type: "POST",
            url: "RegisterCustomerServlet",               
            data: {'input': inputArray},
            dataType: 'json',

            success: function (data) {
                alert('sucess');
            },
            error: function (e) {
                alert('error');
            }
        });
    });
});

HTML with Bootstrap3 (Button reference)

<!-- Button -->
<div class='wrapper text-center'>
    <div class="btn-group">
        <button type="button"  id="buttonSave" class="btn btn-primary">Save</button>
    </div>
</div>

Servlet Reference

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    HashMap<String,String>  map = new HashMap<String,String>();
    CustomerDAO custinfo = new CustomerDAO();
    Gson gson = new Gson();
    CustomerVO vo = new CustomerVO();

    String[] myJsonData = request.getParameterValues("input[]");
    logger.info("in custregisterjsoninput" + myJsonData[0] + myJsonData[2] + myJsonData[3] + myJsonData[4]);

    map.put("custname", myJsonData[0]);
    map.put("getsnumber", myJsonData[1]);
    map.put("custbizname", myJsonData[2]);

    map.put("email", myJsonData[3]);
    map.put("address", myJsonData[4]);
    map.put("street", myJsonData[5]);
    map.put("city", myJsonData[6]);          
    map.put("pincode", myJsonData[7]);
    map.put("mainphone", myJsonData[8]);
    map.put("country", myJsonData[9]);

    try {
        vo = custinfo.saveCustomerInfo(map);
    } catch (Exception e) {
        logger.info("aftercall"+e.getMessage());
        throw new ServletException(e);
    }  
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(Utility.convertPOJOtoJason(vo));
}
Jerry Stratton
  • 3,287
  • 1
  • 22
  • 30