Alex Eyler
Alex Eyler

Reputation: 11

How to check input values against SQL database BEFORE submission?

I want to be able to check if a user-name is not already taken before it is submitted. I've thought about using Javascript to get the value of the input field but how would I compare that to my SQL database?

Basically, the question boils down to a couple of different questions:

  1. Can I somehow get the values of an input-field through PHP BEFORE submission?

  2. IF NOT, then can I somehow use a Javascript variable in PHP?

  3. IF NOT, is there something else I can do?

If I can't do this, it's no big deal, I just always see sites that check to see if a field is valid run-time instead of having to reload the page or going to an error page, which is something that I definitely want to do as well.

NOTE: I already know how to check to see if a user-name is taken, I just want to know if I can do it run-time, so there's no need to supply me with the SQL code haha.

Thanks!

Upvotes: 1

Views: 18508

Answers (2)

DKSan
DKSan

Reputation: 4197

You can achieve that by using ajax. The following example makes use of JQuery and its ajax function. The serverside script has to be written by you and should check the provided username against your database.

$.ajax({
  type: "POST",
  url: "your_ajax_function.php",
  data: "username=" + $('#id_of_username_input'),
  success: function(retval){
    if (retval == true)
      // Username not in use, tell your visitor
    else {
      // Username in use, tell your visitor to change
    }
  }
}};

The returnvalue depends on your serverside-script and may be just the other way round. You can return whatever you want.

Upvotes: 0

key2
key2

Reputation: 428

Anon is right. You have to use ajax for this purpose. You can't simply use your javascript variable in php. Use ajax in your javascript validation and throw warning message if username already exist in your database.

For reference check out this link http://www.9lessons.info/2008/12/twitter-used-jquery-plug-in.html and http://web.enavu.com/tutorials/checking-username-availability-with-ajax-using-jquery/

Upvotes: 1

Related Questions