I have some problem with jquery. Why there is a problem accessing a variable in the json string?
$(function() {
var jqxhr = $.ajax({
type: "POST",
url: "test.php",
async: false,
cache: false,
timeout: 10000,
data: {
test: "test"
},
success: function(response) {
console.log(response); // {"login":"1","status_":0,"user":1}
console.log(response.login); //undefined
test = JSON.parse(response); // Uncaught SyntaxError: Unexpected token in JSON at position 2
console.log(test.login); //not work
},
complete: function(response) {
}
});
})();
test.php
require("config.php");
require("dbconnect.php");
$sth = $dbh->prepare('SELECT * FROM users WHERE email=?');
$sth->bindParam(1, $_POST["login"], PDO::PARAM_STR);
$sth->execute();
$user = $sth->fetch();
if(@$user['email']==$_POST["test"]) {
$json = json_encode(array("login" =>"1","status_"=>0, "user" => 1), JSON_UNESCAPED_UNICODE);
}
else {
$json = json_encode(array("login" =>"1", "status_"=>1, "user" => 1), JSON_UNESCAPED_UNICODE);
}
echo $json;
This is a small php script that returns a single JSON string by simple condition.
If I not use code below:
require("config.php");
require("dbconnect.php");
$sth = $dbh->prepare('SELECT * FROM users WHERE email=?');
$sth->bindParam(1, $_POST["test"], PDO::PARAM_STR);
$sth->execute();
$user = $sth->fetch();
it works and console.log(response.login)//return 1), but if I use a database connection, it doesn’t. Why?
2
Answers
I made an require config.php in dbconnect.php and script work normal, but this is an some kind of anomaly probably.
Declare
dataType
in your Ajax call. like –Or parse your string to a valid JSON. like
The second thing you should normally encode your JSON on the server end. See –