sending json from php to javascript - php

I have a php variable which contain json, I use json_encode to transform an array to json.
If I print my var I have:
["L","M","M","J","V","S","D"]
But if I use my var in js I have:
["L","M","M","J","V","S","D"]
and I can't parse because I have an error
Uncaught SyntaxError: Unexpected token &
Is there a way to get json in my js ?
Thanks
Edit:
In php
$dayArray = array('L','M','M','J','V','S','D');
$dayArray = json_encode($dayArray)
In js
setDayArray('<?php echo $dayArray ?>');
setDayArray = function(dayArray){
console.log(dayArray);
}
With twig
calendar.setDayArray({{ dayArray }});
This is maybe due to symfony rendering, the only way I found is to do an ajax call using json header

To output JSON in PHP, output the result of passing your PHP structure through json_encode.
Example from the documentation:
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
Outputs:
{"a":1,"b":2,"c":3,"d":4,"e":5}
Re your updated question, you've used
$dayArray = json_encode($dayArray)
setDayArray('<?php $dayArray ?>'); // Wrong
Get rid of the quotes, and include echo unless it's magically getting output some other way:
$dayArray = json_encode($dayArray)
setDayArray(<?php echo $dayArray ?>); // Right
When you do that, the browser will see something like:
setDayArray(["L","M","M","J","V","S","D"]); // Right
rather than
setDayArray('["L","M","M","J","V","S","D"]'); // Wrong

I find the solution
calendar.setDayArray({{ dayArray | raw }});
use raw to allow html

Related

Echo/return an array in php

Im trying to query a database from a php file then return the results (userLOC of each row) to the calling Jquery function.
Calling Jquery:
$.post(url, data, function (data)
{
alert(data);
})
relavent PHP:
$sql = "Select * from location";
$result = mysql_query($sql);
$stack = array();
while($row = mysql_fetch_array($result))
{
array_push($stack, $row["userLOC"]);
}
return $stack;
The problem is that I cant return it correctly, if I "echo $stack" it does not work it says Im trying to convert the array to string. If I "echo $stack[0]" it will give me the first result in the array correctly so I know the values are being stored correctly (as are $stack[1], etc.) but this only sends the one value back. And if I "return $stack" as pictured nothing is alerted because nothing is echoed. How would I go about getting the whole array back so that I could iterate through and use them on the jquery side?
In PHP
$foo = array();
echo $foo;
will produce the literal string Array as output.
You need to convert your array into a string. Since you're dealing with a Javascript target, use JSON as the perfect means of doing so:
$foo = array('a', 'b', 'c', 'd', 'e');
echo json_encode($foo);
Then in your JS code:
$.get(...., function (data) {
alert(data[1]); // spits out 'b'
});
Just remember to tell jquery that you're expecting JSON output.
You need to wrap (serialize) the data in a way that can be transported to the client via HTTP and used to get the original data.
Usual container formats are XML and JSON. JSON is well suited for usage in JavaScript, so use the PHP function json_encode() and echo the result.
Youll want to use JSON!
Client-side:
jQuery.post(url, data, function( data ) {
//Data is already converted from JSON
}, "json");
Server-side:
return json_encode($stack);
Explanation
Hope this helps!
echo json_encode($stack); can help you
at jquery side use jQuery.parseJSON()
You need to convert the array to a JSON object like this : return json_encode($stack);
Just convert your array it to a JSON object and return it back to your JavaScript:
return json_encode($stack);
As others have said, you may wish to wrap the output using something like json:
echo json_encode($stack);
However, if you aren't looking for an output with the complexity of JSON formatting, you could just use implode() to output a comma separated list:
echo implode(',',$stack);

json returning string instead of object

i have
$age = implode(',', $wage); // which is object return: [1,4],[7,11],[15,11]
$ww = json_encode($age);
and then i retrieve it here
var age = JSON.parse(<?php echo json_encode($ww); ?>);
so if i make
alert(typeof(<?php echo $age; ?>)) // object
alert(typeof(age)) //string
in my case JSON.parse retuned as string.
how can i let json return as object?
EDIT:
var age = JSON.parse(<?php echo $ww; ?>); // didnt work , its something syntax error
implode returns a string, so it is only natural that json_encode encodes it as such. It does not recognize already JSON-like data passed as a string.
If you want to get an object, you have to pass an associative array to json_encode:
$foo = array(
1 => 4,
7 => 11,
15 => 11
);
echo json_encode($foo); // {1:4,7:11,15:11}
With so little info about what $wage looks like before it's imploded, it's hard to tell exactly what you want to get. How is that structure ([1,4],[7,11],[15,11]) an object? Is the first element of each tuple a key? That's what I assumed with my example, but it might be off.
var age = [<?php echo $age; ?>];
a. You get a syntax error because you need to enclose the string within quotes, like so:
var age = JSON.parse("<?php echo $ww; ?>");
b. Moreover, you don't need JSON.parse. You can simply echo the php var after it was already json_encoded in the server side:
var age = <?php echo $ww; ?>;
JSON.parse is there to convert a JavaScript string to an object. In the case of PHP string, once it is built as JSON, echoing it in the right place is equivalent to coding it yourself.

How to pass php array of arrays to Javascript

