Reputation: 531
Please somebody help me, am new to ajax, i have been trying to read json data from php script but just no success. when i console.log the data i get this,
{"name":"JOHN","surname":"FIGO","sex":"M","Records_id":"1","student":""}.
and when i do this console.log(data[2]);
i simply get n
character. what i want is to get the values, for example, console.log(data['name']);
should give JOHN
or console.log(data[0]);
should give JOHN
. when i use either javascript or jquery parse methods, i get an error, i dont understand. Here is are the codes;
<?php
$conn= new mysqli('localhost', 'root', '', 'Goldfinger');
$query= 'SELECT * FROM records';
$result= $conn->query($query);
while($row = $result->fetch_assoc()) {
echo json_encode($row);
}
?>
and jquery;
$('#one').click(function () {
$.ajax({
url: 'ajaxtesting.php',
type: 'POST',
success: function (data) {
if (data) {
console.log(data['name']);
};
},
error: function () {
$('div:not(#one)').text('error dude!');
}
})
})
pardon my code if it's very poor. Thank you in advance.
Upvotes: 2
Views: 105
Reputation: 9060
Put dataType : 'json',
inside ajax setting like so :
$.ajax({
url: 'ajaxtesting.php',
type: 'POST',
dataType : 'json', //<------------- here
success: function (data) {
if (data) {
console.log(data['name']);
};
},
error: function () {
$('div:not(#one)').text('error dude!');
}
})
or simply parse inside success callback :
$.ajax({
url: 'ajaxtesting.php',
type: 'POST',
success: function (data) {
var myData = $.parseJSON( data ); //<------- here
if ( myData ) {
console.log(myData['name']);
};
},
error: function () {
$('div:not(#one)').text('error dude!');
}
})
Upvotes: 3