Before continuing, SELECT * FROM 'users' WHERE 'username' = '. $_POST['username'];
is just ASKING for a SQL Injection. I suggest you use PHP Data objects.
So as I understood I must pass the POST values via $.ajax too, correct? If yes, how I will be able to access them via validation.php file?
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.
$.post('validation.php',{username: $('#username').val()}, function(data){
if(data.exists){
//tell user that the username already exists
}else{
//username doesn't exist, do what you need to do
}
}, 'JSON');
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()
to validation.php
and expect a JSON
response. When the request is finished, the callback function will be executed with data
being the response from the request. Because we specified that that response will be JSON
, we can access it just like a native object in javascript. Now let’s move to validation.php
Like 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.
//set the headers to be a json string
header('content-type: text/json');
//no need to continue if there is no value in the POST username
if (!isset($_POST['username'])) {
exit;
}
//initialize our PDO class. You will need to replace your database credentials respectively
$db = new PDO('mysql:host=DATABASE_HOST;dbname=DATABASE_NAME;charset=utf8mb4', 'DATABASE_USERNAME', 'DATABASE_PASSWORD');
//prepare our query.
$query = $db->prepare('SELECT COUNT(*) FROM users WHERE username = :name');
//let PDO bind the username into the query, and prevent any SQL injection attempts.
$query->bindParam(':name', $_POST['username']);
//execute the query
$query->execute();
//return the JSON object containing the result of if the username exists or not. The $.post in our jquery will access it.
echo json_encode(array('exists' => $query->fetchColumn() > 0));
Now to recap, our jQuery script will post to validation.php
where it selects a username from the database. It will return a JSON
object that has a key of exists
that 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.