how do i use JSON response with Ajax
how do i use JSON response with Ajax
I am trying to use the JSON response from my Ajax request, but no matter what I try i cannot get this to work so would like some help please.
My code for the ajax request is below
<html>
<head>
<title>QuizMaster</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
http://jquery-3.1.0.min.js
function player(x){
var player = x;
$.ajax({
url:"gameDb.php",
type: "GET",
data: {"request":player},
dataType: "json",
success: function(data){
console.log(data);
var obj = JSON.parse(data);
console.log(obj[1].player1);
//console.log(data['player1']);//undefined
//console.log(data[player[0]]);
}
});
}
$(document).ready(function(){
$('#button input').click(function(){
var x = this.id;
player(x);
});
});
With this i get the reponse
` player1.php:18 Uncaught ReferenceError: data is not defined
at Object.success (player1.php:18)
at i (VM160 jquery-3.1.0.min.js:2)
at Object.fireWith [as resolveWith] (VM160 jquery-3.1.0.min.js:2)
at A (VM160 jquery-3.1.0.min.js:4)
at XMLHttpRequest.<anonymous> (VM160 jquery-3.1.0.min.js:4)`
My JSON reponse with out the success script is the folowing
`{1: {…}}1: 0: "1"1: "1"2: "0"id: "1"player1: "1"player2: "0"__proto__: Object__proto__: Object`
If i change the successs from
`var obj = $.parseJSON(data); console.log(data[0].player1);`
to this
`console.log(data['player1']);` i get undefined
and if i change it to
console.log(data[player[0]]);
console.log(data[player[0]]);
I also get undefined
What am i doing wrong. i would like to be able to use the response in my code
This is the PHP script if it helps
<?php
$request = $_GET['request'];
try
{
$pdo = new PDO('mysql:host=localhost; dbname=game', '***', '***');
}
catch (PDOException $e)
{
echo 'Error: ' . $e->getMessage();
exit();
}
if ($request == 'player1'){
$player1 = 1;
$player2 = 0;
}
if ($request == 'player2'){
$player1 = 0;
$player2 = 1;
}
$id = 1;
$sql = "UPDATE game1 SET player1 = :p11, player2 = :p12 WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':id', $id);
$stmt->bindParam(':p11', $player1);
$stmt->bindParam(':p12', $player2);
$stmt->execute();
$sql = 'SELECT * FROM game1';
$stmt = $pdo->prepare($sql);
$stmt->execute();
while ($row = $stmt->fetch())
{
$x++;
$items[$x] = $row;
}
echo json_encode ($items);
$conn = null;
?>
EDITED
If I change the php script to the following
while ($row = $stmt->fetch())
{
//$x++;
//$items[$x] = $row;
$player1 = $row['player1'];
$player2 = $row['player2'];
}
//$item[{"plater1":"1", "player2":"2"}];
//echo "<pre>";print_r(json_encode($items));die;
$items['player1'] = $player1;
$items['player2'] = $player2;
echo json_encode ($items);
I get the following when going to the php code
{"player1":"0","player2":"0"}
if I change the player script to the following
success: function(data){
console.log(data);
var obj = parseInt(data.player1);
console.log(obj);
}
I get player 1 value which is correct
but if i try
var obj = JSON.parse(data);
or
var obj = $.parseJSON(data);
I still get the syntex error for both. Not sure why but I can get awork around
Your posted JSON response looks rather invalid and un-JSON-y. Can you also post the actual raw response before parseJSON that you can see in the network tab of your browser?
– Shilly
Jun 29 at 14:33
console.log(data)
and verify your PHP code.– Alex
Jun 29 at 14:33
console.log(data)
That was the response {1: {…}} 1 : {0: "1", 1: "1", 2: "0", id: "1", player1: "1", player2: "0"} proto : Object
– Steve8428
Jun 29 at 14:34
Agreed with @Shilly, just noticed your
JSON
, it looks broken. Are you just copying it from your console?– Alex
Jun 29 at 14:34
JSON
3 Answers
3
You have already the json parse with dataType: "json"
so you don't need to do it again with $.parseJSON
or JSON.parse
, the error is because you are trying to parse not an string but an object. Try this:
dataType: "json"
$.parseJSON
JSON.parse
function player(x){
var player = x;
$.ajax({
url:"gameDb.php",
type: "GET",
data: {"request":player},
dataType: "json",//here you have the parse
success: function(data){
//var obj = $.parseJSON(data); you don't need to parse as json
console.log(data[1].player1);//or console.log(data.player1); it depends of the implementation. it should be 0
}
});
}
As the result given in comments, you have this structure:
var str = '{"1":{"id":"1","0":"1","player1":"0","1":"0","player2":"0","2":"0"}}';
var obj = JSON.parse(str);
console.log(obj)
console.log(obj[1].player1);
This is data:
{
"1": {
"0": "1",
"1": "0",
"2": "0",
"id": "1",
"player1": "0",
"player2": "0"
}
there is no data[0]
data[0]
I thought this would work but for some reason i get the same Unexpected token o in JSON at position 1 at JSON.parse (<anonymous>) with element var obj = JSON.parse(data);
– Steve8428
Jun 29 at 15:14
@user2669997 have you tried this?: this var obj = JSON.parse(data); console.log(obj[1].player1); in ajax? because this should work. Because token o is not present in JSON.parse(data);
– Emeeus
Jun 29 at 15:20
This is what i have written : var obj = JSON.parse(data); console.log(obj[1].player1); Which gives the error. I can see what you are saying about no 0 object but I think this might be the first VAR line which is causing the error and maybe the data being sent. Im confused with it
– Steve8428
Jun 29 at 15:32
@user2669997 I'm almost sure that php maybe is throwing an error or a notice then do this in php echo "<pre>";print_r(json_encode($items));die; but execute the php file, not the ajax
– Emeeus
Jun 29 at 15:37
@user2669997 I've updated the code above
– Emeeus
Jun 29 at 17:02
It seems to me the problem starts to excists once you drop the $.parseJSON(data);
part. wich means javascript doesnt know how to handle the json so it returns undefined.
$.parseJSON(data);
console.log($.parseJSON(data[0].player1));
This might work in your case. Can't test it tho.
sorry no this still returns cannot read property player1
– Steve8428
Jun 29 at 14:44
The $.parseJSON()
function will return the JSON as a JavaScript object and not change the original JSON. You need to use the returned value from the function:
$.parseJSON()
function player(x){
var player = x;
$.ajax({
url:"gameDb.php",
type: "GET",
data: {"request":player},
dataType: "json",
success: function(data){
var obj = $.parseJSON(data);
console.log(obj[0].player1); // switched data with obj
}
});
}
As you can see on the jQuery documentation $.parseJSON()
is deprecated and you should JSON.parse()
instead:
$.parseJSON()
JSON.parse()
success: function(data){
var obj = JSON.parse(data);
console.log(obj[0].player1); // switched data with obj
}
Thanks i did try the JSON.parse(data) I am still getting Uncaught SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse (<anonymous>) in the console
– Steve8428
Jun 29 at 14:56
what is the output of
console.log(data)
?– Pedro Henrique
Jun 29 at 14:57
console.log(data)
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Try console.log(data); and tell us the response.
– Emeeus
Jun 29 at 14:30