Viktor Kashlyaev Viktor Kashlyaev - 3 months ago 10
jQuery Question

How handle errors in php script fired by Jquery.ajax?

I have php-script, firing with jquery ajax function. Somthing like this:

$("a.test").click (function () {
var new_id = $(this).attr("new_id");


$.ajax({
url: 'test.php',
type: "POST",
cache: false,
async: true,
data: ({
new_id : new_id
}),
success: function (data) {
alert (data);
},
error: function(){
alert('error');
}
});
return false;
});


Now, a have some errors in test.php, but I can't see them. Sript just runs and I have no feedback, only error alert (alert ('error')).

How can I get back errors, that I have in test.php to handle them?

Answer

If you echo the errors in test.php, you can simply do:

$.ajax({
    url: 'test.php',  
        type: "POST",
        cache: false,
        async: true,
    data: ({
        new_id : new_id
        }),
    success: function (data) { 
        alert (data);       
    },
    error: function(data){
        alert('error:'+data);
    }
});
return false;
}); 

Edit:

I usually do something like this. In test.php if you get an error, create an array with your error info and echo it json encoded:

$message=array('error' => 1,'message' => '<div class="alert alert-danger" role="alert">' . $login['message'] . '</div>' );
echo json_encode($message);

Now in your jquery you can retrive the error by:

success: function (data) { 
        alert (data);       
    },
    error: function(data){
        var obj = JSON.parse(data);
        alert(obj.message);
    }

When you have it in array like this you dont even need error: function(data) anymore, since you can simply:

success: function (data) { 
    var obj = JSON.parse(data);      
    if (obj.error) {
        // do something
        alert (obj.message); 
    }else{
        // do something else
    }
 },