开发者

Getting data back AND $POSTing data using jQuery.Ajax

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开发者_JS百科 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