Get a php array into a js array - javascript

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

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

Combine a string and an array with JSON

I'm trying to combine a string and an array with JSON. No success, so far.
Here is the PHP code:
<?php
$url = ‘example.com’;
$data = file_get_contents($url);
$regex = '/list-animal-id">(.+?)</';
$input = ‘testtext';
preg_match_all($regex,$data, $match);
//var_dump($match);
//echo json_encode($match[1]);
$json = array($input, $match[1]);
$json_data = json_encode($json);
echo $json_data;
?>
$match comes back with an array, for instance:
"22425229","22493325","22596308","24635614","22202322"
The above only creates one instance of the string:
["testtext",["22425229","22493325","22596308"......
I want to create something like this:
"testtext":"22425229", "testtext":"22425230"
Thanks,
What you are looking to do is not possible. [ "testtext":"22425229", "testtext":"22425230" ] assumes an array in which every key is "testtext". You cannot have an array or object with the same key repeated.
What you can do is create an array of arrays where each item is an associative array (object in JSON):
<?php
$url = 'example.com';
$data = file_get_contents($url);
$regex = '/list-animal-id">(.+?)</';
$input = 'testtext';
preg_match_all($regex,$data, $match);
//var_dump($match);
//echo json_encode($match[1]);
function outputArray( $value ) {
global $input;
return array( $input => $value );
}
$json = array_map( 'outputArray', $match );
$json_data = json_encode($json);
echo $json_data;
?>
Output is: [{"testtext":"22425229"},{"testtext":"22493325"},{"testtext":"22596308"},{"testtext":"24635614"},{"testtext":"22202322"}]
my solution was wrong and shouldn't stay here confusing others... the right solution can be found in Jims answere...

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.

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.

How to create javascript array from database by php

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

Categories

Resources