How can get values from php array using jquery or javascript? - 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.

Related

How to get value from a PHP array in JavaScript?

Let's say we have one PHP array:
$decoded = array(
'method' => 'getFile',
'number' => '12345'
);
The array data will pass to another JavaScript get function(params).
function get(params) {
}
How I get the $decoded['method'] value in JavaScript language in the get function?
<?php
$decoded = array(
'method' => 'getFile',
'number' => '12345'
);
?>
<script>
var params = <?php echo json_encode($decoded); ?>;
get(params);
function get(params){
console.log(params);
console.log(params['method']);
}
</script>
Use this way. you have to get php variable or array inside javascript by printing or echo. Then you can call function.
Javascript array and PHP arrays are not equal. But the objects of both languages are equal. Then you can JSON encode your array in PHP and pass the encoded value in the javascript.
For example:
In PHP
<?php
$decoded = array(
'method' => 'getFile',
'number' => '12345'
);
?>
In JS
var params = <?php echo json_encode($decoded); ?>;
function get(params) {
console.log('method', params.method);
console.log('number', params.number);
}

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

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 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