How to get value from a PHP array in JavaScript? - 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);
}

Related

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); ?>;

problems parsing JSON in javascript from PHP

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 ); ?>" );

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!

how to make this javascript object from php json encode

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')
)
)
);

How can get values from php array using jquery or javascript?

I trying to get data from php array and put in java-script variable. Follwoing are the php arrays.
Array Name
Array
(
[0] => username
[1] => byusers
)
Array Value
Array
(
[0] => user
[1] => 1
)
What I have Try tried
Get php array value in javascript variable
var DATATABLE_SEARCH_NAMES = new Array( "<?php echo (is_array($DATATABLE_SEARCH_DATA_NAMES)) ? $DATATABLE_SEARCH_DATA_NAMES['names'] : 0;?>");
var DATATABLE_SEARCH_VALUES = new Array( "<?php echo (is_array($DATATABLE_SEARCH_DATA_VALUE)) ? $DATATABLE_SEARCH_DATA_VALUE['values'] : 0;?>");
This should do what you ask, it is just a case of converting the PHP arrays to a form that javascript can understand. You can use json_encode() to do that.
$DATATABLE_SEARCH_DATA_NAMES = array('username','byusers');
$DATATABLE_SEARCH_DATA_VALUE = array('user', 1);
$js1 = json_encode($DATATABLE_SEARCH_DATA_NAMES);
$js2 = json_encode($DATATABLE_SEARCH_DATA_VALUE);
//echo $js1.PHP_EOL;
//echo $js2.PHP_EOL;
echo "<script>\n";
echo 'var names = ' . $js1 . ";\n";
echo 'var values = ' . $js2 . ";\n";
echo "</script>\n";
say, you have a PHP array as this:
$arr = array("key1"=>"foo","key2"=>"bar");
the easiest way to put it to javascript is this:
var arr = <?php echo json_encode($arr); ?>;
ending with a JSON object.

Categories

Resources