Nick
Nick

Reputation: 4462

Validation to check if username already exists in database without loading new page

I have designed a registration form which you can see here. It includes a javascript validation script which handles everything apart from checking to see if the username already exists on a MySQL database.

The way this is currently handled is by a separate PHP page (register.php) which is called on submitting the form, and checks against the MySQL database, displaying some text if the username already exists with a link back to the html page with the registration form on.

I am wondering if there is a way to not have to load the new PHP page, but append an error message to the html form (as with all of the other validations) when the user tries to submit the form but the username already exists. Is the only way to do this to not have a separate PHP that the form posts to, but rather include all of the PHP from the second file (which connects to the database, checks the username, and adds the new user) in the main registration page?

I hope this is clear!

Thanks,

Nick

Upvotes: 1

Views: 6078

Answers (2)

brian wilson
brian wilson

Reputation: 495

i think this is what you are looking for exactly:

http://www.99points.info/2010/06/live-availability-checking-with-ajax-and-jquery/

Upvotes: 0

jeschafe
jeschafe

Reputation: 2683

I assume you're talking about an ajax request? If you don't know what that is go ahead and google it you'll find plenty of information on it.

I always use a javascript library like jQuery or dojo which makes ajax a lot easier but maybe you don't want to add the overhead of an entire javascript library for a little javascript use.

The basic premise is:

  1. Your javascript sends a request to the server, in this case to your register.php page.
  2. The register.php file runs with the params you passed it in your ajax request.
  3. The javascript receives the response from the register.php file. In this case it'd probably be easiest to do something like:

    • If the username does exist return false, which then your javascript function can use on a callback to pop up a validation error.

    • If the username does NOT exist, then the register.php file could register/log them in and will return true to the javascript. The javascript will then redirect the user to the page that they were supposed to go to as if nothing ever happened in the background.

For coding purposes here's some psuedocode on how I would do it with jQuery:

$.ajax({
  url:'register.php?username=theUsersName',
  dataType:'html',
  success:function(data){
    if (data)
      --redirect to homepage
    else
      --pop up validation error
  }
});

Upvotes: 3

Related Questions