display json from php in javascript - javascript

I have a php file returning this valid Json data, stored in a javascript variable named "json".
[
"564654.56464",
"848492.25477",
"918821.54471"
]
I try to display it in javascript with :
var object = JSON.parse(json);
document.write(object. ..... );
i don't know what to add here since my Json is not like {"attribute":"value","attribute2":"value2"

You can encode your PHP file along with a json header. I guess that should do the trick!
header('Content-Type: application/json');
echo json_encode($array);

Use
document.write(object.toString());

Related

JSON from localstorage not able to decode in php

I am fetching values from localstorage as JSON and trying to decode.
But its not working.
This my code to fetch JSON from localstorage:
$items = "<script> document.write(JSON.parse(JSON.stringify(localStorage.getItem('itemList')))); </script>";
When i echoed above $items it resulted like this:
{"items":[{"name":"Guitar","id":"1"}]}
Decoding above json like this:
$decoded = json_decode($items, true);
When i am trying to echo $decoded not displaying anything. When i did var_dump($decoded) its showing NULL
Any help is appreciated. Thank you.
The situation is that you're not able to combine JS/PHP "in one line".
$items = "<script> document.write(JSON.parse(JSON.stringify(localStorage.getItem('itemList')))); </script>";
json_decode from $items will give you directly the code that you've put in (check json_last_error())... without any JS execution (or you have to use PhantomJS; but it's not your case).
How it has to be:
JS part (sample.js):
jQuery.post('sample.php', {
'item': JSON.stringify(localStorage.getItem('itemList'))
});
PHP part (sample.php)
$items = filter_input(INPUT_POST, 'item');
$decoded = json_decode($items, true);
var_dump($decoded);
localStorage only stores strings. The JSON.stringify() is wrong since it expects a JSON object, not a string, as input.

covert a php array to json object , then back to array in javascript [duplicate]

I need to get an array generated from a script php. I have Latitude and Longitude for each user in a database.
I take the values from the db with this code (file.php):
$query = "SELECT Latitude, Longitude FROM USERS";
$result=mysql_query($query);
$array=array();
while ($data = mysql_fetch_array($result)) {
$array[]=$data['Latitude'];
$array[]=$data['Longitude'];
}
echo $array;
and I call with ajax with this code:
$.post('./file.php',
function( result ){
alert(result);
});
but even if in the script php the array is correct (if I echo array[25] I obtain the right value) in Javascript I obtain "Undefined".
How can I get the array in correct way??
thanks!
edit: after encoded with json_encode($array); in php and JSON.parse(result) in javascript seems not working.
In the console I have the array, but I can't access to its values. (Array[0] gave me "undefined").
use this
echo json_encode($array);
on server side
and
var arr=JSON.parse(result);
on client side
As Ruslan Polutsygan mentioned, you cen use
echo json_encode($array);
on the PHP Side.
On the Javascript-Side you can simply add the DataType to the $.post()-Function:
$.post(
'./file.php',
function( result ){
console.log(result);
},
'json'
);
and the result-Parameter is the parsed JSON-Data.
You can also set the correct Content-Type in your PHP Script. Then jQuery should automaticly parse the JSON Data returned from your PHP Script:
header('Content-type: application/json');
See
http://api.jquery.com/jQuery.post/
http://de3.php.net/json_encode
You need to convert the php array to json, try:
echo json_encode($array);
jQuery should be able to see it's json being returned and create a javascript object out of it automatically.
$.post('./file.php', function(result)
{
$.each(result, function()
{
console.log(this.Latitude + ":" + this.Longitude);
});
});

Return JSON object from php script

I am making an AJAX GET request using jQuery to a PHP file. I want the PHP script to return a JSON object, however, currently it is returning a JSON string. I realise I can use JSON.parse in the jQuery code, however, any experience I have in making an AJAX call to an API a JSON object is returned. I am trying to do the same with the php script however, it is returning a string as opposed to an object.
Does anyone know what the best practice is here, and if the best practise is to return a JSON object how I would do this using PHP?
Please see the code below:
js
$.get('test.php', function(data){
console.log((data));
});
php
<?php
$jsonAnswer = array('test' => 'true');
echo json_encode($jsonAnswer);
In your PHP file, change the content type to application/json.
JS
$.get('/process.php', function(data) {
console.log(data);
} );
PHP
<?php
header( "Content-type: application/json" );
$jsonAnswer = array('test' => 'true');
echo json_encode($jsonAnswer);
Then your console should read Object {test: "true"} rather than just the JSON string.
Add json to the end of your get function to return json
$.get('test.php', function(data){
console.log((data));
},'json');//here
and/or add this header in php
header('Content-Type: application/json');
more info here
Without modifying PHP script you can do:
$.get( "test.php", function( data ) {
var arr = $.parseJSON(data);
console.log(arr);
alert(arr.test);
});

Working with javascript array

Hi I have a php script that successfully gets an array of data from an exsternal xml source, the array is called $file, I know that the php array is populated by using print_r($file).
I have tried to use the following php to pass to a javascript session:
//Convert to JSON Array
$jsonarray = json_encode($file, JSON_FORCE_OBJECT);
$result["json_array"]=$jsonarray;
But either this hasn't worked, or the following JS code below is wrong:
var jsonarray = result["json_array"];
alert(JSON.stringify(jsonarray));
Could someone please tell me where I am going wrong?
You should not use JSON.stringify there. JSON.parse is what you are looking for. Since you want to parse existing JSON, not create new JSON.
edit: Your code is a bit odd. I'd think you want something like this
php
//Convert to JSON Array
echo json_encode($file, JSON_FORCE_OBJECT);
js
alert(JSON.parse(data)); // Where data is the contents you've fetched from the server
You have to encapsulate php code :
<?php
$jsonarray = json_encode($file, JSON_FORCE_OBJECT);
$result["json_array"]=$jsonarray;
?>
var jsonarray = <?= $result["json_array"] ?>;
alert(JSON.parse(jsonarray));

How can i parse php variable to my javascript function result?

I have a script, i have to parse javascript variable to PHP file, i've no problem with this function, in my console i can see that the username variable is sent, it's fine .
$.post("user_add-js.php", { username: username })
.done(function(data) {
alert("Data Loaded: " + data);
});
In my user_add-js.php file , i wrote the variable $data with a value but i can't return the value "test", the variable is empty . I guess i forgot to add something in my PHP code to parse the value from PHP to javascript .
<?php
$data = "test";
?>
you need to set the header
header('Content-type: application/json');
and also you have to encode the variable to json like this
echo json.encode($data);
once you get the result to javascript you should parse the json code
data = JSON.parse(data);
This solution helps you get you data from PHP in any format ( object, array, string ... )

Categories

Resources