0

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?

  • Simplest solution is to open the console and go to Network tab and see the respond of the request. This solution is if you don't want to change code. – Daniel Dudas Aug 17 '16 at 11:55

3 Answers3

2

On test.php you could show errors using the code explained here: https://stackoverflow.com/a/21429652/6525724

And then on this page instead of alert('error') you could use alert(data).

Community
  • 1
  • 1
Nick
  • 12,032
  • 3
  • 11
  • 27
2

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
    }
 },
Bolli
  • 4,714
  • 5
  • 29
  • 45
2

Try this

 error: function(XMLHttpRequest, textStatus, errorThrown) { 
    alert("Status: " + textStatus); alert("Error: " + errorThrown); 
}       
Burhan Nasir
  • 526
  • 4
  • 12