dwstein dwstein - 8 months ago 28
Javascript Question

How to use jquery ajax error parameter

I'm looking for a simple example and/or explanation of how to use the

parameter for

This question (jQuery ajax error function) points to this jQuery documentation (http://api.jquery.com/jQuery.ajax/) which I do not understand.

I have the following code that does not work and I can't figure out why. I'm hoping the error parameter will help:


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

PHP (ajax_text.php)

echo json_encode($_POST);


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

       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) {

Keep in mind that the error callback function will only be invoked if the request actually errors out. If your code simply does not return anything but the request still returns a status of 200 you will have to handle that exception in the success callback function.

Hope this helps.

EDIT: note that I removed the use of chaining events and now all callback functions are handled inside the original parameters object passed into $.ajax.