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?
 
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
 
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
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
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
 
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
 
Eddie ShipmanAll-around developerCommented:
Selected best answers
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.