I've been looking everywhere for the answer.
I have the JSON string
"[{"id":"0"}]"
I've tried
obj['id'] and obj.id
but that doesn't work
$.ajax({
url: 'php/checkdoctorappointmentonday.php',
data: 'doctorName=' + doctorName + '&dayOfEvent=' + date1,
type: "POST",
success: function (json) {
obj = JSON.parse(json.data)[0];
b = obj.id;
}
});
return true;
}
Am I missing anything?
This is the php used to get the result Edit:
<?php
$doctorName = $_POST['doctorName'];
$dayOfEvent = $_POST['dayOfEvent'];
// Query that retrieves events
$query = "SELECT COUNT(id) AS 'id'
FROM doctoravailability
WHERE start >='$dayOfEvent' AND start < DATE_ADD('$dayOfEvent', INTERVAL 1 DAY)
AND title = '$doctorName'
AND backgroundColor = 'red'
";
// connection to the database
try {
$bdd = new PDO("mysql:host=$servername;dbname=$dbname",$username,$password);
} catch(Exception $e) {
exit('Unable to connect to database.');
}
// Execute the query
$resultat = $bdd->query($query) or die(print_r($bdd->errorInfo()));
// sending the encoded result to success page
echo json_encode($resultat->fetchAll(PDO::FETCH_ASSOC));
?>
Does your JSON string actually have the start and end " in it, or have you just added them there to illustrate that it is a string?
Assuming that our data string actually has the ", then you just want to use the syntax
[{"id":"0"}]
As per comments, the object is actually an array containing an object
var str = "[{\"id\":\"0\"}]";
var obj = JSON.parse(str)[0];
alert(obj.id);
obj["id"] would have also worked, its the same as obj.id
Try this:
JS
$.ajax({
url: 'php/checkdoctorappointmentonday.php',
data: {
doctorName: doctorName,
dayOfEvent: date1
},
type: "POST",
dataType: 'json',
success: function (data) {
console.log(data);
b = data.0.id;
}
});
PHP
<?php
$doctorName = $_POST['doctorName'];
$dayOfEvent = $_POST['dayOfEvent'];
// Query that retrieves events
$query = "SELECT COUNT(id) AS 'id'
FROM doctoravailability
WHERE start >='$dayOfEvent' AND start < DATE_ADD('$dayOfEvent', INTERVAL 1 DAY)
AND title = '$doctorName'
AND backgroundColor = 'red'
";
// connection to the database
try {
$bdd = new PDO("mysql:host=$servername;dbname=$dbname",$username,$password);
} catch(Exception $e) {
exit('Unable to connect to database.');
}
// Execute the query
$resultat = $bdd->query($query) or die(print_r($bdd->errorInfo()));
// sending the encoded result to success page
return $resultat->fetchAll(PDO::FETCH_ASSOC);
?>
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.