Welcome Guest, Not a member yet? Register   Sign In
Passing array from PHP to JS
#1

[eluser]agubski[/eluser]
Hi Everyone,

I'm having a technical problem to pass an array (which is database query) to JS on the page. Any help will be appreciated.

Code:
<?php foreach($query->result() as $row): ?>

???????????????

<?php endforeach; ?>
#2

[eluser]Colin Williams[/eluser]
Look at json_encode() for one option.

Code:
print json_encode($query->result());
#3

[eluser]madeks[/eluser]
I guess your problem is the generated JS is a multiple line of string?

The easiest way may be to use a library to handle it like Colin said.

Or you may want to search the google for a multiple line of JS string.
#4

[eluser]agubski[/eluser]
I have found a relatively easy solution. here it is:

Code:
<?php
# create PHP array:
$php_array = array("one", "two", "three");
# "pass" php array to JS array:
echo "[removed]\n";
echo "var js_array = new Array();\n";
$ix = 0;
foreach($php_array as $key => $value)
{
echo "js_array[$key] = $value;\n";
}
# .....rest of JavaScript.....
echo "[removed]\n";
?>

now I have another problem of generating 3 php arrays from database query output. each array must contain values for a specific database field (column)

I'm using follwing construct;

Code:
<?php foreach($query->result_array() as $row): ?>    
<?
{
    echo element('MyFirstColumn', $row);
  
}   ?>
<?php endforeach; ?>




Theme © iAndrew 2016 - Forum software by © MyBB