1

Added header to the PHP code and the catch in the Ajax but still no joy.

I'm having trouble getting my head around handling MySQL errors when using Ajax to handle form submissions. I have the following code:

var url = "save.php"; // the script where you handle the form input.

    $.ajax({
        type: "POST",
        url: url,
        data: $("#frmSurvey").serialize(), // serializes the form's elements.


        success: function(jqXHR, textStatus, errorThrown){

                $('.sequence-container div').hide().delay( 2000 );
                $next.show().delay( 2000 );



        },
        error: function(jqXHR, textStatus, errorThrown){
            if (jqXHR.status === 0) {
                            alert('Not connect.\n Verify Network.');
                        } else if (jqXHR.status == 503) {
                alert('Error: ' + jqHXR.responseText);
            }    else if (jqXHR.status == 404) {
                            alert('Requested page not found. [404] - Click \'OK\' and try to re-submit your responses - if this error box re-appears, call 01255 850051 and we will assist.');
                        } else if (jqXHR.status == 500) {
                            alert('Internal Server Error. [500] - Click \'OK\' and try to re-submit your responses - if this error box re-appears, call 01255 850051 and we will assist');
                        } else if (exception === 'parsererror') {
                            alert('Requested JSON parse failed - Click \'OK\' and try to re-submit your responses - if this error box re-appears, call 01255 850051 and we will assist');
                        } else if (exception === 'timeout') {
                            alert('Time out error - Click \'OK\' and try to re-submit your responses - if this error box re-appears, call 01255 850051 and we will assist');
                        } else if (exception === 'abort') {
                            alert('Ajax request aborted - Click \'OK\' and try to re-submit your responses - if this error box re-appears, call 01255 850051 and we will assist');
                        } else {
                            alert('Uncaught Error.\n' + jqXHR.responseText + ' - Click \'OK\' and try to re-submit your responses - if this error box re-appears, call 01255 850051 and we will assist');
                        }
          }

    }); 

This works fine and handles any erros such as pages missing etc.

However, I am completely stumped how to then handle/ display to the user any errors that might arise when actually submitting to the database.

Currently I've tried this:

if ($mysql_error!="") {
        header('HTTP/1.1 503 Service Unavailable');
                    printf("Unexpected database error: %s\n", $mysql_error);
        mysqli_stmt_close($proc);
        mysqli_clean_connection($link);
        exit();
    }

But as the page is not being shown (as it is being submitted by Ajax) the error message doesn't appear. I think I have to bring that error message back into the Ajax script to display it to the user (is that right?) - and I'm not sure how to do this.

Any pointers/ suggestions?

2 Answers 2

3

I would move all your error logic from jQuery to PHP. You can respond with a simple JSON object that can hold the status (success or error), code (if needed), message, and even data, if you want to provide specific results.

For example, you make a request like this:

$.ajax({
  type: 'POST',
  url: url,
  data: $("#frmSurvey").serialize(),
  success: function(result){
    var json = $.parseJSON(result);
    if(json.response.status == 'success') {
      // do something
    } else {
      // look at message or code to perform specific actions
    }
  }
});

Then in the PHP file processing this request, you build an array with all the aforementioned elements you need (status, code, message, etc). Ultimately, you'll echo something like this:

$result = array(
  'response' => array(
    'status' => 'error',
    'code' => '1', // whatever you want
    'message' => 'Could not connect to the database.'
  )
);    

echo json_encode($result);

The $result array will contain the relevant data based on the checks you make in PHP.

Hope this helps!

Sign up to request clarification or add additional context in comments.

3 Comments

thanks for the reply - appreciated. I'm struggling to get my head around this - mental block. I'm assuming I need to put a success as well as error in the array?
got it - placed the array in both the error and success sections of the PHP code, modified accordingly and it works a treat! Thanks.
One other note, I would make the error reporting more transparent to the user. Log the error and generate an email to you, then provide the user with a simplified message. All the user really needs to know is whether their request worked or not. If there's something they can do to fix it, you can let them know, other than that, a simple "We're sorry, but our application has experienced a problem" will do.
3

Send a 503-Header

<?php
header('HTTP/1.1 503 Service Unavailable');

and your ajax-code should work.

Edit: It will use your fail-code and you can check in the function for the status-code 503.

jqXHR.status

will be 503 and

jqXHR.responseText

will contain your message.

Edit2: js.file

var url = "save.php"; // the script where you handle the form input.

$.ajax({
type: "POST",
url: url,
data: $("#frmSurvey").serialize(), // serializes the form's elements.

success: function(jqXHR, textStatus, errorThrown){
    if (jqXHR.status == 404) {
        alert('Error: ' + jqHXR.responseText);
    }else{
        $('.sequence-container div').hide().delay( 2000 );
        $next.show().delay( 2000 );
    }


},
error: function(jqXHR, textStatus, errorThrown){
    if (jqXHR.status === 0) {
                    alert('Not connect.\n Verify Network.');
                } else if (jqXHR.status == 404) {
                    alert('Requested page not found. [404] - Click \'OK\' and try to re-submit your responses - if this error box re-appears, call 01255 850051 and we will assist.');
                } else if (jqXHR.status == 500) {
                    alert('Internal Server Error. [500] - Click \'OK\' and try to re-submit your responses - if this error box re-appears, call 01255 850051 and we will assist');
                } else if (errorThrown === 'parsererror') {
                    alert('Requested JSON parse failed - Click \'OK\' and try to re-submit your responses - if this error box re-appears, call 01255 850051 and we will assist');
                } else if (errorThrown === 'timeout') {
                    alert('Time out error - Click \'OK\' and try to re-submit your responses - if this error box re-appears, call 01255 850051 and we will assist');
                } else if (errorThrown === 'abort') {
                    alert('Ajax request aborted - Click \'OK\' and try to re-submit your responses - if this error box re-appears, call 01255 850051 and we will assist');
                } else {
                    alert('Uncaught Error.\n' + jqXHR.responseText + ' - Click \'OK\' and try to re-submit your responses - if this error box re-appears, call 01255 850051 and we will assist');
                }
  }

});

save.php:

<?php
header('HTTP/1.1 503 Service Unavailable');
echo('hallo welt');
exit();

result:

Uncaught Error.
hallo welt - Click 'OK' and try to re-submit your responses - if this error box re-appears, call 01255 850051 and we will assist

7 Comments

Hi Markus, not sure what the above will do? The Ajax code works and shows errors when pages aren't there - will the above help with handling error messages that are returned by mysql?
@Homer_J It will cause jQuery to enter the error callback rather than success since the status code is no longer 200.
Thanks to both of you - just wondering where it goes and then, how I still handle/display any messages coming back?
@Markus, ok that makes a little bit more sense - would it be something like header: ('HTTP/1.1 503 Service Unavailable'); - would this be captured in the success or fail section though I wonder?
I'm still unclear as to how it can bring back the PHP error message if there is an error submitting data to the database. I'm utterly lost on this.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.