1
 $("#submit").click(function(){
    $.ajax({
       type: "POST",
       url: "session.php",
       data: "name=John123&location=Boston",
       success: function(a, msg2){
          $('#feedback').removeClass().addClass('success').text(a +' '+msg2).fadeIn('slow');

       },

         error: function(a, b, c){
              $('#feedback').removeClass().addClass('error').text('This is' +b).fadeIn('slow');
           },

I'm trying to invoke error function using the following code in PHP:

if ($_POST['name'] != "John") {
        $message['error'] = true;
        $message['message'] = "Hmm, please enter a subject in the subject field.";

        echo json_encode($message);
}
else
{
    echo $_POST['name'];
}

But I'm always getting success function invoked. Is there any way i can get error function invoked.

2 Answers 2

2

You need to set the HTTP status code to 500 (or anything else >= 400) to indicate that there was an error.

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

1 Comment

Thanks. But tell me how should i set this code in PHP so that it returns error and invoke the error function.
1

Why won't you do something like this:

$("#submit").click(function(){
    $.ajax({
        type: "POST",
        url: "session.php",
        data: "name=John&location=Boston",
        success: function(a, msg2){
            if(a.error) {
                $('#feedback').removeClass().addClass('error').text('This is' +a.message).fadeIn('slow');
            }
            else {
                $('#feedback').removeClass().addClass('success').text(a.name +' '+msg2).fadeIn('slow');
            }
        }
    });
});

And:

if ($_POST['name'] != "John") {
    $message['error'] = true;
    $message['message'] = "Hmm, please enter a subject in the subject field.";
}
else
{
    $message['error'] = false;
    $message['name'] = $_POST['name'];
}
echo json_encode($message);

The error function is invoked only when the ajax fails, so instead you can check if the ajax returned that the error exists or not.

1 Comment

Yes i can do that and it is just the alternative way. But you know what if i get any error while validating the data the error message will be parsed through "success" function, which I feel is not a good programming practice.

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.