Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax / php - How to return failure

Tags:

jquery

ajax

php

jquery allows for success failure and error responses. How can i return a failure or error manually along with a string that describes the failuer or error?

like image 433
John Avatar asked Aug 25 '10 20:08

John


People also ask

How do you make Ajax call fail?

The function specified by the ajaxError() function is called when the request fails or generates the errors. We can use the fail() callback function as well on the JavaScript promise object( the jqXHR object return by the $. ajax() function) to run the specific function on the ajax request fail.

How does Ajax return success data?

The ajaxSuccess event is only called if the request is successful. It is essentially a type function that's called when a request proceeds. The function takes three parameters, namely: The data returned from the server, formatted according to the dataType parameter, or the dataFilter callback function.

What is success response Ajax?

Response is the object passed as the first argument of all Ajax requests callbacks. This is a wrapper around the native xmlHttpRequest object. It normalizes cross-browser issues while adding support for JSON via the responseJSON and headerJSON properties.

What causes an Ajax error?

Many pages send AJAX requests to a server. Because this relies on the cooperation of the server and the network between the client and the server, you can expect these AJAX errors: Your JavaScript program receives an error response instead of data; Your program has to wait too long for the response.


1 Answers

It has become somewhat of a convention to utilize a simple JSON envelope to report failures that occurred on the server side (that are not HTTP errors).

The flickr api provides a typical packaging example:

look at the bottom of this page for success and failure examples

So in the case of an Ajax call to the flickr API, in your success callback you would check the returning data for success/failure

$.ajax({   
  //...   
  success:   function(data) {
    if(data.stat == 'fail') {
       //data.code + data.message contain details that could be used here
    }
    else {
      //do success stuff here
    }
  }
});
like image 103
Andrew Wirick Avatar answered Sep 19 '22 07:09

Andrew Wirick