hello i am trying to figure out how i would ago about pulling information from a database in php and json_encoding it ito a JavaScript object that contains several JavaScript arrays that themselves have children objects and arrays.
below is the JavaScript i need. ive been playing with embedding arrays into php objects but cant seem to get it to come our correctly.
self.navigation = [
{
menutext:"Home",
url:"/"
},
{
menutext:"About",
url: "#/about",
submenu:[
{
menutext:"Pricing",
url: "/pricing"
}
]
}
];
<script type="text/javascript">
var jsObject = <?php echo json_encode($phparray); ?>;
</script>
pretty self-explanatory i think, if you need the object a specific way it's about how you format your php array itself.
To get arrays within objects you use the object key and set it to an array like so:
$phpArray = array(
'magic' => array('elmo')
);
json_encoded an array will be within the "magic" object. In order to get the parent item as an array with objects inside i would just fudge it in the variable setting itself like so:
<script type="text/javascript">
var jsObject = [<?php echo json_encode($phparray); ?>];
</script>
To get submenu into array have you tried the following:
$phpArray = array(
'menutext' => 'About',
'url' => '#/about',
'submenu' => array(
array(
'menutext' => 'Pricing',
'url' => '/pricing')
)
);
Bit unintuitive I know. Actually to get exactly what you want without fudging it would be:
$phpArray = array(
array(
'menutext' => 'Home'
),
array(
'menutext' => 'About',
'url' => '#/about',
'submenu' => array(
array('menutext' => 'Pricing',
'url'=> '/pricing')
)
)
);
Related
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);
}
I have array like below,
Array
(
[0] => http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911570.png
[1] => http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911570.png
[2] => http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911571.png
)
I want to split above array and each key value has to stored in localStorage like 'front'=> array[0],'back'=>array[1],'side'=>array[0].
How to achieve this. ?
If your array is in JAVASCRIPT, you can access to the array elements directly, so you can call the localStorage function directly...
var yourArray = [
'http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911570.png',
'http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911570.png',
'http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911571.png'
];
localStorage.setItem('front',yourArray[0]);
localStorage.setItem('back',yourArray[1]);
localStorage.setItem('side',yourArray[2]);
If your array is in PHP, you'll have to add a <script> element...
<?php
$yourarray = array(
"http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911570.png",
"http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911570.png",
"http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911571.png"
);
?>
<script>
localStorage.setItem('front','<?=$yourarray[0]?>');
localStorage.setItem('back','<?=$yourarray[1]?>');
localStorage.setItem('side','<?=$yourarray[2]?>');
</script>
you can have separate script (test.php) and have a json out as below
<?php
$arr1 = array(
0 => 'http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911570.png',
1 => 'http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911570.png',
2 => 'http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911571.png'
);
$arr2 = array('front'=>'', 'back'=>'', 'side'=>'');
// assign values from array 1 to array 2
$arr2['front'] = $arr1[0];
$arr2['back'] = $arr1[1];
$arr2['side'] = $arr1[2];
echo json_encode($arr2);
then from javascript you can access this object as follows and store it in local storage
<script>
$(document).ready(function () {
$.get("test.php", function (data, status) {
var out = JSON.parse(data);
// Store in local storage
localStorage.setItem("frontElem", out.front);
localStorage.setItem("backElem", out.back);
localStorage.setItem("sideElem", out.side);
var side = localStorage.getItem("sideElem", out.side);
console.log(side)
});
});
</script>
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); ?>;
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 ); ?>" );
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!