Elyor
Elyor

Reputation: 5532

return error to sweetalert from php

I have this ajax code to process php file

$.ajax({
  url:'vals/Package.php', 
  data:$(this).serialize(),
  type:'POST',
  success:function(data){
    console.log(data);
    swal("Success", "We will contact you soon! Thank you :)", "success");
  },
  error:function(data){
    swal("Sorry", "Failed to send order. Please try later :(", "error");
  }
});

in my Package.php

$Query = mysqli_query($connecDB,"insert into query here");
if($Query){
    echo 'success message';
}
else{
    echo 'error here';
}

if there is an error inserting into database, how can I send it to sweetalert?

if I remove if else condition, it is showing Success message. I am trying to show the error message as well.

Upvotes: 1

Views: 2624

Answers (3)

Elyor
Elyor

Reputation: 5532

I found this code, it seems working

if($Query){

}
else{
    header('HTTP/1.1 500 Internal Server...');
    header('Content-Type: application/json; charset=UTF-8');
    die(json_encode(array('message' => 'ERROR', 'code' => 1337)));
}

Upvotes: 1

mibrito
mibrito

Reputation: 164

The best solution is using a try/catch and send two kind of messages as response, the following is a snipped using your own code:

In your package.php

try {
    $Query = mysqli_query($connecDB, "insert into query here");
    if ($Query) {
        echo 'success message';
    } else {
        throw new Exception('dummy error message');
    }
} catch (Exception $exc) {   
    //handle any errors in your code, including connection issues
    echo 'error'; //this will be your "flag" to handle on the client side
    //and if you want, can also log the error with 
    //$exc->getMessage() or $exc->getTraceAsString()
    die;
}

In the JS file:

$.ajax({
    url: 'vals/Package.php',
    data: $(this).serialize(),
    type: 'POST',
    success: function (data) {
        if (data !== 'error') {
            swal("Success", "We will contact you soon! Thank you :)", "success");
        } else {
           //our handled error
            swal("Sorry", "Failed to send order. Please try later :(", "error");
        }
    },
    error: function (data) {
           //other errors that we didn't handle
        swal("Sorry", "Failed to send order. Please try later :(", "error");
    }
});

With the use of try/catch your code will be bullet proof against unexpected errors. Note: Of course you can edit the headers instead of echoing your own flag and return an http error that will be handled in your ajax error function.

Upvotes: 1

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76395

You're now simply echoing an error string, but that response is still going to be sent with a status 200 header. What you need to do is set the headers explicitly:

header('HTTP/1.1 500 Internal Server Error');
echo 'error message';

I think I'm right in saying that jQuery simply regards all non HTTP 200 responses as errors (ie unsuccessful requests). There might be some exceptions to this, like a 404, 301, or possibly the 201 status codes. Either way, if you want to indicate a serious problem: use http 500 (internal server error)

Upvotes: 2

Related Questions