How I can get the success (data) value on Ajax? I want to get the value of firstname and lastname, which are Kevin Yam.
Example I want to set input value, document.getElementById("reply").value = "Kevin Yam"
Ajax code:
$.ajax({
type:'post',
url:'getuser_reply_name.php',
data:{get_reply_postid:post_id,get_reply_commentid:comment_id},
cache:false,
success: function (data){
console.log(data);
}
});
getuser_reply_name.php code:
if($stmt = $conn->prepare($query)) {
$stmt->execute();
$stmt->bind_result($user_firstname, $user_lastname);
while ($stmt->fetch()) {
$userdetails = array(
'u_firstname' => $user_firstname,
'u_lastname' => $user_lastname
);
header('Content-Type: application/json');
echo json_encode($userdetails);
}
$stmt->close();
}
Console log result:
1.Add dataType:"JSON",
in your $.ajax
, so that it automatically parse json
data coming from php
.
2.Inside success
fetch data from response using keys
(what you are seeing in console.log()
)
Do like below:-
$.ajax({
type:'post',
url:'getuser_reply_name.php',
data:{get_reply_postid:post_id,get_reply_commentid:comment_id},
dataType:'json', //add dataType
cache:false,
success: function (data){
$("#reply").val(data.u_firstname+' '+data.u_lastname); // put value to input box
}
});
$.ajax({
type:'post',
url:'getuser_reply_name.php',
data:{get_reply_postid:post_id,get_reply_commentid:comment_id},
cache:false,
dataType: 'json', // what type of data do we expect back from the server
encode: true,
success: function (data){
console.log(data);
}
});
you will get object of array in response
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.