I am brand new to the world of AJAX. I have a Mysql database that contains a column filled with URLs. My end goal is to have an on click event load an iframe with a unique URL from the database. If anyone has a better methodology please let me know.
Right now however I'm just trying to figure out how AJAX works by trying to retrieve the URLs. I've attached my Javascript code and my PHP code.
The PHP code does output a json encoded copy of the data. The javascript however reports the variable result as undefined. I think this may have to do with the "asynchronous" side of AJAX but I followed this tutorial to try to make code work correctly. I appreciate any help that can be provided.
How do I return the response from an asynchronous call?
Here is my code Javascript code it logs results is undefined and "I made it" to the console
function retrieve_callback(result) {
console.log (result);
console.log("I made it!");
};
function retrieveURL (retrieve_callback) {
$.getJSON({
url: './fetch.php',
dataType: 'json',
success: retrieve_callback
});
}
//Runs when our document initializes
$( document ).ready(function() {
retrieveURL(retrieve_callback());
});
Here is my PHP code it outputs the JSON array of the URLs
<?php
//--------------------------------------------------------------------------
// Connect to mysql database (I've removed the info from this example but it works)
//--------------------------------------------------------------------------
$db = new mysqli($DB_HOST, $DB_USER, $DB_PASSWORD, $DB_NAME);
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
//--------------------------------------------------------------------------
// Query mysql database
//--------------------------------------------------------------------------
$links = array();
//SQl query
$sql = <<<SQL
SELECT `Gnews_url`
FROM `Gnews_RSS`
SQL;
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
while($row = $result->fetch_assoc()){
array_push($links, $row);
}
echo json_encode($links);