Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to callback a function on 404 in JSON ajax request with jQuery?

Tags:

I want to make an Ajax request with response in JSON. So I made this Ajax request:

$.ajax({     url: 'http://my_url',     dataType: "json",     success: function(data){       alert('success');     },     error: function(data){       alert('error');     },     complete: function(data) {       alert('complete')     }}) 

This code works good but when my url send me a HTTP code 404, no callbacks are used, even the complete callback. After research, it's because my dataType is 'json' so 404 return is HTML and the JSON parsing failed. So no callback.

Have you a solution to call a callback function when a 404 is raised ?

EDIT: complete callback don't call is return is 404. If you want an URL wit 404 you can call : http://twitter.com/status/user_timeline/jksqdlmjmsd.json?count=3&callback=jsonp1269278524295&_=1269278536697 it's with this URL I have my problem.

like image 760
shingara Avatar asked Mar 22 '10 16:03

shingara


People also ask

What is the functionality of status is 404 in Ajax?

There is an easy way to check: Open your HTML in the browser, remove the last bit of the path, and replace it with "busca-notas. jpg", and see what you're getting. A 404 also means, your JSP code never gets executed.

What is callback jQuery Ajax?

jQuery - ajaxSuccess( callback ) Method The ajaxSuccess( callback ) method attaches a function to be executed whenever an AJAX request completes successfully. This is an Ajax Event.

How define callback function in jQuery?

jQuery Callback Functions JavaScript statements are executed line by line. However, with effects, the next line of code can be run even though the effect is not finished. This can create errors. To prevent this, you can create a callback function.

How do I return a response from Ajax?

What you need to do is pass a callback function to the somefunction as a parameter. This function will be called when the process is done working (ie, onComplete): somefunction: function(callback){ var result = ""; myAjax = new Ajax.


1 Answers

$.ajax({     url: 'http://twitter.com/status/user_timeline/jksqdlmjmsd.json?count=3&callback=jsonp1269278524295&_=1269278536697',     dataType: "json",     success: function(data) {         alert('success');     },     error: function(data) {         alert('error');     },     complete: function(xhr, data) {         if (xhr.status != 0)              alert('success');         else              alert('fail');     } }) 
like image 95
Dustin Laine Avatar answered Sep 21 '22 11:09

Dustin Laine