3

I have looked around and followed the instructions on this post but I still can not get the error function to execute. What I want to do is have my PHP script return either error or success along with a message. Eventually it will be data returned from a database that will be put inside of a div but for now I just need to get the error handling working. I am hoping someone here can help me out with this. I have included my code below.

This is obviously my AJAX request.

function getProductInfo() {
    if($("#serialNumber").val() != '') {
        serialNumber = $("#serialNumber").serialize();
        $.ajax({
            type: "POST",
            url: 'post.php',
            data: serialNumber + "&getSerialNumber=" + 1,
            dataType: 'json',
            success: function(data, textStatus, jqXHR) {
                console.log("SUCCESS");
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log("ERROR");
            }
        });
    }
}

This is my php function that will return the error and message as JSON

function getSerialNumber() {
    $serial = $_POST['serial'];
    $product = new Inventory;

    if($product->GetSerial($serial)) {
        $productInfo = $product->GetSerial($serial)->first();
        echo '{"error": false, "message": "Successfully got serial number"}';
    } else {
        echo '{"error": true, "message": "failed to get serial number"}';
    }
}

As the current code stand it will only keep outputting SUCCESS regardless if it actually has an error or not.

Community
  • 1
  • 1
Yamaha32088
  • 4,125
  • 9
  • 46
  • 97
  • 1
    AFAIK the error handler in jquery is only called if the HTTP request returns a 4XX or 5XX status code. If you want your page code to always return a 200 status, you need to check the contents in the success handler and call further functions from there. – Dan Smith Mar 03 '15 at 14:30
  • if your error msg is returned from backend then your ajax request was success. If you have cause error, you send back error HTTP header – daremachine Mar 03 '15 at 14:34

2 Answers2

4

You need to send an http status code other than 200:

if($product->GetSerial($serial)) {
    $productInfo = $product->GetSerial($serial)->first();
    header('Content-Type: application/json', true, 200);
    die(json_encode(["error"=> false, "message"=> "Successfully got serial number"]));
} else {
    header('Content-Type: application/json', true, 400);
    die(json_encode(["error"=> true, "message"=> "failed to get serial number"]));
}

Also, when sending json, set the content type accordingly, and never try and manually build a json string, use the built in json_encode function instead, and its a good idea to use die() or exit() rather than echo, to avoid any accidental additional output

That said, although sending appropriate status codes seems like a good idea, you may well find it a lot easier to always return 200 and parse the response, and keep the error handler for unexpected errors

Steve
  • 20,703
  • 5
  • 41
  • 67
  • I just seen your edit, I was originally going to do what you mentioned with parsing it but I was not sure if it was the proper way of doing things. – Yamaha32088 Mar 03 '15 at 14:39
  • @Yamaha32088 well sending a suitable status code if probably semantically correct, and if this api is going to consumed by any other clients, thats probably the way to go. But if you intend to send anything other than a string via the error handler, you will need to write some additional code to parse the result. The choice is yours – Steve Mar 03 '15 at 14:47
1

One option is to set error in backend. Another is taking care in success ajax method of your logic error.

success: function(data, textStatus, jqXHR) {
                if ( data.error == 'false' ) 
                    console.log('success');
                else
                    console.log('error');
            },

So without changes in backend, entire function may look like:

function getProductInfo() {
    var result;
    if($("#serialNumber").val() != '') {
        serialNumber = $("#serialNumber").serialize();
        $.ajax({
            type: "POST",
            url: 'post.php',
            data: serialNumber + "&getSerialNumber=" + 1,
            dataType: 'json',
    success: function(data, textStatus, jqXHR) {
                    if ( data.error == 'false' ) 
                        {
                            console.log('success');
                            result = data.message;
                         }
                    else
                        {
                            console.log('error');
                            result = data.message;
                         }
                },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log("ERROR");
            }
        });
    }
    return result;
}
changtung
  • 1,614
  • 15
  • 19