Jony Kale
Jony Kale

Reputation: 189

jQuery POST handling errors

Explanation

I am sending a POST, and in PHP I am checking if username already exists in database. If yes, return an error.

But the thing is, I can't use the same function(data) because I want the error to be located in another div.

$.post("events.php?action=send", { data :  $(this).serialize() }, function(data) 
{
    $("#processing").html('');  
    $("#comments").html(data);
});

Problem

I can't have two variables in anonymous function, like function(data, error), then how am I supposed to fetch the 'error' PHP printed e.g 'User already exist's in database', and then put it in the #errors div?

Upvotes: 0

Views: 1028

Answers (3)

Johan
Johan

Reputation: 35194

It depends on how you are handling the error in your PHP code.

In order to even end up in the error handler you need to set the HTTP statuscode to "5XX".

What you probably want to do is to serialize an error object in case the user already exists, and handle it in the success handler like you are doing now:

PHP:

header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');

$data = array('error' => 'something went wrong');
echo json_encode($data);

JS:

function(data){

    if(data && data.error){
       //there was an error, handle it here
       console.log(data.error);
    } else {
       //do something else with the user
       console.log(data);
    }

}

Upvotes: 2

jithujose
jithujose

Reputation: 551

I suggest you to return data as a json string from your server. If you do that, you can get an object from $.parseJSON(data);

// In your php code
$result = new stdClass();
$result->userExists=false;

echo json_encode($result);

Now inside your anonymous function:

// Javascript
data = $.parseJSON(data);
console.log(data);

if (data.userExists) alert("User exists!");

Upvotes: 0

inJakuzi
inJakuzi

Reputation: 151

In PHP you can return json error, like print '{"error":'.json_encode($error).'}' and then, in your js put in desired div

$.post("events.php?action=send", { data :  $(this).serialize() }, function(data) 
{
  $("#processing").html('');
  $("#comments").html(data);
  $("#error").append(data.error);
});

Upvotes: 0

Related Questions