Good afternoon developers,
The last couple weeks I've been working on Ajax with jQuery, since it's a major element on modern websites nowadays. However, I simply can't retrieve an encoded JSON array, from my PHP file with jQuery. Because the most basic ability I at least should possess is reading out Mysql data with AJAX.
I've tried $.getJSON(url, data, response)
, dataType: 'json'
, but neighter solutions worked out, and I've also visited several websites including various StackOverflow questions...
This is the regarding PHP code that retrieves data through Mysql and converts it into a JSON object array:
<?php //ajaxIndex.php
include 'connectionFile1.php' ; //connection file
$sql1 = "SELECT * FROM users" ;
if ($result1 = mysqli_query($connection, $sql1) ) {
$resultsSql1 = mysqli_num_rows($result1) ;
$return_array = array();
while ($row1 = mysqli_fetch_array($result1)) {
$row_array['userName'] = $row1['userName'];
$row_array['email'] = $row1['email'];
//$return_array[] = $row1 ;
array_push($return_array, $row_array);
}
//encode the mysql array
print json_encode($return_array); // this array is correctly encoded
}
?>
This is the jQuery code that should properly retrieve and assimilate the JSON object array:
<script>
//$(document).ready(fetchData) ;
$("#button").click(function () {
$.ajax({
url: "ajaxIndex.php",
type: "GET",
dataType: 'json' ,
success: function(response){
console.log(response) ;
$.each(response, function() {
console.log(this.userName + "<br>") ;
console.log(this.email) ;
}) ;
}
});
}) ;
//window.setTimeout(fetchData, 1000);
</script>
Thank you dudes in advance.