How to use jQuery ajax error parameter

I am looking for a simple example and / or explanation of how to use the error parameter for .ajax .

This question ( jQuery ajax error function ) points to this jQuery documentation ( http://api.jquery.com/jQuery.ajax/ ) that I don't understand.

I have the following code that does not work and I can not understand why. I hope the error parameter helps:

JQuery

  <script> // wait for the DOM to be loaded $(document).ready(function() { // bind 'myForm' and provide a simple callback function $("#myForm").submit(function(){ var user_input = $("#signup_id_email").val(); $.ajax ({ type: "POST", url: "ajax_test.php", dataType: 'json', data: {email: user_input}, **error: ""** }) .done(function(r) { $("#answer_id").append(r.email); }); }); }); </script> 

PHP (ajax_text.php)

 <?php echo json_encode($_POST); ?> 
+6
source share
2 answers

The error property of the $ .ajax parameter object is used to provide a callback function known as closing the $ .ajax method. In other words, you need to provide an anonymous function to handle the error if it occurs during an ajax request. Here is a basic example.

  $.ajax({ type: "POST", url: "ajax_test.php", dataType: 'application/json', data: {email: user_input}, success: function(result) { // You can use success instead of .done }, error: function(requestObject, error, errorThrown) { alert(error); alert(errorThrown); } }); 

Keep in mind that the error callback function will only be called if the request really fails. If your code just doesn't return anything, but the request still returns 200, you will have to handle this exception in the success callback function.

Hope this helps.

EDIT: note that I removed the use of chain events, and now all the callback functions are processed inside the original parameter object passed in $ .ajax.

+12
source

I doubt that you even send a request. Your spaces are disabled.

Javascript does not need semicolons at the end of statements. Because of this, sometimes they appear where you do not want them.

Try putting '({' on the same line as $ .ajax. You have not seen the error because it does not exist. $ .Ajax is a valid statement, although it does nothing. Similarly, the object you create inside parentheses, is a valid object, even if it does nothing.

 $.ajax({ type: "POST", ... }).done(function(r) { .... }); 

To answer your original question, the error takes a function as a parameter. This function takes 3 parameters in the following order:

  • XHR (request)
  • request status
  • error that was selected (may be undefined)

An example is as follows:

 $.ajax({ ... error: function(xhr, status, error) { alert("oh no!"); } }) 
+2
source

All Articles