Putting mySQL Database Information into a JavaScript Array
I'm trying to use the above example of passing MYSQL data to AJAX but it only uses a single dimensional array, how do I get data from a multidimensional array?
Here are some test code that I've tried (load_ajax.php):
<?php
$mysqli=mysqli_connect("localhost","root","admin","database_name");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$mysqli->set_charset("utf8");
$i=0;
$arraylist=""; // Initialise local array for icons
$result = $mysqli->query('select * from word_table');
while($row=$result ->fetch_object()) {
$arraylist[$i]["word_id"]=$row->word_id;
$arraylist[$i]["word_name"]=$row->word_name;
$i++;
}
//convert the PHP array into JSON format, so it works with javascript
echo json_encode($arraylist);
?>
And in HTML (load_ajax.html):
$.ajax({
url: "load_ajax.php",
datatype: "json",
success: function(data, textStatus, xhr) {
data = JSON.parse(xhr.responseText);
for (i=0; i<data.length; i++) {
alert(data[i]["word_id"]+"/"+data[i]["word_name"]);
}
}
});
The above code will not work for me. Previously I only used PHP to generate my array and print straight out to HTML. Now I want to use AJAX to load MySQL data from PHP into a javascript multidimensional array that can be used more interactively with other local functions.