I am retrieving data from database. When I try to output it in console using console.log(response)
, I would get this:
Array
(
[deptCode] => Econ
[collegeCode] => BA
[deptName] => Economics
)
I am expecting to get the values Econ, BA, and Economics
.
My problem is when I pass it from PHP to AJAX using response["deptCode"]
, I would get undefined
.
I have tried doing data = JSON.parse(response);
and I would get the error:
Uncaught SyntaxError: Unexpected token A in JSON at position 0
at JSON.parse (<anonymous>)
I've also tried this:
for(var key in response){
console.log(response[key]);
}
but the result is this: image result from console
Here's my db.php
:
public function getDept($code){
$sql = 'SELECT * FROM department WHERE "deptCode" = :code';
$stmt = $this->conn->prepare($sql);
$stmt->execute(['code'=>$code]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
return $result;
action.php:
if(isset($_POST['edit_id'])){
$id = $_POST['edit_id'];
$row = $db->getDept($id);
echo json_encode($row);
}
index:
$("body").on("click", ".editBtn", function(e){
e.preventDefault();
edit_id = $(this).attr('id');
$.ajax({
url: "action.php",
type: "POST",
data:{edit_it:edit_id},
success:function(response){
console.log(response);
//data = JSON.parse(response);
//for(var key in response){
// console.log(response[key]);
//}
}
})
})
any help would be appreciated :)
I have json_decode
in such as errors before. to parse to JSON in ajax response, you have to decode the data in PHP. ie Please use json_decode
in PHP. and then JSON.parse(response)
in ajax response. I hope that you will solve it.
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.