Pass array from php to javascript method - javascript

In my php i make a db call, and the result is
$options = mysqli_fetch_array($result);
Now, I want to make a javascript method call and pass this function. My javascript method looks like
function myFunction(options){
//iterate over each option
}
and what I am doing is
<?php echo "<script>myFunction('".$options."')</script>";
This gives me error on my server that I am doing array to string conversion.
I thought javascript determined the datatype on runtime and hence I'll be ok with this. can someone please tell me the correct way of doing this?
Thanks

To have PHP print out an array JavaScript can use, you can convert the array to JSON string and then echo that directly.
# Convert PHP array to JSON array
$json_options = json_encode($options);
# Echo JavaScript and JSON without single quotes
<?php echo "<script>myFunction(".$json_options.")</script>";

You can not pass a php array into javascript function as array. However you can pass it as stated by Grokify or you can pass it directly assign into your a javascript variable if your function is on same page by giving into php environment.
function myFunction(){
var options = <?php echo json_encode($options); ?>;
}

Firstly, declare your JS function.
function myFunction(options){
options = JSON.parse(options);
for(var i=0; i<= options.length; i++){
console.log(options[i]);
}
}
And in your PHP side, convert array into JSON and pass it to JS function
$json = json_encode($options);
# Echo JavaScript and JSON without single quotes
<?php echo "<script>myFunction(".$json.")</script>";

Related

Return array containing SQL query results to a webpage using JSON