I have an array of arrays in PHP in this layout for example,
"Key1" => { "id" => 1, "name" => "MyName", "address" => "USA" }
"Key2" => { "id" => 2, "name" => "MyName2", "address" => "Australia" }
The data in the PHP array was taken from SQL Database. Now I want to be able to use this in JavaScript.
I searched the web and people are suggesting to use JSON using this code:
var js_var = JSON.parse("<?php echo json_encode($var); ?>");
I get this error in firefox when using firebug
missing ) after argument list [Break On This Error]
var js_var = JSON.parse("{"Key1":{"id":"1","name":"MyName","address":"USA"...
Error is in right after JSON.parse("{"Key1
In google chrome, firebug does not report any errors
var js_var = JSON.parse('<?php echo json_encode($var); ?>');
Or, even better:
var js_var = <?php echo json_encode($var); ?>;
... Since JSON is, by definition, valid JavaScript syntax for object declaration.
Why go through this bizarre json_encode into a string to only JSON.parse on the client side? Useless use of encoding, really.
Try var js_var = <?php echo json_encode($var); ?>;
Your error is being cause by the fact you are using double-quotation marks (") to wrap the JSON string. Due to the fact that the JSON string also contains double-quotations the parser is unable to determine when the string starts and ends correctly.
Change the line to this:
var js_var = JSON.parse('<?php echo json_encode($var); ?>');
That been said JSON or JavaScript Object Notation is already a subset of the JavaScript programming language and therefore can already be parsed by the JavaScript engine so does not necessarily need to be parsed by JSON.parse.
var js_var = <?php echo json_encode($var); ?>;
I would however only recommend this option if you are sure about the JSON you are outputting as an incorrect parsing by JSON.parse can be handled where as incorrect JSON injected directly will cause a parser error I believe.

Decoding only one key of Twitter's JSON in PHP and putting it in an array

Using Twitter's search API, I'm being returned a helluva lot of information that is essentially extraneous to me. I'd like to populate an array with just the content of the tweets, none of the metadata.
Here's an example of a request and the response. So basically, I'd like to populate an array with the values of the text key.
I assume the answer would like in some kind of for loop however I don't know where to begin.
Something like this will do it:
<?
$json = json_decode(file_get_contents('http://search.twitter.com/search.json?q=laughter&rpp=100&result_type=recent&lang=en'));
$l = count($json->results);
for ($i=0; $i < $l; $i++) {
echo $json->results[$i]->text . '<br/>';
}
?>
Note: Use whatever reading method you need if file_get_contents isn't allowed to read remote.
try this:
Convert JSON to Array PHP
<?php
//get json
$foo= file_get_contents('http://search.twitter.com/search.json?q=stackoverflow&rpp=10&result_type=recent&lang=en');
//convert to array
$var = json_decode( $foo , true );
//print array
print_r( $var );
?>
Convert Array PHP to JSON
<?php
//declarate array
$foo = array( 1 ,2 ,3 ,4 ,5 , 6 => 7, 8);
//convert to json
$var = json_encode( $foo );
//print json
print_r( $var );
?>
Read:
As of PHP 5.2.0, the JSON extension is bundled and compiled into PHP
by default.
See And Read This JSON PHP Documentation
AND
If you use PHP < 5.2, use JSON Class Objects
Bye!

Jquery json echo

EDIT
Solved it. It was before the ajax call and, hence, this code. Thank you all for the answers.
I can't find anybody with this problem. I have a AJAX call to a PHP script that returns a JSON response.
I fetch the values from a database into an array:
while($row = mysql_fetch_array($ret)){
$temp = array(
'id' => $row['id_reserva'],
'start' => $row['data_inicio'],
'end' => $row['data_fim'],
'title' => $row['descricao']
);
$js[] = $temp;
}
Headers:
header('Content-type: application/json');
And echo:
echo json_encode($js);
There is no return whatsoever, just a null string.
What is really bugging me is that if instead of this I create a json string with the previous result directly in the code:
$temp = '[{"id":"3914", "start": "2011-08-25 09:00:00",
"end":"2011-08-25 18:00:00", "title":"asdasdasd"},
{"id":"3915", "start": "2011-08-25 09:00:00",
"end":"2011-08-25 18:00:00", "title":"asdasdasd"}]';
echo $temp;
It works.
Tried changing the file codification, comparing the strings, checking for some problem with chars, and nothing.
Anybody?
Cheers
you have to encode it. try
echo json_encode($js);
You need to json encode array:
echo json_encode($js);
You're not outputting as JSON?
echo json_encode($js);
With your method, when jQuery gets the response and cannot parse the JSON it will return the empty string as you have experienced.
Process of elimination..
can you print_r ($js) and get output?
Take out the header(); statement, does anything appear?
Do you have error_reporting and display_errors turned on?
You don't seem to initializing 'js' ($js = array()). If you get the literal string 'null' back, this could simply imply that your query is not returning any results.
I could add this statement to almost every long-winded PHP requestion on stack overflow:
Go through your code step by step and echo what you expect the contents of variables to be at that point. Then you'll slowly isolate exactly where your issue is; there's nothing wrong with your code as-is.
Are you not making a multi-dimentional array with $js[] = $temp; and then encoding that? Try just doing json_encode($temp);

Categories