12

Javascript code, using jQuery 1.7:

$( function() { 
  $.get('/ajax_dummy', function() { alert('foo');  })
});

With Firebug I can see that the HTTP GET request is sent and a "hello world" response with code 200 is returned, so everything seems fine. But the callback is never called.

I have no idea what is wrong; this should be so simple, right?

Lucy Brennan
  • 555
  • 1
  • 7
  • 13

4 Answers4

10

You are not providing dataType so jQuery makes an "intelligent guess" of what the content type is from the response Content-Type header which you said is application/json.

So jQuery treats the response as JSON which means it will try to automagically parse it as so, causing an error.

Because the request causes an error

$.parseJSON( "hello world" );
"Invalid JSON: hello world"

the success callback won't obviously be fired.

Esailija
  • 130,716
  • 22
  • 250
  • 308
6

Give this a rip:

$.ajax("/ajax_dummy", {
    dataType: "text",
    success: function() {
        console.log("winning.");
    },
    error: function(jqXHR, textStatus, errorThrown) {
        console.log(textStatus); //error logging
    }
});
Naftuli Kay
  • 75,812
  • 80
  • 244
  • 374
0

add this markup

<div id="error"></div>

then add this handler to catch AJAX errors

$("#error").ajaxError(function(event, request, settings){
  $(this).append("<li>Error requesting page " + settings.url + "</li>");
});

Alternatively, you could rewrite your original code like this

$.get('/ajax_dummy', function() { 
    alert('foo');  
}).error(function() {
    // catch error
});
Lloyd
  • 7,498
  • 2
  • 31
  • 52
0

This is because according to the documentation the $.get() syntax should be like this

jQuery.get( url [, data] [, success(data, textStatus, jqXHR)] [, dataType] )

please note the "success" callback option. a success callback called when the request is success based on status codes (200). but your url might be not a valid path or returns some other status code (404) meaning "file not found" and thus an error occurs. so success method never called.

also there is no "error" callback defined with your syntax. check the following more complete code

$.get("/ajax_dummy", function() { alert('foo'); })
  .error(function(d,e) { alert(e); })
  .complete(function() { alert("complete"); });
Syed Ekram Uddin
  • 2,289
  • 1
  • 22
  • 28