I have a PHP script that runs an SQL query. I'd like to put the results in an array, encode it as a JSON object, echo it back to the Javascript that called it, and use it as an array to write some HTML.
This is the JS which calls the PHP script using POST. I attempt to parse the echoed data using JSON.parse(data) (I also tried jQuery.parseJSON(data) - not sure if there's a difference), and I display the raw echoed data on the HTML page for testing.
var components = []; // create empty array for component list
if ($('#area').val) { // if area contains a value and isn't zero (i.e. an area has been selected)
$.post("/basic/get_area_components.php"
,{area: $("#area").val()}
,function(data){ components = JSON.parse(data);
$("#components_raw").html(data);
$("#components").html(components);
});
}
The PHP script (after the database connection has been set up) looks like this:
$result = $conn->query("SELECT Component FROM ConfigComponent WHERE Parent =" . $area);
while($row = $result->fetch_array()) {
$rows[] = $row;
}
$i = 1;
foreach ($rows as $value) {
$components[$i] = $value[0];
$i++;
}
echo json_encode($components);
When I run the script, I get the raw output on the HTML page as follows:
{"1":"Handlebar","2":"Stem","3":"Headset","4":"Fork"}
which appears to be a correctly formatted JSON object, but nothing from the parsed components array, and no exceptions. I have tried scanning the array using forEach and printing or alerting the elements individually, to no avail.
How can I parse the JSON object correctly and use it in the Javascript? Is it a problem with the JS parsing, or the PHP encoding?
This behavior is normal. Javascript only support indexed arrays. Because your index in php starts with 1 instead of 0 it becomes an associative array instead of indexed.
$i = 0; // start with 0
foreach ($rows as $value) {
$components[$i] = $value[0];
$i++;
}
or
foreach ($rows as $value) {
// or don't use an index when adding a value to the array
$components[] = $value[0];
}
This will result in a json array
["Handlebar","Stem","Headset","Fork"]
Interesting problem. In Js the line:
{"1":"Handlebar","2":"Stem","3":"Headset","4":"Fork"}
Is no longer an array. It's an object. It seems jQuery actually disregards objects passed into the .html() method. It will render strings or execute functions.
So, you are already doing it right it's just not displaying to the page properly. I suggest using console.log instead.
Try defining the type of data javascript should expect from the server. Try the following
$.post("/basic/get_area_components.php",
{area: $("#area").val()},
function(data){
var components = JSON.parse(data);
$("#components_raw").html(data);
$("#components").html(components);
},
"json"); //define expected type here
Try it out and let me know if it works for you. More information on how to use $.post() can be found here
I suppose you're using jquery there so this maybe of help:
How do I iterate over a JSON structure?
and yes for loop will also do:
var componentFormatted;
for (var k in obj){
componentFormatted += obj[k];
}
then just apply any of your formatted output here
$("#components").html

while passing php 2d array to Javascript and try to parse using json_encode() It throws uncaught type error

I i try try to access passed php 2d array using json_encode function in javascript it throws the error that its an uncaught typeerror and the array is null, but if i print the contents of array in php only it is printing and having values in it. but it is not passing to javascript.
Both javascript and php are in same file.Below is simply a sample code snippet
var javascript_var = echo json_encode($Php_2D_array);
alert(javascript_var[0].OrderDate[1]); //javascript_var['OrderDate'].[1] earlier i tried to access like this because im having php variable index as a name as mentioned
Please help me sort out this problem
Thanks.
Try this:
var javascript_var = JSON.parse("<?php echo json_encode($Php_2D_array); ?>");
alert(javascript_var[0].OrderDate[1]);
First you need to convert to json and then javascript will take it as string, then you parse it in js.
you can encode array value in javascript by using instruction
JSON.stringify
if your array variable is in php then
var javascript_var = JSON.stringify('<?php echo $Php_2D_array?>');
if your array variable is in javascript
var javascript_var = JSON.stringify(var_array);

Creating "objects" and "arrays" in PHP in a way that would allows JS to distinguish between them

PHP's syntax to create an array (either indexed or assosiative) is the same, aka
$arr = [];
However, json_encode will convert an empty PHP "array" (note the quotes) to an empty JS array ([]), which is not desirable in certain situations.
Is there a way I can create an empty assosiative array in PHP, so json_encode will convert it to an empty JS object, aka {}, instead of [].
You can use stdClass:
$obj = new stdClass();
echo json_encode($obj);
This gets me the intended {} output.
Use a stdClass():
php > $x = new StdClass;
php > echo json_encode($x);
{}
Of course, once it's a stdclass, you wouldn't be able to use it as an array anymore. But this is at least one way of forcing an empty object in JSON, so you could just special-case your code:
if (count($array) == 0) {
$json = json_encode(new StdClass);
} else {
$json = json_encode($array);
}
You can just pass the JSON_FORCE_OBJECT option to the json_encode function. This will force any empty arrays to be objects as well.
JSON_FORCE_OBJECT (integer) Outputs an object rather than an array
when a non-associative array is used. Especially useful when the
recipient of the output is expecting an object and the array is empty.
Available since PHP 5.3.0.
So:
if (empty($array)) {
$json = json_encode([], JSON_FORCE_OBJECT);
} else {
$json = json_encode($array);
}
This looks cleaner than converting an object in my opinion.
Or even
$json = json_encode($array, empty($array) ? JSON_FORCE_OBJECT : 0);

Convert php array of objects to javascript array

if i have an associative array in php.
Say, in the same view, i have $params array:
$parameters = array(
'parameter1'=>'value1',
'parameter2'=>'value2
);
Is there any way or php function or even javascript function to convert the php array to javascript array? in such a way that if we have the converted array, jsParameters, you'd be able to access it's fields and values like :
console.log(jsParameters.parameter1);
console.log(jsParameters.parameter2);
that will output, 'value1' and 'value2'. Is there a way? many Thanks!
Use json_encode:
console.log(<?php echo json_encode($parameters); ?>);
Use json_encode:
echo json_encode($parameters);
You should be able to call json_encode on the array, and echo that back to your application.
Check out the docs here

JS variable inside JSON string from PHP

I am generating a JSON string from a PHP array to echo a JS object.
This is what I want to get in js:
var myVar = 123;
//php output:
var obj = {a:1, b:[1,2], c: myVar, d:Date.UTC(2014, 0, 07)}
This is what I have:
<?php
$array = array('a'=>1, 'b'=>array(1,2), 'c'=>???, 'd'=>???);
echo json_encode($array);
?>
The question is: What I put in PHP instead of question marks so that it won't be converted to string?
JSON doesn't support variables or special Date objects. You can only use scalar values (strings, numbers, booleans), arrays and objects (associative arrays).
A way to get what you want would be to return a .js file and have the browser execute that (by including it as a script) instead of transferring simple JSON data. Otherwise you could only define "special" strings that are handled by the receiving side. (For example, array ["var", "myVar"] could be parsed accordingly.)
You could actually do something like that:
<?php
$array = array('a'=>1, 'b'=>array(1,2),
'c'=>'##myVar##',
'd'=>'##Date.UTC(2014, 0, 07)##'
);
$json = json_encode($array);
echo preg_replace('/\"\#\#(.*?)\#\#\"/', '${1}', $json);
?>
But in js JSON.parse won't work, so:
eval("var x = " + json_from_php);
Not such a good idea, but if you need it, it'll work. Just remember not to use this with any "json" which are generated not by your server.

Categories

Resources