开发者

jquery ajax form function(data)

Why do I get the answer "no"?

jQuery to send data to php query

 $j.post("logincheck.php",{ 
username:$j('#username').attr('value'),
password:$j('#password').attr('value'),
rand:Math.random() } ,
function(data) {
  if(data=='yes') {alert('yes');}
  else {alert('no');}
  }
 );

Here is the php query

if(isset($_POST['username']))开发者_JAVA技巧:
$username  = $_POST['username'];
$password  = $_POST['password'];
$posts   = mysql_query("SELECT * FROM users WHERE username='$username'");
$no_rows  = mysql_num_rows($posts );
while($row  = mysql_fetch_array($posts)): 
print 'yes';
endwhile;
else:
print 'no';
//header('location: index.php');
endif;
endif;


It appears from your php code that if the user has multiple posts, then 'yes' will get printed multiple times. This means that this statement will only be true if the user has exactly one post:

if(data == 'yes')

Change your else clause in the javascript to the following to see what is getting returned by the ajax call and left us know what you get.

alert(data);


Try replying this instead:

{
 "valid" : "yes" // or "no"
}

and on your post:

$j.post(url,{your stuff}, function(data){
   if(data.valid==="yes"){...}
},"json");

And use .val() instead to fetch the input


Try to debug what response you get from the ajax.

Also, looking at your script, you are adding an extra endif; at the end.


What about using .val() instead of .attr('value').

I mean, it's a shot in the dark, but the attribute value doesn't update when you type anything in, it's used to set the default value of the form, instead the .val() method should get the value of the input.

PS: Have you actually tested that your PHP script is receiving the data correctly?

Edit After checking it in jsFiddle it turns out both should work fine :-)

http://jsfiddle.net/cwPPp/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