简体   繁体   中英

Receiving JSON object after sending data to server in javascript

I am trying to pass a email and password on login click to a db that uses PHP. Once it tests the email and password combo, the php sends back a json object. Now, I have tested the php and it does properly and will show a json object with the correct "success" or "fail" value, but either I get a status: request was cancelled, or "success" is not returned ever but "fail" does get returned. I have no idea what is going wrong with this.

Here is the javascript I have so far:

//make sure the login is correct
function testLogin(email, password){
//make sure the boxes arent empty
if(email !== "" && password !=="")
{
    //create a json object, and 
    var jsonObject = {"email":email, "password":password};
    var finalObject = JSON.stringify(jsonObject);
    //alert(finalObject);

    //sending json object

        $.ajax({
            type: 'POST',
            url: 'WebPHP/check_login.php',
            data: finalObject,
            dataType: 'json',
            success: function(data)
            {

               if(data['result'] === "success"){
                   alet("good");
                    window.location.href = "AMessage.html";

            } else{
                    alert("Invalid Email or Password");
            }
            }
        });

}     return false;  

}

And here is the php I have so far:

<?php

require 'db_connect.php';

header('Content-type: application/json');

$json = file_get_contents('php://input');

$jsondata = json_decode($json);

$email = $jsondata->{'email'};
$password = $jsondata->{'password'}
//$email = "TestUser";
//$password = "TestPasss";

$sql1 = " SELECT *
           FROM users
          WHERE email = '$email' AND password = '$password';";

$result = mysqli_query($Thesisdb, $sql1) or die(mysqli_error($Thesisdb));

$rows = $result->num_rows;

$post_data = array();

if($rows == 1){
    $post_data = array('result' => "success");
} else {
    $post_data = array('result' => "fail");
}

echo json_encode($post_data);

mysqli_close($Thesisdb);

Your success alert has a typo, in your example you have used alet where it should be alert :

if(data['result'] === "success"){
  alert`("good");
  window.location.href = "AMessage.html";
}

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