I wonder why is it not working?
check_login.php
<?php
session_start();
$data = array("username" => "true");
echo json_encode($data);
?>
my js file var linkName;
$.ajax({
type: "POST",
url: "check_login.php",
dataType: "json",
success: function(json){
if(json.username != "true")
{
//do something
}
}
});
I am trying to get the username after checking whether or not the user has signed in yet in the php file, something like passing a session variable. But currently passing a string seems to already have a problem. Any know what I did wrong here?
Still not working the code above. Anyone want to help me out here?
5 Answers 5
You have an error in your PHP code. The square bracket ] is not needed in line 3. And, of course you should use echo json_encode($data);
1 Comment
`if(json.data.username != "true")` is wrong you do not have data object
`if(json.username != "true")` try this
Comments
You should echo the json data so that the page you get using ajax contains the string data.
<?php
session_start();
$data = array("username" => "true");
echo(json_encode($data));
?>
$.ajax({
type: "POST",
url: "check_login.php",
dataType: "json",
success: function(json){
console.log(json)
}
});
Also some times you might need to set the content type of the header in php to json.
2 Comments
try to send the header
header("Content-Type: application/json", true);
print json_encode($data);
Comments
return json_encode($data);
I think you have to return the data rather than just json encoding it!