0

I was looking around for ways to make it but I only seen it being done with ajax and no PHP explanation/usage at all.

What do I mean?: I want the username check validation to be done at real time, means that if the user inserts a username that already exists, it will immediately show an error message.

Example of what I mean:

register.php

if(isset($_POST["reg"]))
{
    $name = $_POST["name"];
    $query = mysqli_query($link, "SELECT * FROM `users` WHERE `name`='$name');
    if(mysqli_num_rows($query))
    {
        ... 
    }
    else
    {
        ...
    }
}

form.html

    <head>
        <script>
         $(document).ready(function(){
             $("#error").hide();
         });
        </script>
    </head>

    <div id="error">
        Username exists.
    </div>

    <form action="register.php" method="post">
        Name: <input type="text" name="name" />
        <input type="submit" name="reg" />
    </form>

(Only the relevant code has been copied for comfort, the other required tags exist in the original code)

I want the #error div to show whenever the username exists (without reloading the page) and to hide whenever everything is okay, and disallow the user to submit the form, I'm not sure how can I do it efficiently.

Thanks in advance.

Michael Naidis
  • 116
  • 2
  • 4
  • 15
  • You need some Ajax code, with your PHP echo'ing back a response. An example here on SO - http://stackoverflow.com/questions/17258541/ajax-username-availability – Sean May 28 '16 at 14:34
  • Can you please explain it to me how it works? I see the code, but an explanation would be nice :) – Michael Naidis May 28 '16 at 14:40
  • Search for tutorials on ajax – charlietfl May 28 '16 at 14:44
  • [jQuery AJAX Basics](http://jayblanchard.net/basics_of_jquery_ajax.html) – Jay Blanchard May 28 '16 at 14:45
  • [Little Bobby](http://bobby-tables.com/) says [your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – Jay Blanchard May 28 '16 at 14:46
  • You use `$.ajax()` to send the value of `` to `register.php`. In `register.php` you check that value and then echo a response if it is available or unavailable. And in the `success: function(response){ }` of your `$.ajax()`you do something with that response, i.e. show your error message or post the form to insert that value. – Sean May 28 '16 at 14:46

0 Answers0