tags:

views:

145

answers:

2

I'm trying to build a registration system using PHP and the AJAX components of jquery.

My jQuery takes the values of the username and password fields and makes a POST request to the PHP script, which grabs the values using $_POST and saves them to the database.

Of course, i'm wanting to make sure that there aren't any duplicate usernames, and beyond using the PHP mysql_error() function, i wasn't sure how to do this.

So i want to set my PHP to first check for entries in the database with the username the person enters in the form, if it exists, i'd like to return a custom error message to the user using the php return() feature.

How can i use jQuery to first POST the values to the script, and then return any data/ custom error messages that i am creating with return();

By the way, security is not an issue here.

+1  A: 

Simplest way would be to make a page, for example, post.php. post.php will do all the checking and stuff you want and, I know you want to use return, but just echoing the stuff back would be the absolute easiest. So, echo any error or even a value (for example, you can echo back -1 for a false or a 1 for a true).

The jQuery side is pretty simple:

$('form').submit(function(){
  $.post('post.php',{username:$('#username').val(),password:$('#password').val()},function(data){

  //username and password == $_POST['username'] && $_POST['password']
  //data will now equal anything you echo back. So, lets say you did as my example and used -1 for an error

    if(data==-1){alert('ERROR');}

  });
  return false;
});

If there is an error you will get an alert otherwise nothing will happen at all. Now you could do an else{} and have whatever you want for if there is no error.

Oscar Godson
A: 

For the ajax call:

$.ajax({
    type: "POST",
    url: url,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: "{'username': " + username + "}",
    success: function(result) {
        var myData = JSON.parse(result.d);
    }
 });

On the php side just use echo to return the json, either an error message or the username/id perhaps.

echo "{'error': '".$mysql_error."'}";

echo "{'username': '".$username."'}";

By using JSON you can just look for the error property.

I use a json parser from http://json.org (look toward the bottom of page).

James Black