Reputation: 7805
I'm sending some data via Post to a php file, and I'm always retrieving a "success" in Jquery status even though the PHP is clearly sending back an error message.
What's the reason behind that?
$.post('post.php',
{
post1:somevariable1,
post2:somevariable2,
post3:somevariable3
},
function(response,status){
if(status == "success") {
//success message (I'm always getting this)
}
else {
//error message
}
});
Post.php
if ($stmt === false) {
echo "error!!";
die(print_r(sqlsrv_errors(), true)); // This is what PHP is sending
} else {
echo "Success!!";
sqlsrv_free_stmt($stmt);
}
Thanks!
Upvotes: 0
Views: 193
Reputation: 147166
As has been pointed out in the other answers, your PHP file is completing and then returning a success status and so you always see status=='success'
. What you actually want to do is check the value in response
. I would recommend doing something like:
if ($stmt === false) {
echo json_encode(array('success' => false, 'reason' => sqlsrv_errors()));
exit;
} else {
echo json_encode(array('success' => true));
sqlsrv_free_stmt($stmt);
}
Then in your jquery do this:
$.post('post.php',
{
post1:somevariable1,
post2:somevariable2,
post3:somevariable3
},
function(response,status){
let result = $.parseJSON(response);
if (result.success) {
echo "success!";
}
else {
echo "error: " + result.reason;
}
});
Upvotes: 1
Reputation: 5053
If you're sending the result of an operation as the return of a request, simply check the response in the success
callback`
$.post('post.php',
{
post1:somevariable1,
post2:somevariable2,
post3:somevariable3
},
function(response,status){
if(response.status == "success") { // Here I'm checking the `response` argument
//success message (I'm always getting this)
}
else {
//error message
}
});
Where I've made the assumption that your response is being sent back from PHP as an object with the property status
:
{
status: "success"|"error"
}
Upvotes: 1
Reputation: 1898
I think the problem is that there is not a problem going on, the server is giving you a response of 200, because it did'nt find an error.
try using headers inside the condition where you want it to fail like
header("HTTP/1.1 500 Internal Server Error");
exit;
//or try return false;
Upvotes: 0
Reputation: 2223
The post.php is responding with status 200 with a response. The browser/js doesn't check what text you are sending in the response.
You can set the header to let the browser/just know about the error:
header("HTTP/1.1 500 Internal Server Error");
Upvotes: 0