I want to add a feature to my registration form which I will check if that username already exists in the database.
I have a few questions about AJAX –
-
I want to create an AJAX request on_change function, so something like this –
$('#username').change(function() { $.ajax({ url: "validation.php" }); });So, as far as I understood, I must have all validations made in PHP inside the validation.php file, correct? Is there any special validation needed or can it be just simple validation with a sql statement –
SELECT * FROM 'users' WHERE 'username' = '. $_POST['username']; -
So as I understood I must pass the POST values via $.ajax too, correct? If yes, how will I be able to access them via the validation.php file?
-
After I get the results in validation.php file, how can I pass them back (true or false — exists or doesn’t exist)? I will need to pass them back, and then do an if check, if it’s true – show an error that the username already exists, otherwise, don’t show anything?
Before continuing,
SELECT * FROM 'users' WHERE 'username' = '. $_POST['username'];is just ASKING for a SQL Injection. I suggest you use PHP Data objects.Because this is a simple request, I suggest you use JQuery’s method
$.post(). Here’s a sample based off of what you’re trying to do.jQuery’s post method takes 4 parameters
$.post(url, data, callback, datatype). In the example above, we will be posting the username with$('#username').val()tovalidation.phpand expect aJSONresponse. When the request is finished, the callback function will be executed withdatabeing the response from the request. Because we specified that that response will beJSON, we can access it just like a native object in javascript. Now let’s move to validation.phpLike I stated above, I suggested you use PDO for your database driver. So in this example, I will show you a basic usage of it.
Now to recap, our jQuery script will post to
validation.phpwhere it selects a username from the database. It will return aJSONobject that has a key ofexiststhat is a boolean indicating if the username already exists as a row in your database. When the request is complete via jQuery, you can do what you need based off the result of the query.