skolind
skolind

Reputation: 1754

jQuery, AJAX - How to tell if script returned false

I'm using jQuery and AJAX to validate my form when someone creates a new user on my website. I'm programming in OOP PHP, together with the jQuery and AJAX. I'm using this code:

$.ajax({  
        type: "POST",  
        url: "includes/classes/handler.php?do=addLogin",
        data: dataString,  
        success: function() {
            $('.sideBarNewUserWrap').fadeOut();
        }
    });  
    return false;

But how do I return an error message, if the e-mail already exists?

Hope it's info enough, else I'll just add some more. Thanks in forward :)

* UPDATE *

This is my PHP checking if email exists:

$email_count = mysql_num_rows($check_email);
    if($email_count){
        return false;
    }

* UPDATE *

      success: function(data){

            if(data.error){
                $('.sideBarNewUserWrap').fadeOut();
            } else {
                $('.sideBarNewUserError-email').fadeIn();
            }

Now this looks pretty much as a failure because. if(data.error) then it's okay?

Shouldn't it be something like:

if(date.error){
  //Error message
}

And not the other way around?

Well, If I try to enter an email which already exists, it tells me as it should, but why does this work? In my eyes I'm doing something wrong here?

Upvotes: 2

Views: 8009

Answers (4)

user1988125
user1988125

Reputation:

You can return data by using an echo in your handler.php file. To receive this in jQuery just place a parameter in the success function of the Ajax function.

success: function(returnedValue)
{
// Here you check if returned value e.g. "returnedValue == 1"
}

Upvotes: 1

Manuel Rauber
Manuel Rauber

Reputation: 1392

You can get the response in the function:

$.ajax({  
        type: "POST",  
        url: "includes/classes/handler.php?do=addLogin",
        data: dataString,  
        success: function(response) {
            if (response == "ok")
            {
                 $('.sideBarNewUserWrap').fadeOut();
            }

            else
            {
                // error happend
            }
        }
    });  
    return false;

You can return string, int in PHP or even XML, JSON, whatever you want to validate on client side

Upvotes: 1

Alex Pliutau
Alex Pliutau

Reputation: 21957

php:

$result = array('error' => true); // or $result = array('error' => false);
echo json_encode($result);

js:

success: function(response) {
    if (response.error) {
        // ...
    }
}

Upvotes: 2

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123397

basically in the handler.php you should verify whether email already exists or not and then send to the client (at least) two different responses (eg. 0: email exists, 1:ok).

In the success callback you can read the response data so you can tell the user the operation status

Upvotes: 0

Related Questions