4

New to web design here. I have a login form that validates and works perfectly in php but when I try and validate using ajax it doesn't work. When i run the page it says it is a success no matter the input into the form. I have tried for days trying to get it to validate in many different methods. If there is a better way please let me know!

php here and is on same page as login form

if (isset($_POST['login'])) {

    $email = mysqli_real_escape_string($con, $_POST['email']);
    $password = mysqli_real_escape_string($con, $_POST['password']);
    $result = mysqli_query($con, "SELECT * FROM users WHERE email = '" . $email. "' and password = '" . md5($password) . "'");

    if ($row = mysqli_fetch_array($result)) {
        echo json_encode('true');
        $_SESSION['usr_id'] = $row['id'];
        $_SESSION['usr_name'] = $row['name'];
        $_SESSION['logged_in'] = true;


    } else {
        echo json_encode('false');
        $errormsg = "Incorrect Email or Password!!!";
    }
}


?>

$(document).ready(function() {
  $('#login_submit').click(function() {
      var form = $('#login_form').serialize();
    $.ajax({
        type: "POST",
        url: "header.php",
        data: form,
        success:function (response){
                
                alert('Hi');
        
        },
        error: function(response){
                
                alert('Nope');
            
        }
          
        
   });
 });
});
<form id="login_form" form role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="loginform">
                
                <label class="login_form_labels"> Email:</label>
                
                <input type="email" id="email" class="login_input" name="email"><br><br>
                
                <label class="login_form_labels"> Password:</label>
                
                <input type="password" id="password" class="login_input" name="password"><br>
                
                <div id="stay_log">
                    Stay logged in.
                    
                    <input type="checkbox" name="stayLoggedIn" value=1 id="checkbox_1">
                    
                </div>
                
                
                <input class="login_form_btn" name="login" value="Submit" type="Submit" id="login_submit">
                
                <button class="login_form_btn" type="button">Forget your Password?</button>

            </form>

Please help!

Ishita Sinha
  • 2,168
  • 4
  • 25
  • 38

4 Answers4

0

First use alert(response) to find out the response you are getting. It should be true or false.

success:function (response){

            if(response === "true") 
           {
               alert("hi");
           }
           else
           {
             alert("nope");
           }
    },
coder
  • 906
  • 1
  • 12
  • 19
0

set dataType as Json in your ajax as like given below

$.ajax({
    type: "POST",
    url: "header.php",
    dataType: json,
    data: form,
    success:function (response){
            alert('Hi');
    },
    error: function(response){
            alert('Nope');
    }
});

Try this...

Dharit Soni
  • 415
  • 4
  • 17
0

I think you need to require pure JSON response from server side and handle it in your ajax success method.

In your PHP code.

$response=array();
if (!empty($_POST)) {
    $email = mysqli_real_escape_string($con, $_POST['email']);
    $password = mysqli_real_escape_string($con, $_POST['password']);
    $result = mysqli_query($con, "SELECT * FROM users WHERE email = '" . $email. "' and password = '" . md5($password) . "'");

    if ($row = mysqli_fetch_array($result)) {
        echo json_encode('true');
        $_SESSION['usr_id'] = $row['id'];
        $_SESSION['usr_name'] = $row['name'];
        $_SESSION['logged_in'] = true;


        $response['type']="success";
        $response['message']="Login done successfully";


    } else {
        $response['type']="error";
        $response['message']="Incorrect Email or Password!!!";
    }
}
else
{
    $response['type']="error";
    $response['message']="invalid post request";
}

ob_clean();
echo json_encode($response);
die();

In above way from server you can response in only json format.

In you ajax call javascript code

$(document).ready(function() {
  $('#login_submit').click(function() {
      var form = $('#login_form').serialize();
    $.ajax({
        type: 'post',
        url: $('#login_form').attr("action"),
        data: form,
        dataType:'json'
        success:function (response){
                if(response.type=="success")
                {
                    alert(response.message);
                    // write code for handle your success login;
                }
                else
                {
                    alert(response.message);
                    // write code for handle your failure login;

                }

        },
        error: function(response){

                alert('Nope');

        }


   });
 });
});

You have to handle JSON response from server side in your ajax success response

Haresh Vidja
  • 8,340
  • 3
  • 25
  • 42
0

In jQuery/AJAX, the HTTP response code termines whether it is a success or not. So if the login failed, you should set a header in PHP indicating this failure.

if (.. login has failed .. ) {
  // HTTP 401 = 'Unauthorized'.
  http_response_code(401);  
}

By doing this, you won't even have to process the resulting JSON, only maybe to get additional info. But the basic result will tell you enough: if the success callback was called, logging in was successful. If error was called, it was not successful for whatever reason.

This sets out your basic flow, and after that you could parse the result message to see any details of what's going on (internal server error, user unknown, password doesn't match, etc).

See List of HTTP response codes, for a list of alternatives and this question for an argumentation about using 401.

Community
  • 1
  • 1
GolezTrol
  • 114,394
  • 18
  • 182
  • 210