Sesama Sesame
Sesama Sesame

Reputation: 279

ajax call to check duplicate data

Here is the form to have ajax check out user existence.

<!DOCTYPE html>

<html>
    <head><title>Register new user!</title>
    <script src="jquery-1.7.1.min.js"></script>
    </head>
    <body>
        Username:
        <input type="text" name="username" id="username"/><span id="user"></span><br/>
        Password:
        <input type="password" name="password" id="password"/><br/>
        <input type="button" value="Register" name="submit" id="submit" onclick="register_user();"/>
    </body>
    <script>
        function register_user()
        {
            $.ajax(
                {
                    type:"POST",
                    data:username,
                    url:"userexists.php"                    
                })
            .fail(function()
                  {
                    $('#user').html("This user already exists");
                  }
            );                
        }
    </script>
</html>

And here is the userexists.php module

<?php
    // connection to the db
    define(IPHOST,"localhost");
    define(DBPASSWORD,"");
    define(DBUSER,"root");
    define(DATABASE,"ajaxtest");
    define(TABLENAME,"at");

    $conn=mysql_connect(IPHOST,DBUSER,DBPASSWORD) or die(mysql_error());
    mysql_select_db(DATABASE) or die(mysql_error());
    $username=$_POST('username');
    $sql="SELECT username FROM ".TABLENAME." WHERE username=".$username;
    $query=mysql_query($sql);
    if(0!=mysql_numrows($query))
    {
        //
    }
    else
    {

    }
?>

But I am stuck to really figure out how the ajax function actually works, what should I enter the blank field after I know that the entered username has been used, for example ? I don't understand ajax at all.

[UPDATE] Thank you, I understand it now, I have got several answers, don't know which one to choose as the best reply. No option to choose all.

Upvotes: 2

Views: 15011

Answers (4)

Menztrual
Menztrual

Reputation: 41597

Since you're new to AJAX, let me try and help you a bit better with some explanations as we go.

AJAX stands for Asynchronous Javascript And XML. Using it, you can make a request to another page and have your original page behave differently according to the results returned by the other page.

So how is this useful? Well; You could set an onblur even on a 'username' field to check a remote script to see if a username is already in use. (Which you are already doing in your current setup. Good work!)

Firstly; the .fail() is telling your current page "If the ajax request fails, lets do this code". This is called a callback. A callback is a function of javascript code to execute when the asynchronous request is finished.

So what you want to actually do is use the .done() method. This tells your jQuery request "Hey, when you're done doing this request, do this chunk of code. While you're doing that, im going to sit here and handle anything else that happens".

So you can see there is a slight difference between using .done() and .fail(), however I can see how you can be easily confused with .fail() being new to ajax.

So lets get back to your current problem. Lets modify the ajax to something more like this:

$("#submit").click(function()
{
    $.ajax({
      type: "POST",
      data: "username="+$("#username").val(),
      url: "userexists.php"                    
    })
    .done(function(response){
        $('#user').html(response);
    });
});

What this does is bind an onclick handler for your submit button with the id "submit". So now you can remove onclick="register_user". Secondly, it says, "Hey webpage, go send userexists.php the username textbox value with the parameter name username. When you've finished that request, set the html of #user to the response.

So off it goes and does it.

Now your PHP file, you can do:

<?php
    // connection to the db
    define(IPHOST,"localhost");
    define(DBPASSWORD,"");
    define(DBUSER,"root");
    define(DATABASE,"ajaxtest");
    define(TABLENAME,"at");

    $conn = mysql_connect(IPHOST,DBUSER,DBPASSWORD) or die(mysql_error());
    mysql_select_db(DATABASE) or die(mysql_error());

    $username = mysql_real_escape_string($_POST['username']); // Stop some MySQL injections

    $sql="SELECT username FROM ".TABLENAME." WHERE username='$username'";
    $query=mysql_query($sql);
    if(mysql_numrows($query) == 0)
    {
        echo 'Username is available!'
    }
    else
    {
        echo 'Sorry, username is in use.';
    }
?>

So once your script does its query, if it finds a result it will say in the HTML div "Username is available!". Otherwise, if it finds a match, it says "Sorry, username is unavailable".

Hope this helps you understand ajax a little better!

Upvotes: 3

user899205
user899205

Reputation:

You have a lot of mistakes in your code, try codes below:

<!DOCTYPE html>

<html>
    <head><title>Register new user!</title>
    <script src="jquery-1.7.1.min.js"></script>
    </head>
    <body>
        Username:
        <input type="text" name="username" id="username"/><span id="user"></span><br/>
        Password:
        <input type="password" name="password" id="password"/><br/>
        <input type="button" value="Register" name="submit" id="submit" onclick="register_user();"/>
    </body>
    <script>
        function register_user()
        {
            $.ajax({
                type: "POST",
                data: {
                    username: $('#username').val(),
                },
                url: "userexists.php",
                success: function(data)
                {
                    if(data === 'USER_EXISTS')
                    {
                        $('#user')
                            .css('color', 'red')
                            .html("This user already exists!");
                    }
                    else if(data === 'USER_AVAILABLE')
                    {
                        $('#user')
                            .css('color', 'green')
                            .html("User available.");
                    }
                }
            })              
        }
    </script>
</html>

And for your php code:

<?php
    // connection to the db
    define(IPHOST,"localhost");
    define(DBPASSWORD,"");
    define(DBUSER,"root");
    define(DATABASE,"ajaxtest");
    define(TABLENAME,"at");

    $conn=mysql_connect(IPHOST,DBUSER,DBPASSWORD) or die(mysql_error());
    mysql_select_db(DATABASE) or die(mysql_error());

    $username = mysql_real_escape_string($_POST['username']); // $_POST is an array (not a function)
    // mysql_real_escape_string is to prevent sql injection

    $sql = "SELECT username FROM ".TABLENAME." WHERE username='".$username."'"; // Username must enclosed in two quotations

    $query = mysql_query($sql);

    if(mysql_num_rows($query) == 0)
    {
        echo('USER_AVAILABLE');
    }
    else
    {
        echo('USER_EXISTS');
    }
?>

Upvotes: 2

Koga
Koga

Reputation: 135

Function .fail in ajax is used when server return unexpected datas. But your php code dont return anything. Use something like this:

function register_user()
    {
        $.ajax(
            {
                type:"POST",
                data:username,
                url:"userexists.php"                    
            })
        .done(function(_return)
              {
                if(_return)                                                                                                                                                               
                {
                   if(_return['status']=='yes')
                   {
                     $('#user').html(_return['msg']);
                   }
                 }
              })
        .fail(function());                
    }

And in php:

if(0!=mysql_numrows($query))
{
      $return = array('status'=>'yes',
                      'msg'=>"User alredy exist");

      echo json_encode($return);
      return true;
}

Now you can add more conditions with many statuses and parse it in javascript.

Upvotes: 0

Yaniv Peer
Yaniv Peer

Reputation: 161

It's technically up to you. (For example) You could return a "1" for "user exists" and "0" for "user doesn't exist", or return a more detailed XML. The client app (Javascript) will read the returned result and print out an appropriate message to the user.

The .fail method should be used in case your function actually fails (server side error etc). So it doesn't seem appropriate for what you're trying to do. I would put in your ".done()" code a test of the returned values as described above and print out the correct message.

Javascript:

.done(function ( data ) {
  if(data == "0")
    alert("Your username is OK");
  else
    alert("Your username is already used");
});

PHP:

if(0!=mysql_numrows($query))
{
    echo "0";
}
else
{
    echo "1";
}

Upvotes: 0

Related Questions