-1

i'm trying to check if a username exists in the db with ajax. I don't know why it doesn't work i tried many things and still get nothing.

this is the code that i'm actually trying. the php code works but doesn't send the result to the ajax function

html >Registration.php

<input class="form-control" onblur="checkUser()" id="Pseudo" type="text name="Pseudo" value="" required>" 
 <span id="availability" name="availability" value="">  </span>

php >Welcome.php

if(!empty($_POST['Pseudo']))
{

    $pseudo = $_POST['Pseudo'];

    $connexion = mysqli_connect('localhost', 'root', '', 'database');

        if(!$connexion)
        {
            die('Error during connexion ');
        }

    $sql = "SELECT * FROM Web_database WHERE Pseudo='$pseudo'";

    $result = mysqli_query($connexion, $sql);
    echo  mysqli_num_rows($result);

}

Javascript > Registration.php

    function checkUser()
    {
        var Pseudo = $('#Pseudo').val();

          $.ajax({
            url:'Welcome.php',
            method:"POST",
            data:{Pseudo:Pseudo},

             success:function(data)
             {
                  if(data == '0')
                    { 
                       $('#availability').html('Pseudo correcte');
                    }
                    else
                    {
                        $('#availability').html('Pseudo déja utilisé');
                    }

            }


    });

}

naigu
  • 1
  • Did you checked what is the value being passed to the server through browser developer tools. All the ajax/backend calls will be recorded in network tab of browser console. Just check whether the value is getting passed to the server call and let us know – Sivaprasath Apr 12 '19 at 17:15
  • Regardless of it working or not, taking input straight from the request and putting it into an sql statement is a **very bad** idea, and is subject to sql injection attacks. – Taplar Apr 12 '19 at 17:21

1 Answers1

0

First of all, you can probably optimize your SQL:

$sql = "SELECT COUNT(*) FROM Web_database WHERE Pseudo='$pseudo'"

Instead of using mysqli_num_rows().

You are also opening yourself up to SQL injection unless you use prepared statements.

As for your AJAX, it doesn't seem to be wrong. I found this question to be very similar so you might want to check that out. When in doubt, console.log() the response from PHP to see what's actually being returned. Or better yet, add a breakpoint.

Luke
  • 186
  • 1
  • 7