problems parsing JSON in javascript from PHP - javascript

Here is my PHP array:
$entries = array(
1420934400 => array(
'entry' => 'I think I liked it.',
'data' => 'some'
),
1452470400 => array(
'entry' => 'Turkey is much better. Tastes more like chicken.',
'data' => 'no calls'
));
Then I convert to JSON
$entries = json_encode($entries);
This produces the string:
{"1420934400":{"entry":"I think I liked it.","data":"some"},"1452470400":{"entry":"Turkey is much better. Tastes more like chicken.","data":"no calls"}}
...which I believe is valid JSON. But when I try to access in JavaScript:
<script>
var fetchedEntries = JSON.parse(<?php echo $entries ?>);
console.log('entries: %o', fetchedEntries);
</script>
I get the following error:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of
the JSON data
Can anyone see where I'm going wrong?

You don't need JSON.parse in JS since JSON can be directly interpreted by JS (it is called JavaScript Object Notation for a reason ;-). Do
var fetchedEntries = <?php echo $entries ?>;
When you receive the JSON data as a string, then JSON.parse is appropriate. For example, this works too:
var fetchedEntries = JSON.parse( "<?php echo json_encode( $array_or_obj ); ?>" );

Related

How to get value from a PHP array in JavaScript?

Let's say we have one PHP array:
$decoded = array(
'method' => 'getFile',
'number' => '12345'
);
The array data will pass to another JavaScript get function(params).
function get(params) {
}
How I get the $decoded['method'] value in JavaScript language in the get function?
<?php
$decoded = array(
'method' => 'getFile',
'number' => '12345'
);
?>
<script>
var params = <?php echo json_encode($decoded); ?>;
get(params);
function get(params){
console.log(params);
console.log(params['method']);
}
</script>
Use this way. you have to get php variable or array inside javascript by printing or echo. Then you can call function.
Javascript array and PHP arrays are not equal. But the objects of both languages are equal. Then you can JSON encode your array in PHP and pass the encoded value in the javascript.
For example:
In PHP
<?php
$decoded = array(
'method' => 'getFile',
'number' => '12345'
);
?>
In JS
var params = <?php echo json_encode($decoded); ?>;
function get(params) {
console.log('method', params.method);
console.log('number', params.number);
}

unable to get json data from server

My server side code is:
$bus = array(
'meaning' => $name
);
$jsonstring = json_encode($bus);
echo $_GET['callback'].'(' . $jsonstring. ')';
the value displayed on the screen is correct - ?word=heart({"meaning":"heart"})
but when I am reading it with following code its printing the value of meaning as 11200665987893779229_1460521505942
$(document).ready(function(){
$.getJSON('http://mydomain?callback=?','word=heart',function(res){
document.getElementById('print').innerText=''+res.meaning;
});
});
but when I do this:
$bus = array(
'meaning' => 'heart'
);
it's printing the correct value i.e heart
I am not getting why this is happening and how to get the correct value (I am accessing data from my different domain).
JSON.parse() converts any JSON String passed into the function, to a JSON Object.
$(document).ready(function(){
$.getJSON('http://mydomain?callback=?','word=heart',function(res){
obj = JSON.parse(res);
document.getElementById('print').innerText=''+obj.meaning;
});
});
a similar post is here

Associative php array sent via jquery returns [Object object]

