How to catch sql error with Ajax.

My PHP script returns an SQL error:
SQLSTATE[HY000] [2002] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
whenever it cannot connect to the database to fetch the expected result.  This SQL error always comes up on my webpage and I would like to present it with something nice to my page  visitors. But my Ajax seems not to be working as it always comes up with that error each time I lost db connection. Below is my ajax:

function feedUpdate() {
    //$(document).ready(function() {
    $.ajax({
        type: 'POST',
        url: 'functions/feedUpdate_New.php',
        success: function(data) {
            if (data) {
                document.getElementById("homeFeed").innerHTML = data;
            } else {
                document.getElementById("homeFeed").innerHTML = "We are not able to get the feed at this time";
            }
        }
    });
    //});
}
feedUpdate();

Open in new window


NOTE: The PHP script is - feedUpdate.php and it contains the expected result. The above ajax returns the required result from the script if I have db connection. But once the db connection is lost, it pops up the sql error on the web page. Please how can I pick that sql error and present something like:
We are not able to get the feed at this time
Adebayo OjoRegional Network ManagerAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ganesh GuruduSenior ConsultantCommented:
Did you tried like this.

$(document).ajaxError(function(){
    alert("An error occurred!");
});

OR

if(mysql_query($query)){
    $response_array['status'] = 'success';  
}else {
    $response_array['status'] = 'error';  
}

also check below URL for reference.
https://www.sencha.com/forum/showthread.php?238414-Ajax-Request-Error-Handling
0
Dave BaldwinFixer of ProblemsCommented:
AJAX does not see that as an error but as a 'valid return'.  You have to handle that in the PHP code.
1
Scott Fell, EE MVEDeveloper & EE ModeratorCommented:
As Dave said, that is your valid return and it is your error.   The issue is your php code on feedUpdate_New.php couldn't connect to the database.
0
Bootstrap 4: Exploring New Features

Learn how to use and navigate the new features included in Bootstrap 4, the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites.

Adebayo OjoRegional Network ManagerAuthor Commented:
@Dave Baldwin,
Yes, AJAX saw everything from the PHP as valid return, but can't I separate the return result from PHP like below:?

function feedUpdate() {
    //$(document).ready(function() {
    $.ajax({
        type: 'POST',
        url: 'functions/feedUpdate_New.php',
        success: function(data) {
            if (data == "SQLSTATE[HY000] [2002]") {
                document.getElementById("homeFeed").innerHTML = "We are not able to get the feed at this time";
            } else {
                document.getElementById("homeFeed").innerHTML = data;
            }
        }
    });
    //});
}
feedUpdate();

Open in new window


NOTE: When I did this, it didn't still work, as the string "We are not able to get the feed at this time" were been output by AJAX whether I have DB connectivity or not. So my question again is, how can I separate the PHP result on AJAX and output the expected result on my webpage?
0
Dave BaldwinFixer of ProblemsCommented:
'data' will never equal just "SQLSTATE[HY000] [2002]", it will be the whole string you posted above.
0
Eddie ShipmanAll-around developerCommented:
Yeah, this should catch it, although I would catch it in the PHP and return a 500 exception making the AjaxError be thrown:

if (data.indexOf("SQLSTATE[HY000]") > -1) {

Open in new window

0
hieloCommented:
My suggestion would be to send an error status code whenever you encounter problems.  On the server side you need to enable PDO exceptions and execute your statements in a try-catch clause. If it makes it to the "catch" clause, then send a 500 status code:
try
{
  $pdo = new PDO('mysql:host=localhost;dbname=someTable', 'username', 'password', array(  PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION) );

  // your query should follow here...
}
catch(Exception $ex){
    header( $_SERVER['SERVER_PROTOCOL'] .' 500 Internal Server Error');

   // you can notify an admin about the error
  mail("webmaster@domain.com","Error executing query", $ex->getMessage(), "From: no-reply@domain.com");

  // if you want to send a custom description you do it here and on the client side you retrieve it in the "error" callback
  // from xhr.responseText
   die("Server problems.");
}

Open in new window


 The jquery $.ajax() will interpret that as an error and invoke the "error" function/handler.
function feedUpdate() {

    $.ajax({
        type: 'POST',
        url: 'functions/feedUpdate_New.php',
        success: function(data) {
                document.getElementById("homeFeed").innerHTML = data;
        },
        error:function(xhr, ajaxOptions, thrownError){
                document.getElementById("homeFeed").innerHTML = "We are not able to get the feed at this time";
        }
    });
}
feedUpdate();

Open in new window

1

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Eddie ShipmanAll-around developerCommented:
Selected best answers
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
SQL

From novice to tech pro — start learning today.