I am very new to PHP and Javascript. I would like to use a PHP function in order to fetch database data as an array and be able to use it in Javascript. I am I have searched online but I haven't come across anything that helps my particular situation. How would I get the array in Javascript and be able to use it like so:
var arrayJS = arrayFromPhp;
My PHP code is below:
<?php
function fetch(){
$link = mysqli_connect("localhost", "root", "Southflorida8", "test");
if ($result = mysqli_query($link, "SELECT * FROM aircraft")){
if (!mysqli_query($link, "SET @a:='this will not work'")) {
printf("Error: %s\n", mysqli_error($link));
}
$array = mysqli_fetch_all($result);
mysqli_free_result($result);
return json_encode($array);
}
}
if (isset($_POST['fetch'])){
echo fetch();
}
?>
Here is the Javascript:
var array = [];
$.ajax({
url: 'server.php',
type: 'post',
data: 'fetch',
datatype: 'json',
success: function(array) {alert(array);}
});
pubnub.publish({channel:pnChannel, message:{lat:array[0][1] , lng:array[0][2] }});
Try this.
$.ajax({
url: 'server.php',
type: 'post',
data: 'fetch',
success: function(array) {
array = JSON.parse(array);
console.log(array);
}
});
**EDIT: ** And also update your php code.
Replace $array = mysqli_fetch_all($result);
with $array = mysqli_fetch_all($result, MYSQLI_ASSOC);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.