Jquery Ajax call got json result 'undefined'
I want to get json result using Jquery. Now I always got 'undefined' result. I can get the json print out using
alert(data);
But always return 'undefined' using
alert(data.first_name);
Jquery client-side code
$.post(
"/modules/services/userlogincheck_new.php",
{
dataType: 'jsonp',
action : "checkpassword",
email : email,
password : password
},
function(data) {
alert(data.first_name);
}
);
PHP server-side
if ($_POST['action'] == "checkpassword") {
$query = "select * from users where email='" . $email . "'";
$result = mysql_query($query, $forumdbcon) or die('Error, insert query failed');
while ($row = mysql_fetch_assoc($result)) {
if (($row['password开发者_运维知识库'] == md5($password))) {
$arr = array("response" => 1, "first_name" => $row['first_name'], "last_name" => $row['last_name'], "address" => $row['address1']);
echo json_encode($arr);
} else {
$arr = array("response" => 2);
echo json_encode($arr);
}
}
}
Try this:
$.post("/modules/services/userlogincheck_new.php", {
action : "checkpassword",
email : email,
password : password
}, function(data) {
alert(data.first_name);
},'json');
The response sent from the server is JSON not JSONP. Change dataType to JSON.
"Off topic": Your code is might be highly vulnerable to SQL Injection. If I transmitted ';DROP TABLE users; --
as my email address, you woud be in trouble.
On topic:
$.post(
"/modules/services/userlogincheck_new.php",
{
action : "checkpassword",
email : email,
password : password
},
function(data) {
alert(data.first_name);
},
'json'
);
$.post()
needs the data-type to be set explicitely.
You don't need jsonp
since this is on the server. Try changing dataType: 'jsonp'
to dataType: 'json'
.
You're using $.post
, so you're just sending the dataType
to PHP, which doesn't do anyting, you need to tell $.post
to use JSON.
$.post("/modules/services/userlogincheck_new.php", {
action : "checkpassword",
email : email,
password : password
}, function(data) {
alert(data.first_name);
}, 'json;);
You're using jsonp
, so you need to wrap your output in a function call, per the parameter given by the automatically created jsonp
parameter.
echo $_GET['jsonp'] . '(' . json_encode($arr) . ');';
Alternatively, just use plain JSON instead.
精彩评论