dwstein dwstein - 4 months ago 9
Javascript Question

How to use jquery ajax error parameter

I'm 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/) 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:

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);
?>

Answer

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.

    $.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 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.