First things first: It’s been a while I posted about Programming.
Second things second: The topic sounds weird, because jQuery and PHP are two languages with different purposes.
In my line of coding, I’ve discovered its too naive of programmers to be ‘troubling’ the server every time. How? Simple! You want to check if a record exists in a database, you go through the server. You want to validate, the same procedure. And so on..
JavaScript, jQuery, AJAX… all came to solve part of these problems.. hence, I’ll be recommending swapping PHP for jQuery once in a while.
Recently, while working on a mega project, I wanted to capture an exception of duplicate signup. This gave me a lot of headache (you might think its an easy and straight-forward task, you’re not wrong). I eventually made a headway when I rubbed minds with jQuery.
To check if a record exists in your database, you set the following:
$(document).ready(function(){
$(‘#username’).keyup(username_check);
});
//this gets the function ready with name ‘username_check’ and parameter ‘username’
Afterwards,
function username_check(){
var username = $(‘#username’).val();if(username == “” || username.length < 4){
$(‘#username’).css(‘border’, ‘3px #CCC solid’);
$(‘#tick’).hide();
}else{jQuery.ajax({
type: “POST”,
url: “check.php”,
data: ‘username=’+ username,
cache: false,
success: function(response){
if(response == 1){
$(‘#username’).css(‘border’, ‘3px #C33 solid’);
$(‘#tick’).hide();
$(‘#cross’).fadeIn();
$(“#AssignTPM”).attr(“disabled”, “disabled”);
}else{
$(‘#username’).css(‘border’, ‘3px #090 solid’);
$(‘#cross’).hide();
$(‘#tick’).fadeIn();
$(“#AssignTPM”).removeAttr(“disabled”, “disabled”);
}}
});
}}
//the lines above set the event to fire if the record exists or not. Also, it loads two images: ‘tick’ and ‘cross’ – tick for non-existence and cross for otherwise.
It also disables the submit button, so that users cannot submit invalid data but enables it when input has been validated.
‘check.php’ is the php file that queries the database for the existence of the record. The contents are these:
$username = trim(strtolower($_POST[‘username’]));
$username = mysql_escape_string($username);$query = “SELECT username FROM usernameCheck WHERE username = ‘$username’ LIMIT 1”;
$result = mysql_query($query);
$num = mysql_num_rows($result);echo $num;
mysql_close();
You can thereafter go ahead to add designs in the homepage. In may case, this is what I have:
<style>
#username{
padding:3px;
font-size:18px;
border:3px #CCC solid;
}#tick{display:none}
#cross{display:none}</style>
The ‘display:none’ makes sure that the two images ‘tick.jpg’ and ‘cross.jpg’ are not displayed by default.
Note: include the two images immediately after the field you’re validating, like this:
<img id=”tick” src=”tick.png” width=”16″ height=”16″/>
<img id=”cross” src=”cross.png” width=”16″ height=”16″/>
Doing this, you’ve successfully bypassed the headache of pestering the server!