1

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'])):
$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;
3
  • Is the php code complete or is there something around? Have you tried to look into data object to see what kind of info it does return? PS Why dont'you use .val() method instead of .attr('value')? Commented Apr 15, 2010 at 12:30
  • Just as a side note, I wouldn't send a password value over a GET request unless it's totally unavoidable. Commented Apr 15, 2010 at 12:31
  • did you try to alert data?are you echoing yes from the server side? Commented Apr 15, 2010 at 12:32

4 Answers 4

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

Try to debug what response you get from the ajax.

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

Comments

0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.