How to create javascript array from database by php - javascript

I want to create a javascript array from databse like this:
var m = [
[one]
[two]
[three]
]
it is important that typeof m be object.

Use Json_encode
$phparray; // This is your php array
$jsArray = <?php echo json_encode($phparray); ?>;
//do stuff with $jsArray now

Related

" " instead of [ ] in JSON

I used a php variable into Javascript like this-
var Coordinates = <?php echo json_encode($coords); ?>;
And now I want to stringify it so I used
var JSON_Coordinates = JSON.stringify(Coordinates);
the result is
["-98.47442960102632,38.51861967935271","-98.46128420909388,38.17510666712973","-97.91584295178713,38.17274814619617", -"97.91882439611877,38.51683243137235", "-98.47442960102632,38.51861967935271"]
But I want It to be like this-
[[-98.47442960102632,38.51861967935271],[-98.46128420909388,38.17510666712973],[-97.91584295178713,38.17274814619617], [-97.91882439611877,38.51683243137235], [-98.47442960102632,38.51861967935271]]
So how to replace " " with [ ]?
You could fix it on the server side:
$coords = array(
'-98.47442960102632,38.51861967935271',
'-98.46128420909388,38.17510666712973',
'-97.91584295178713,38.17274814619617',
'-97.91882439611877,38.51683243137235',
'-98.47442960102632,38.51861967935271'
);
$coords = array_map(function($coord) {
list($lat, $lon) = explode(",", $coord);
return array((float) $lat, (float) $lon);
}, $coords);
echo json_encode($coords);
Output (pretty printed):
[
[-98.474429601026, 38.518619679353],
[-98.461284209094, 38.17510666713],
[-97.915842951787, 38.172748146196],
[-97.918824396119, 38.516832431372],
[-98.474429601026, 38.518619679353]
]
Before converting to json in php, you could convert each coords string to an array in a loop, then ensure values are not strings but numeric using JSON_NUMERIC_CHECK
<?php
foreach ($coords as &$value) {
$value = explode(',', $value); // prevent to array like ["23","45"]
}
unset($value); // avoid reuse of &reference variable by mistake
echo json_encode($coords, JSON_NUMERIC_CHECK);
?>

Get a php array into a js array

I want to get a php array made by pg_fetch_all in a javascript array. But when I try to do it, firebug tells me that I'm trying to convert an array to string. Indeed, I don't understand why because both are arrays.
Here is where I create the php array :
$conn_string = "host=localhost port=5432 dbname=test_postgre user=postgres password='1234'";
$dbconn = pg_connect($conn_string);
$sql = "SELECT ".$colonne." FROM public.".$tablevar."";
$res = pg_query($sql) or die("Pb avec la requete: $sql");
$data = pg_fetch_all($res);
And here is my js code :
var array_dropdown =[<?php echo $data;?>];
And it doesn't work. Please help me !
PHP Arrays 101: Arrays in a string context are the literal word Array:
$x = array(1 => 2);
echo $x; // ouputs "Array"
You need to use json_encode():
var array_dropdown = <?php echo json_encode($data); ?>;
json_encode guarantees that whatever you pass in to the encode function will be output as syntactically valid javascript. Note the lack of [] around the above code - json_encode handles all of that for you.
Assume this as your PHP array
$array = array('foo' => 'bar');
The JS part:
var array = <?php echo json_encode($array); ?>;

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.

Storing data from MySQL to PHP Array to return with JSON

I have a MySQL table with cols | btn_id | btn_title | btn_bg | btn_text |.
I am trying to get the data in the table to a php array and then return via JSON so the array can be used in the JS document requesting the PHP/MySQL Data. Respective of row and columns/index.
So far i have:
$sql = 'SELECT *
FROM btn_color_presets
';
$result = mysqli_query($sql);
$array = array(); //
while($row = mysql_fetch_assoc($result)) //
{
$array[] = $row;
$index++;
}
Q. Now i wish to return a JSON Array made from the array of data. How do i proceed here?
Note: I am horrible with arrays and not entirely sure i have the correct method above for my requirements, but i think it is correct.
Call json_encode after the loop:
header("Content-type: application/json");
echo json_encode($array);

Copying array values from php to javascript

I have a php array
array(6) {
["merchant_id"]=> string(6) "ajeesh"
["passkey"]=> string(4) "1234"
["amt"]=> string(5) "10.00"
["email"]=> string(16) "ajeesh#gmail.com"
["mobileNo"]=> string(10) "9874563210"
["orderID"]=> string(6) "123456"
}
which I got as a result of var_dump($_POST).
How can I copy all this value to a javascript array variable?How can it be possible? Suppose if the javascript array I made is
var thisSession = new Array();
TRY
I have tried this in the javascript
<script>
window.onload = function getApp(){
var thisSession = JSON.parse('<?php echo json_encode($_POST); ?>');
alert (thisSession);
}
</script>
and this in the php
json_encode($_POST);
but the javascript is alerting "Object object".Im not gettign the array!why?
You can use JSON, encode the PHP variable, then parse it in JS:
var thisSession = JSON.parse('<?php echo json_encode($_POST); ?>');
using php's json_encode & javascript's JSON.parse
var thisSession=JSON.parse('<?php echo json_encode($phparray)?>');
EDIT
If you want to access merchant_id you simply do
alert(thisSession.merchand_id);
Here, you need to json_encode the php data to use in javascript
$array = json_encode($_POST);
In your html
<script>
var data = JSON.parse("<?php echo $array; ?>"); // your new javascript object
</script>
Reference http://www.php.net/json_encode
There is no comparable object (associative array) in JavaScript to that which you've shown us in your example. You'd either have to use two Arrays or lose the ordering (and ability to have multiple keys of the same name) by using an Object. This second option is what json_encode will result in.

Categories

Resources