Reputation: 595
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?
Upvotes: 12
Views: 10100
Reputation: 3091
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"); });
Upvotes: 0
Reputation: 140220
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.
Upvotes: 11
Reputation: 8396
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
});
Upvotes: 0
Reputation: 91630
Give this a rip:
$.ajax("/ajax_dummy", {
dataType: "text",
success: function() {
console.log("winning.");
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus); //error logging
}
});
Upvotes: 6