...
$php_array = mysqli_fetch_all($result,MYSQLI_ASSOC);
?>
<script type='text/javascript'>
<?php
$js_array = json_encode($php_array);
echo "var location = ". $js_array . ";\n";
?>
</script>
How can I modify the above code that gives me this output (an array of objects methinks?)
var javascript_array = [
{"city":"Hermosa Beach","lat":"33.860069","lng":"-118.398784"},
{"city":"San Jose","lat":"34.694628","lng":"-118.398784"},
.... ]
to give me this... (an array of arrays?)
var javascript_array = [
["Hermosa Beach",33.860069,-118.398784],
["San Jose",34.694628",-118.398784],
.... ]
without a bunch of foreaching's...
Use MYSQLI_NUM instead of MYSQL_ASSOC when you call mysqli_fetch_all(). Then the rows will be indexed arrays instead of associative arrays.
Although I don't know why you would want the array to be like this. Arrays should be used for uniform data, objects should be used for heterogeneous data.
thanks, this works and is very lean...
<?php
$query = "SELECT * FROM file";
$result = $con->query($query);
// Fetch all rows and return the result-set as an associative array:
// using numeric keys for the array, instead of creating an associative array.
$php_array = mysqli_fetch_all($result,MYSQLI_NUM);
?>
<script type='text/javascript'>
<?php
// create a JSON representation of a value that javascript will understand
$js_array = json_encode($php_array);
// dump json object into javascript variable 'locations'
echo "var locations =" . $js_array . ";\n";
?>
</script>
Related
I have a PHP variable which contains a JSON object in string format.
<?php
$url = "http://ip-api.com/json";
$phpObj = file_get_contents($url);
?>
Javascript:
<script>
var obj = "<?php echo $phpObj; ?>";
</script>
When I try to echo a PHP variable in javascript, I get the following error:
Uncaught SyntaxError: Invalid or unexpected token.
I've tried using json_encode, but it gives me the same error.
No need to use the quotes ("s) and json_encode as it is already a JSON object. Try
var obj = <?php echo $phpObj; ?>;
When I ma fetching the data and try -
<?php
$phpObj = file_get_contents("http://ip-api.com/json");
?>
<script>
var obj = <?php echo $phpObj; ?>;
console.log(obj);
</script>
I am getting -
{as: "AS45194 Syscon Infoway Pvt. Ltd.", city: "Thane", country: "India", countryCode: "IN", isp: "Syscon Infoway Pvt.", …}
in the console.
Passing simple arrays or arrays of objects between PHP and JavaScript can be done through json_encode and json_decode respectively. For instance, in your case, I can do the following
<?php
$url = "http://ip-api.com/json";
$phpObj = file_get_contents($url);
?>
<script>
var obj = <?php echo $phpObj; ?>;
</script>
Since the data fetched is JSON.
However, this fully depends on your application. If $phpObj = file_get_contents($url); returns json then I will simply do the following
<script>
var obj = <?php echo $phpObj; ?>;
</script>
If it's an object that is returned($phpObj), then I will, first of all, convert the object to an array then parse it into JSON format then echo it to JavaScript as shown below
<script>
var obj = <?php echo json_encode((array)$phpObj); ?>;
</script>
If it's an array that is returned, then I will parse the variable to JSON format then echo it to JavaScript as shown below
<script>
var obj = <?php echo json_encode($phpObj); ?>;
</script>
For the case of json_decode, if for instance, you want to use the value returned by file_get_contents($url); and assuming this returns JSON, you can convert the JSON to a PHP array or a PHP object as shown below,
$data_obj = json_decode($phpObj); //Return object not array
$data_arr = json_decode($phpObj,true); //Return array not object
So I am currently doing some coding for the website of someone of my outer family and I had to create a bar chart and now I need to fill it with data from their SQL-Database. First I just echo'd the array like this:
PHP:
<?php
$exampleArray = ["212", "33", "7"]
?>
and JS:
<script> var jExampleArray = <? echo json_encode($exampleArray);?>; </script>
And then I used jExampleArray in my bar chart code. Now I was very happy but the they say that it needs to be more secure (it involves their company) and I have to find a way to make sure nobody can just see the data while looking through the code on the page. I thought about using Ajax and what not but it just didn't work for me. I got it to alert me the array, but was not able to fill a Javascript array with it.
I never did stuff with JS, PHP oder SQL before and only learned Java in school so I am pretty clueless and most of the stuff I did was with help of the Internet. Luckily I managed to at least understand the code I wrote/copied.
Edit: [] for a JS array not {}
Your syntax for creating the PHP array is incorrect.
Use the function json_encode to transform PHP arrays into Javascript arrays and objects.
<?php
$arr = ['hello', 'world', 'foo', 'bar'];
$obj = ['hello' => 'world', 'foo' => 'bar'];
echo 'var Array = ' . json_encode($arr) . PHP_EOL .
'var Obj = ' . json_encode($obj, JSON_FORCE_OBJECT) . PHP_EOL;
Will result in the following:
var Array = ["hello","world","foo","bar"]
var Obj = {"hello":"world","foo":"bar"}
Some pseudo code to show how you might accomplish the stated goal
$data=array();
while( $rs=$db->fetch() ){
$data[]=array(
'field_1' => $rs->field_1,
'field_2' => $rs->field_2,
'field_3' => $rs->field_3
);
}
$json=json_encode( $data );
<script>
<?php
echo "var jExampleArray={$json};";
?>
/* rest of barchart code */
</script>
If the PHP array is available at page load use:
<?php
$phpArray = array('data1' => 2, 'data2' => 3);
?>
<script>var arr = <?php echo json_encode($phpArray); ?>;</script>
To retrieve PHP array in JS after page load using ajax:
var arr = JSON.parse(responseArray);
I am doing a project on converting a database using sql, php and java for making a website. I have this inside my database:
echo's echos
sound wall
this is my code:
var places = [<?php
$mysqli = new mysqli("localhost", "root",null, "cdcol");
$stmt = $mysqli->prepare("select Name,Latitude,Longitude from food");
$stmt->execute();
$stmt->bind_result($name,$lat,$lon);
$space="
";
while ($stmt->fetch()) {
echo "['$name',$lat,$lon,$i,'Food',20],$space";
$i++;
}
$stmt->close();
$mysqli->close();
?>];
and using php, I have make I've taken out the two data but it has cause the problem with the '
the data display before will be
var place = [['echo's echos', lat, lon, 13, 'Food', 20],
['sound wall', lat, lon, 13, 'Food', 20]];
which the array will be use for some purposes
Try loading the values in php array using
array_push
Then pass the array as json encoded format, use json_encode
so the assignment to place will be made as
var place = <?php echo json_encode($placearray); ?>
Hope it helps!
your result looks like JSON, so you could put all your variables into a PHP array and let json_encode() do the escaping for you:
$placesJson = array();
while ($stmt->fetch()) {
$placesJson[] = array($name, $lat, $lon, $i, 'Food', 20);
$i++;
}
$places = json_encode($placesJson);
I have a array which comes through an POST request from javascript/jquery. In php the array content is as follows:
[{"name":"Ta","def":"somestring"},{"name":"WSCall","def":"somestring"},{"name":"manual","def":"somestring"}]
How do I iterate over this array to get the keys and values?
When I do: json_decode($_POST['shape_defs'])
How do I iterate over this array. Doing foreach says:
Invalid argument supplied for foreach()
While the (current) other two answers do get working code, they fail to address why you get the error you do.
$data = json_decode($j);
var_dump($data);
This will produce an object, with keys as properties. An object is not valid to be passed to foreach unless it implements Traversable.
What you need to do is:
$data = json_decode($j,true);
This will make objects be associative arrays instead, which are compatible with foreach and most likely the rest of your code.
When there's a definite number of children, you can use nested foreach-loops:
$json = '[{"name":"Ta","def":"somestring"},{"name":"WSCall","def":"somestring"}, {"name":"manual","def":"somestring"}]';
$decode = json_decode($json, true);
foreach ($decode as $k1 => $v1) {
foreach ($v1 as $k2 => $v2) {
echo "$k2: $v2, ";
}
echo "<br>";
}
It will output this:
name: Ta, def: somestring, <br>
name: WSCall, def: somestring, <br>
name: manual, def: somestring, <br>
$j= '[{"name":"Ta","def":"somestring"},{"name":"WSCall","def":"somestring"},{"name":"manual","def":"somestring"}]';
$data = json_decode($j,true);
foreach($data as $key=>$val){
foreach($val as $k=>$v){
echo "Key :".$k." Value :".$v."<br />";
}
}
var labels = new Array();
<?php foreach($crud_data as $cd ) { ?>
labels['<?php echo $cd['name'] ; ?>'] = '<?php echo $cd['label'] ; ?>';
<?php } ?>
$.post('url.php' , { labels:labels} );
Why can I not send labels array like this? It doesn't show anything in Firebug.
My console.log(labels) result:
[]
avatar
"avatar"
email
"email"
id
"id"
name
"name"
password
"password"
if i populate array like this
<?php foreach($crud_data as $cd ) { ?>
labels.push('<?php echo $cd['label'] ; ?>');
<?php } ?>
$.post('url.php' , { labels:labels} );
it works fine !
Oh I see now. If you have string keys, you have to use an object, not an array:
var labels = {};
Arrays in JavaScript are supposed to only hold elements with numeric keys. While you can assign arbitrary properties to arrays, they are not considered to be elements of the array and thus ignored by most processes which deal with arrays.
Additionally you might want to have a look at jQuery.param to see how jQuery will convert the input to a transport-able string and adjust your data structure accordingly.
labels['<?php echo $cd['name'] ; ?>'] =
It seems you want to create an associative array, which is in fact an object in JavaScript (JavaScript has no dedicated associative arrays). So the array itself is in fact empty because you are adding properties to the array object.