Question

I have a code that checks if the username is available if you want to change. But now I saw that if you update something else such as your password, you can assume to save as the user name already exists. Listed below are the code I use, as you see, I have tried to think of something but did not go well at all.

PHP

$sql = "Select * FROM table WHERE Slug = '$slug' AND ID ='$id' LIMIT 1";
$query = mysql_query($sql);

if(mysql_num_rows($query)>0){    
    echo 'true';  
}else{  
    $e_sql = "Select * FROM table WHERE Slug = '$slug'";
    $e_query = mysql_query($e_sql);
    if(mysql_num_rows($e_query)>0){    
        echo 'false';  
    }else{  
        echo 'false';  
    }   
}   

Jquery/Javascript

 var response;
    $.validator.addMethod(
        "uniqueUserName", 
        function(value, element) {
            $.ajax({
                type: "POST",
                url: "User.php",
                data: {
                'slug': value,
                'id': <?php echo $id; ?>
                },
                dataType:"html",
                success: function(msg)
                {   console.log(msg);
                    response = ( msg == 'true' ) ? true : false;

                }
             });
             return response; 
        },

        "This Name is already used!"
    );

    $("#addSurvey").validate({
        rules: {
            name: {
                required: true,
                uniqueUserName: true
            },
        }
    });
Was it helpful?

Solution

Basically problem is in your $.ajax request.

As you know $.ajax by default perform an asynchronous HTTP (Ajax) request.

Easiest solution for you is to make request synchronous.

To make request synchronous you should set option async: false - in this case code will be executed linearly and you will get return response; only when ajax request is completed.

So basically change part of ajax call to:

 $.ajax({
      type: "POST",
      url: "User.php",
      async: false,
      data: {
        'slug': value,
        'id': <?php echo $id; ?>
      },
      dataType:"html",
      success: function(msg){
        response = msg === 'true';
      }
    });

May be useful:

jQuery.ajax() Documentation

OTHER TIPS

set

response = (( msg == 'true' ) ? true : false);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top