Raccoon
Raccoon

Reputation: 1427

$.ajax error cannot catch thrown exception from php

$.ajax({
    type: "POST",
    url: "functions/add_vendor.php",
    data:
    {
        vendor_info_json : vendor_info_json
    },
    success:function(result)
    {
        alert('Successfully Done.')
        location.reload();
    },
    error: function(jqXHR, textStatus, errorThrown){
        alert('Error Message: '+ textStatus);
        alert('HTTP Error: '+ errorThrown);
    }
})

This is the jquery code I'm working on. And the following is the add_vendor.php file being called.

<?php
include_once('../models/VENDOR_DB_MANAGER.php');

$vendor_info_json = $_REQUEST["vendor_info_json"];
$DB = new VENDOR_DB_MANAGER();
$DB->connectTo('BBY');
try
{
            //This ALWAYS returns false to test the code.
    if($DB->insertDataToTable('mfVendor', $vendor_info_json))
    {
        $DB->disconnect();

        header('Content-Type: application/json');
        $data = json_encode($result);
        echo $data;
    }
    else
    {
        throw new Exception("Error has been detected.");

    }
}
catch (Exception $e)
{
    header("HTTP/1.1 500 Internal Server Error");
            echo "Exception occurred: " . $e->getMessage();
}
?>

Ok, That 'if($DB->insertDataToTable('mfVendor', $vendor_info_json))' part always is false to test $.ajax's error handling code. No matter what I do, error: callback is not working even if the php code throws an exception all the time.

What are the problems I'm missing here? :(

Upvotes: 2

Views: 1869

Answers (1)

Tam&#225;s Pap
Tam&#225;s Pap

Reputation: 18273

When your server throws an Internal Server Error, from Javascript side it's still a success. In your success function you have to check the response's status code, and handle it accordingly.

Upvotes: 1

Related Questions