json returning string instead of object - php

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.

Related

Create a Javascript array from a PHP array

I am having trouble converting from a PHP array to a Javascript array and then accessing the value. I have tried JSON encoding and decoding.
PHP:
$simpleArray= [];
$childProducts = Mage::getModel('catalog/product_type_configurable')
->getUsedProducts(null,$_product);
foreach($childProducts as $child) { //cycle through simple products to find applicable
$simpleArray[$child->getVendor()][$child->getColor()] = $child->getPrice();
var_dump ($simpleArray);
}
Javascript:
var simpleArray = <?=json_encode($simpleArray)?>;
//..lots of unrelated code
for(var i=0; i < IDs.length; i++)
{
console.log(simpleArray);
//which color id is selected
var colorSelected = $j("#attribute92 option:selected").val();
console.log('Value of color selected is ' + colorSelected);
$j('.details'+data[i].vendor_id).append('<li class="priceBlock">$'+simpleArray[i][colorSelected]+'</li>');
}
Edit:
I have gotten rid of the simpleArrayJson declaration in the php and changed the first line of the javascript.
The is no reason for you to json_decode() the value you are trying to output. Just echo it directly:
var simpleArray = <?= $simpleArrayJson ?>;
This will output a javascript object literal.
Remove from the php.
$simpleArrayJson=json_encode($simpleArray, JSON_FORCE_OBJECT);
here you are converting the php array into a json string.
Change in the javascript
var simpleArray = <?= json_encode($simpleArray, JSON_FORCE_OBJECT); ?>;
Here you are just outputting the sting. previously you where doing this
var simpleArray = <?=(array) json_decode($simpleArrayJson)?>
which after json_decode was returning an array, which you where casting to an array which then was cast to a string by the <?= so what ended up going to your browser was something like:
var simpleArray = Array;
try a for in loop.
for( item in data ) {
console.log(data[item]);
}
this is because json has keys that match the indexes of the array that was json_encoded, instead of necessarily 0->n indexes.
Edit thanks to comments changed data.item to data[item]

Json decode in javascript

i have encoded my required data in the json object ,but i want to decode the json object into a javscript array, my json encoded object is :
{"product_id":"62","product_quantity":"65"}
however i want to use this json in my java script and want it to be available to a java script array
so if i do :
var arr = new Array()
arr = <?php json_decode('$json_object',TRUE); ?>;
however when i check my page source i get null i.e arr =
how can i assign my json object converted to array to java script array ?
further how to access the json objects from java script array ?
json_decode returns a PHP data structure. If you want to serialise that to a JavaScript data structure you have to pass it through json_encode (and then actually echo the string that it returns).
Note that json_encode outputs a JavaScript data structure that is safe for injecting into a <script> element in an HTML document. Not all JSON is safe to do that with (PHP adds additional escape sequences, and will transform plain strings, numbers, null values, etc (which aren't legal JSON on their own).
Note that there is also no point in creating a new array and assigning it to arr if you are going to immediately assign something else to arr.
Also note that '$json_object' will give you a string starting with the $ character and then the name of the variable. Single quoted string in PHP are not interpolated.
var arr;
arr = <?php echo json_encode(json_decode($json_object,TRUE)); ?>;
Also note that this JSON:
{"product_id":"62","product_quantity":"65"}
Will transform in to a PHP associative array or a JavaScript object (which is not an array).
So given this PHP:
<?php
$json_object = '{"product_id":"62","product_quantity":"65"}';
?>
<script>
var arr;
arr = <?php echo json_encode(json_decode($json_object,TRUE)); ?>;
alert(arr.product_id);
</script>
You get this output:
<script>
var arr;
arr = {"product_id":"62","product_quantity":"65"};
alert(arr.product_id);
</script>
Which alerts 62 when run.
You could push the JSON objects into javascript array and iterate through the array, selecting the appropriate fields you need.
Fixed it..
var json = {"product_id":"62","product_quantity":"65"};
var array = new Array();
array.push(json);
for(var i = 0; i < array.length; i++){
console.log(array[i].product_id)
}
Okay so to start off :
the json string generated in PHP can be used in Javascript as an Object. If you declare the variable as an array to start with then it might conflict.
anyway this should work :
<?php
$error_fields_structure = array(
'product_id' => 4531
,'main_product_quantity' => 2
);
$json_object = json_encode($error_fields_structure);
?>
<html>
<head>
<script>
var jsonstring = <?php echo (isset($json_object) ? $json_object : 'nothing here'); ?>
for( var i in jsonstring ){
alert( i +' == ' +jsonstring[i] );
}
</script>
</head>
<body>
</body>
</html>

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.

How to read php array of string in javascript

var longitudeArray = new Array(<?php $result = count($longitudeArray);
if ($result > 1){
echo implode(',', $longitudeArray);
} else {
echo $longitudeArray[0];
}
?>);
$longitudeArray contain array of number like: $longitudeArray = array(23.54545, 2323.32);
Above script create following javascript array:
var longitudeArray = new Array(12.32444,21.34343,23.5454);
but if i passes string in $longitudeArray like:
$longitudeArray = array('one', 'two');
instead of integer value in $longitudeArray then my javascript array is not creating properly or its not working.
Try
var longitudeArray=<?=json_encode($longitudeArray)?>;
If you pass an array of strings to your code, you will end up without quotes around them in your generated javascript code. You need to add some quotes somehow, something like:
var longitudeArray = new Array("<?php echo implode('","', $longitudeArray);?>");
#Shad, very useful and efficient approach. In the same manner, if one is trying to convert a PHP array to pass back to a JavaScript function (EG: an AJAX callback), that would be accomplished as such:
$some_php_array = array( 'indexA' => 'nice', 'indexB' => 'move' );
json_encode($some_php_array);
Where the PHP data would look as follows in JavaScript:
{"indexA":"nice","indexB":"move"}

PHP array to JS array with jQuery and json_encode

I just want to get my PHP array to a JS array, what am I doing wrong here?
PHP:
// get all the usernames
$login_arr = array();
$sql = "SELECT agent_login FROM agents";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
array_push($login_arr, $row["agent_login"]);
}
$js_login_arr = json_encode($login_arr);
print $js_login_arr; // ["paulyoung","stevefosset","scottvanderlee"]
JS:
var login_arr = "<?= $js_login_arr; ?>";
alert(login_arr); // acn't even get the string in??
var obj = jQuery.parseJSON(login_arr);
Remove the quotes from the embedded PHP in your javascript. The notation is an array literal, and doesn't need quoting (assuming the PHP comment after js_login_arr is the what is printed into the javascript).
An easy way to do it is through delimiting. Take your array (don't use assoc arrays unless you need the field names), implode it into a string delimited by some character that shouldn't be used, say % or something, then in JS just explode on that character and voila, you have your array. You don't need to always use formalisms like JSON or XML when a simple solution will do the trick.
If you want to make php array to JSON you have to do this if $phpArray is actually an array.
var jsJSON = echo json_encode($phpArray)
If you want just to echo and turn to JSON you have to give it like a string:
$phpArray = '{'.$key1.':'.$val1','.$key2':'.$val2.'}';
This will work for sure.

Categories