1

I apologize in advance for what appears to be a duplicate question but I am truly stuck. I am sending login info to a php page which validates the username and password. It works fine in that it says success or failure depending on if the user info exists as shown in the picture. Post Response

What I want to do is send the $user value back to my javascript page and then redirect them to the user page if it returns "ok". I cannot for the life of me figure out how to do it.

Here is my Javascript:

function Userlogin() {
    $.post("login.php",
    {            
        username: $("#login_username").val(),        
        pass: $("#login_password").val()
        success: function(user){
            alert("Done!");
        }
    }
},

Here is my PHP:

$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['pass']);

echo $username;

$login = mysqli_query($conn, "SELECT * FROM users where username = '$username' and password = '$password'");
$num_rows = mysqli_num_rows($login);

printf("Result set has %d rows.\n", $num_rows);

mysqli_free_result($login);

if ($num_rows == 1) {
    echo "Success";
    $user = "ok";
} else {

}

echo json_encode($user);
mysqli_close($conn);

Any help would be greatly appreciated. Thanks in advance!

hanish singla
  • 782
  • 8
  • 21
Evan Lalo
  • 1,209
  • 1
  • 14
  • 34
  • 2
    Are you just asking how to perform a redirect in JavaScript? If you Google that exact phrase, you get this: https://stackoverflow.com/questions/503093/how-to-redirect-to-another-webpage-in-javascript-jquery – David Aug 10 '17 at 12:07
  • Well, the odd thing is that I don't get my success alert. Even when I get the post response. I was thinking the easiest thing to do would be to return my user variable and then redirect if the user exists. I am very new to all of this though so I am sure I missing something. – Evan Lalo Aug 10 '17 at 12:14
  • I guess you have received sufficient guidance to write the redirect. Please also consider these: 1. Do not store plain passwords in DB, use a salted hash instead. 2. Use `prepared statement` as that is the ultimate guard against SQL injection, not using `mysqli_real_escape_string`. – Majid Fouladpour Aug 10 '17 at 12:20
  • @EvanLalo: `"the odd thing is that I don't get my success alert"` - Yet in the question you state: `"It works fine in that it says success or failure"` - Does your current code work or not? What is the specific problem you're addressing in this question? Please clarify. – David Aug 10 '17 at 12:25
  • I get a response as shown in the picture. I don't however hit my `success` function in my Javascript code. – Evan Lalo Aug 10 '17 at 12:33
  • @EvanLalo: If the current problem you're trying to solve is running the `success` callback then it looks like an answer below (https://stackoverflow.com/a/45613717/328193) found what is essentially a kind of typo in your code. The `success` callback is being passed to the server as a value rather than passed to the `$.post()` function as a callback. You just need to separate that function into its own argument to `$.post()`. – David Aug 10 '17 at 12:49

5 Answers5

2
function Userlogin() {
   $.post("login.php",
    {            
        username: $("#login_username").val(),        
        pass: $("#login_password").val()
    },function(user){
            console.log(user)//You'll see what your PHP sent you.
            if(user == "ok"){
                //Redirect
            }else{
               alert("You shall not pass!");
            }
        }
    );
 }

Now the trick is to make sure PHP return only ok. You could also send JSON, as you tried to do a bit. But look at the console.log results, you'll see that the main problem is your echoes and prints. You shouldn't output useless information, as you need to handle the answer accordingly.

To answer your comment: Looking at your request response screenshot, you are receiving the content of 3 echo/print:

printf("Result set has %d rows.\n", $num_rows);
echo "Success";
echo json_encode($user);
Salketer
  • 14,263
  • 2
  • 30
  • 58
  • I trimmed it down to just echo my `$user` variable. When the user exists it has a value of "ok". I want to send this value back to my javascript. I try to `JSON.parse` the variable and then `console.log` its value but it doesn't get to that part. Any ideas? – Evan Lalo Aug 10 '17 at 12:41
  • I am sorry, it was my mistake I wrote the .post() call as if it was .ajax(). I've corrected the call to make the function be at the right parameter. – Salketer Aug 10 '17 at 12:45
1

Edit you above php code part like this for sending json response with login status and user details

    if($num_rows == 1) {
        $user = $login->fetch_assoc()[0]['username'];
        $data=array("status"=>"1","user"=>$user);

    } else {
      $user = "";
        $data=array("status"=>"0","user"=>$user);
    }
   echo json_encode($data);

in the you frontend javascript code parse the json response and use the information to redirect to the user page

function Userlogin() {
$.post("login.php",
    {    

    username: $("#login_username").val(),        
    pass: $("#login_password").val()

    success: function(response){
        var data = JSON.parse(response);
        if(data.status==="1")
          window.location = "http://example.com/page.php?user="+data.user;
        else alert("Wrong Username or password");
    }
},

PS: do not print or echo anything else in your server side code otherwise you will get JSON pasring error in the frontend.

flamelite
  • 2,654
  • 3
  • 22
  • 42
1

You are passing the success callback as a request parameter. Try this one:

function Userlogin() {
    $.post("login.php", {
        username: $("#login_username").val(),        
        pass: $("#login_password").val()
    }, function(user){
        alert("Done!");
    });
}
vher2
  • 980
  • 6
  • 9
0

You can echo in php to make use in javascript.

Change code In Javascript:

  $.post("login.php",
  {            
    username: $("#login_username").val(),        
    pass: $("#login_password").val()
    success: function(user){
         if(user == "ok"){
               //redirect
          }
    }
  },

Change code In PHP:

$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['pass']);
$login = mysqli_query($conn, "SELECT * FROM users where username = '$username' and password = '$password'"); 
$num_rows = mysqli_num_rows($login);
printf("Result set has %d rows.\n", $num_rows);
mysqli_free_result($login);
if($num_rows == 1) {
    echo "ok"
} else {

}
mysqli_close($conn);

In php just echo ok on success and use that same in javascript to validate it.

BSB
  • 2,270
  • 17
  • 26
-1

If you want to get the response from the request which you have made,create an array or variable in php and append your response as below:

$responseData['data']['User'] = $User;

Where $responseData is an array.

Inside your JS:

if($User) {
echo'<script>window.location="your landing page";</script>';
end();
}
lifeisbeautiful
  • 817
  • 1
  • 8
  • 18