I have to pass a php multidimensional array via ajax/jQuery to another php file.
I have encoded the array using
I expected theat every item in the array would have been an array itself. Instead it returns [Object object].
How can I access the data using php?
here's my code:
in the first php file:
<script type="text/javascript">
var arr_data = <?php echo json_encode($itemsData); ?>;
$("#confirmButton").click(function(){
$.post("send_test.php", {"my_array_data[]":my_array_data}, function( data ) {
alert(data);
});
});
</script>
the other php file:
<?php
$my_array_data = $_POST['my_array_data'];
?>
if I try to retrieve the first row ($my_array_data[0]) I get [Object object]
I just want to access to $my_array_data[0]['category'] etc.
A couple of errors here:
the data you are passing to ajax has an incorrect key using brackets[]
you are not passing the correct object through ajax since my_array_data is never defined
redo your code like this:
PHP
$itemsData = array(
array(
"test" => 30,
"test2" => 10,
),
array(
"test" => 90,
"test2" => 50,
)
);
JS
var arr_data = <?php echo json_encode($itemsData); ?>;
$("#confirmButton").click(function () {
$.post("send_test.php", {my_array_data: arr_data}, function (data) {
console.log(data);
});
});
Then in send_test.php
$data = $_POST['my_array_data'];
print_r($data);
Result:
Array
(
[0] => stdClass Object
(
[test] => 30
[test2] => 10
)
[1] => stdClass Object
(
[test] => 90
[test2] => 50
)
)
You're putting json-encoded data into the arr_data javascript variable - however you don't appear to be sending that to the other php file.
In the other php file, try using json_decode on the data you're receiving in the POST request:
$my_array_data = json_decode($_POST['my_array_data']);
Yes, as Aric says, name array consistently like this:
var my_arr_data = <?php echo json_encode($itemsData); ?>;

JSON passes string instead of array or object from PHP to Javascript

I am having som trouble with passing a multidimensional and associative array from php to Javascript. I converte it with JSON, using:
_SESSION = '<?php print json_encode($_SESSION) ?>';
I have also tried
_SESSION = '<?php print json_encode($_SESSION, JSON_PRETTY_PRINT) ?>';
_SESSION = $.parseJSON('<?php print json_encode($_SESSION) ?>');
both of them give me errors like: Uncaught SyntaxError: Unexpected token ILLEGAL.
However, the first one doesn't give me any errors and I can access it in Javascript. It then outputs:
{"items":{"221163":{"CodeComplete":null,"Project":"Coding","Team":"Mail","TimeSpent":25","Children":[]}}, {"221165":{CodeComplete":null,"Project":"Coding","Team":"Batman","TimeSpent":"40","Children":[]}}
I belive this is like a string, since _SESSION[0] outputs "{". However, I want it to be an array or an object. The Array looks like this in php:
_SESSION( "items" => array(
221163 =>
array( CodeComplete => null
Project => "Coding"
Team => "Mail"
Timespent => "25"
Children => array(
)
)
221165 =>
array( CodeComplete => null
Project => "Coding"
Team => "Stones"
Timespent => "40"
Children => array(
)
)
)
)
I want to be able to access this array in the same way as I can in php (not litterary ofcorse) but _SESSION["items"] or _SESSION.items is undefined as _SESSION is a string...
Any ideas of what I'm doing wrong?
Just as #CD001 suggested in his comment, I removed the '' from the transfer so that it became
_SESSION = <?php print json_encode($_SESSION) ?>;
instead and now everything works fine, thank you!

Get a php array into a js array

I want to get a php array made by pg_fetch_all in a javascript array. But when I try to do it, firebug tells me that I'm trying to convert an array to string. Indeed, I don't understand why because both are arrays.
Here is where I create the php array :
$conn_string = "host=localhost port=5432 dbname=test_postgre user=postgres password='1234'";
$dbconn = pg_connect($conn_string);
$sql = "SELECT ".$colonne." FROM public.".$tablevar."";
$res = pg_query($sql) or die("Pb avec la requete: $sql");
$data = pg_fetch_all($res);
And here is my js code :
var array_dropdown =[<?php echo $data;?>];
And it doesn't work. Please help me !
PHP Arrays 101: Arrays in a string context are the literal word Array:
$x = array(1 => 2);
echo $x; // ouputs "Array"
You need to use json_encode():
var array_dropdown = <?php echo json_encode($data); ?>;
json_encode guarantees that whatever you pass in to the encode function will be output as syntactically valid javascript. Note the lack of [] around the above code - json_encode handles all of that for you.
Assume this as your PHP array
$array = array('foo' => 'bar');
The JS part:
var array = <?php echo json_encode($array); ?>;

Categories

Resources