views:

39

answers:

4

Can some one please tell me where I have gone wrong. What ever I 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'])):
$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;

Thank in adance

A: 

Try to debug what response you get from the ajax.

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

Sarfraz
A: 

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

fmsf
A: 

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/

ILMV
+1  A: 

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);
Aaron