1

I am using jQuery Ajax with PHP. When I use post with jQuery Ajax, then it's send request to PHP (server). In my PHP code, I want to return status success or error. In case it error, send error code and error message, else, it success return success code and message.

How can I do that in jQuery Ajax with PHP?

Edit:

$.post(url, { id: id },
function(data) {
    // success code do here.
});
KH-DP
  • 43
  • 2
  • 8
  • 1
    Add your ajax code for clear answer! – Svetoslav Oct 29 '12 at 09:15
  • You can check my edit on post. For my jQuery ajax is work fine. what i want is how to determine that it error or success, and how can we response in php code. – KH-DP Oct 29 '12 at 09:29
  • Here the link for Handling Success and Error on Ajax Post [**Click**](http://stackoverflow.com/questions/2833951/how-to-catch-ajax-query-post-error) – Arun Manjhi Oct 29 '12 at 09:45
  • @ArunManjhi thank you. but it's just ajax code. What is code we write in php to determine or let ajax know that it error? – KH-DP Oct 29 '12 at 09:57

2 Answers2

4

Just return array with json encode...

header('Content-Type: application/json');
$array = array("status"=>"success");
echo json_encode($array);
exit();

The exit is to prevent any further echo's .

At your ajax ..

$.post(url, { id: id },
function(data) {
    alert(data.status);
}, 'json');

the data.status equals to your php array key status ..

to just catch at Ajax error ... You can set simple..

header('Content-Type: application/json');
echo "string whithout json_encode";
exit();

In this case change your ajax to ...

$.post(url, { id: id },function(data) {}, 'json')
.success(function(data) { alert("success"); })
.error(function(data) { alert("error"); });
Svetoslav
  • 4,686
  • 2
  • 28
  • 43
  • in this case mean that all status error or success is response into success function in ajax. so all code in php return only json data that determine it's error or success, but can not set it to error that can catch by ajax – KH-DP Oct 29 '12 at 10:10
  • @KH-DP you are correct. I personally prefer my PHP to tell me that everything is successfull or not, than to trust only on ajax responde. This way you can return and error message if it has failed, etc.. – Svetoslav Oct 29 '12 at 10:51
  • I accept your answer only on json content type as json that you return. – KH-DP Oct 31 '12 at 04:00
0

just return it with echo

PHP: 
if($check == 0){ 
    echo 'success';
    exit();
}
else {
    echo 'failed';
    exit();
}

jquery :
$.post(url, { id: id },
function(data) {
    alert(data);
});
Frenda
  • 57
  • 5