简体   繁体   中英

ajax login form doesn't work

I am trying to pass user's info from mysql to the webpage, if the user has logged in but can't get it to work. If I put a wrong email or password it will show the error message but if the credentials are ok it would do anything...

on php file:

$sql = "SELECT * FROM users WHERE email='$l_email' AND password='$l_password'";
$query = mysql_query($sql) or die ('Error: ' . mysql_error());
$num_rows = mysql_num_rows($query);
if($num_rows < 1)
{
    echo "You have entered a wrong email or password!";
}
else {
$memberInfo = array();
while( $row = mysql_fetch_array( $query ) )
{
    $memberInfo[] = $row;
}
return $memberInfo;
echo json_encode( $memberInfo );
//echo "1";
}

on js file:

 $.post("./includes/checkOut.php",{ l_email1: l_email, l_password1: l_password },
          function(data) {
           if(data=='1')
            $("#checkOut_form")[0].reset();
            $("#login_returnmessage").html("");
            $("#memberInfo").hide("");
            var memberInfo = jQuery.parseJSON(memberInfo);
            for( var i in memberInfo )
            {
            var f_name = memberInfo[i].f_name;
            var l_name = memberInfo[i].l_name;
            var phone = memberInfo[i].phone;
            }
            $("#loggedinInfo").show("");
            $('#_f_name').val(f_name);
            $('#_l_name').val(l_name);
            $('#_email').val(l_email);
            $('#_phone').val(phone);
         }
           $("#login_returnmessage").html(data);        
        });

If you use return outside a function then it terminates the script at that point. This is exactly what you're doing here:

return $memberInfo;
echo json_encode( $memberInfo );
//echo "1";

You need to remove the return statement.

You should also add a Content-type: header to the response to tell the browser to expect JSON:

header('Content-type:application/json');
echo json_encode( $memberInfo );

Your Javascript code is checking the response for the value 1 , which you're not sending, so the code that updates the display won't execute.

Lastly:

  • don't store passwords unencrypted - use password_hash()
  • don't use mysql as it's deprecated - use mysqli or PDO
  • ensure you escape your inputs before passing them to the database (or better, use prepared statements (not supported by mysql_*() ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM