Javascript and PHP

by 5 replies
6
I have a register form and i want to check before submitting if the username is taken or not.

I`m using the following php code:
<?php
include ('connectandselectdatabase.php');
$check = "select id from $table where username = '".$_POST['username']."';";
$qry = mysql_query($check)
or die ("Could not match data because ".mysql_error());
$num_rows = mysql_num_rows($qry);
if ($num_rows != 0) {
echo "Allready taken!";
exit;
}
else {
echo "ok";
}
?>

I`m thing the best would be to use Javascript , something like onmouseout execute the php script , how i can done this , or if not what method to use?

Thanks for any help!
#programming #javascript #php
  • You can use Javascript - I'd definately recommend a Javascript library, such as jQuery, to help you get started and up and running very quickly. There are plugins for such libraries which will let you, on an event (e.g. a time delay, keypress or mouse event) call a PHP file and return a result.

    However, you'll need to consider users who don't have Javascript enabled (depending on the figures you read, this could be 1 in 10 visitors to your site). How will you check whether the username has already been taken for them?

    Typically it's best to have checks when posting the form to check field inputs are valid, usernames are not taken etc (via PHP), and then add Javascript functionality to do these checks as the user completes the form (pre-posting the form).
    • [1] reply
    • Hey there.

      I think the best way to start is to forget about JavaScript for the minute, display your form and page normally, and have the form post to the same page it's on.

      At the top of file you can test whether the form has been posted, and then do your checks. If the name is not available, you can display a message near the form.

      Once this is working you can introduce some JavaScript to post the form (or whatever you want) AJAX style. Take a look at the jQuery Form Plugin - nice and straightforward to use.

      By that stage you should have a good feel for how everything fits together.

      One important note: it's a very good idea to get into the habit of considering security issues. Take a quick look at the PHP function mysql_real_escape_string and from the example you can see why it's a very good idea to use it in your code above.

      There will be other things to consider too, but this is the most important for now I think. A general rule of thumb is to never trust anything that isn't hard-coded :-)

      Here's an amusing cartoon about SQL injection. I posted it elsewhere but it serves as a good reminder:





      Phil.
      • [2] replies

Next Topics on Trending Feed