Pass a PHP Array to a JavaScript Function

Pass a PHP array to a JavaScript function

In the following example you have an PHP array, then firstly create a JavaScript array by a PHP array:

<script type="javascript">
day = new Array(<?php echo implode(',', $day); ?>);
week = new Array(<?php echo implode(',',$week); ?>);
month = new Array(<?php echo implode(',',$month); ?>);

<!-- Then pass it to the JavaScript function: -->

drawChart(<?php echo count($day); ?>, day, week, month);
</script>

How to pass PHP array parameter to Javascript Function?

Your PHP variables only live on the server. They are completely separate from the JavaScript variables on the client. The only mechanism for passing values from the server to the client is through the contents of the web page (or through specially requested behind-the-scenes web content through AJAX).

This means that to make your JavaScript receive PHP values, you have to write JavaScript with those values embedded inside of it. You must mix the PHP with the JavaScript at least a tiny bit to get the stuff that runs on the client to have any data from the server.

This is how all web server-side scripting works in all languages.

JavaScript simply cannot know what goes in your movies variable unless you stuff it full of values, in JavaScript.

I recommend you to @levu's answer to see a good way to get your PHP variable's values into JavaScript.

How to Pass a PHP array to JavaScript function?

You forgot the $ to referrence the chartvals var at the json_encode() function call:

var s1 = <?php echo json_encode(chartvals); ?>;

Should be

var s1 = <?php echo json_encode($chartvals); ?>;

To not trap into this sort of mistakes again you can add error_reporting(E_ALL); to the beginning of your script and set display_errors to on in your PHP config during development.

How can I pass a PHP array as an argument to a JavaScript function

I'd recommend using the PHP function htmlspecialchars -- that will not only take care of issues with quotes, but any other characters (&, <, >} that should be turned into HTML entities before being used as HTML attribute values.

$json = htmlspecialchars(json_encode($array));

How to pass an php associative array as argument to Javascript function with json_encode()

The quotes in the generated JSON confuse the html parser. You need to entity encode the contents of tag attributes. You can use htmlspecialchars() or htmlentities() for this:

<?php
$arr = [ "A" => 1, "B" => 2, "C" => 3 ];
?>
<button onclick="test(<?=htmlentities(json_encode($arr))?>);">test</button>
<script>
function test(x){
alert(x["A"]);
alert(x["B"]);
alert(x["C"]);
}
</script>

Pass php array in onclick attribute of button and read it in javascript

You pass a json object so you shoudn't wrap it with any apostrophes.

Here is how it should be:

<?php
$output = '<tr><td>
<a class="btn btn-primary" role="button" onclick="ProductExtraModal(`'.$data['id'].'`,`'.$data['name'].'`,'.allSizes($data['id']).')"></a>
</td></tr>';

The problem is, json will contain " so it will break the HTML's attribute wrapper.

The final solution will be somethong like this:

<script>
// put this outside the loop
var allSizes = {};
</script>
<?php
$output = '<tr><td>
<script>allSizes[' . $data['id'] . '] = ' . allSizes($data['id']) . ';</script>
<a class="btn btn-primary" role="button" onclick="ProductExtraModal(`'.$data['id'].'`,`'.$data['name'].'`,allSizes[' . $data['id'] . '])"></a>
</td></tr>';

Or escaping the apostrophes.

Edit

According to your comment, you have another issue: you are not getting the expected array.

I guess this happens beacuse in your allSizes function you aren't looping through $product_size_search, and you only call mysqli_fetch_array once.

Use this code instead, to loop throgh all product sizes:

function allSizes($product_id)
{
include("../../include/config.php");

$allSizes = array();
$extraDataIds = array();

$products_extra_search = mysqli_query($link,"SELECT product_size from products_extra WHERE product_id = $product_id");

while ($products_extra_data = mysqli_fetch_array($products_extra_search)) {
$extraDataIds[] = $products_extra_data['product_size'];
}

$product_size_search = mysqli_query($link,"SELECT size from products_size WHERE id IN (" . implode(",", $extraDataIds) . ") GROUP BY size");

while ($products_size_data = mysqli_fetch_array($product_size_search)) {
$allSizes[] = $products_size_data["size"];
}

return json_encode($allSizes);
}

Passing (laravel) Array in Javascript

var app = @json($array);

Works like a charm

Convert php array to Javascript

Spudley's answer is fine.

Security Notice: The following should not be necessary any longer for you

If you don't have PHP 5.2 you can use something like this:

function js_str($s)
{
return '"' . addcslashes($s, "\0..\37\"\\") . '"';
}

function js_array($array)
{
$temp = array_map('js_str', $array);
return '[' . implode(',', $temp) . ']';
}

echo 'var cities = ', js_array($php_cities_array), ';';


Related Topics



Leave a reply



Submit