简体   繁体   English

使用JavaScript将数据发送到服务器后接收JSON对象

[英]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. 我试图将登录单击时的电子邮件和密码传递给使用PHP的数据库。 Once it tests the email and password combo, the php sends back a json object. 一旦测试了电子邮件和密码组合,PHP就会发回一个json对象。 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. 现在,我已经测试了php,它可以正常运行,并且将显示具有正确“ success”或“ fail”值的json对象,但我的状态是:请求已取消,或者“ success”从未返回,而是“失败”。 I have no idea what is going wrong with this. 我不知道这是怎么回事。

Here is the javascript I have so far: 这是到目前为止的javascript:

//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:

<?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 : 您的成功警报有一个错字,在您的示例中,您使用alet alert

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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