Attempting to retrieve JSON data from a PHP file and display it.
Managed to successfully request the data via AJAX and log it to the console. (At least one part is working).
Tried implementing a callback to ensure that the script waits for the data before executing the display function. Followed a tutorial step by step, but there seems to be an issue as the inspector throws an error stating that jsonData
is not defined.
Unable to display the data properly without the callback functioning correctly.
Let me explain what I've done:
1. Waiting for the document to load before executing the script
$(document).ready(scriptWrapper);
2. Encapsulating everything within a single function
function scriptWrapper(){
displayJson();
}
3. Starting the function with the callback parameter
function requestJson(_callback){
4. Requesting data from the PHP file using AJAX
$.ajax({
url: "/test/senate.php",
success: result,
});
5. Logging the data result to console.log
function result(jsonData){
console.log (jsonData);
}
6. Callback ends here
_callback();
7. Triggering the displayJson function
function displayJson(){
8.
Calling requestJson()
with the showData()
function as the parameter, indicating that showData
will wait for the callback to execute.
requestJson(showData());
9. Function responsible for displaying the JSON data in the output div.
function showData(){
$(".output").append(jsonData);
}
Any insights would be greatly appreciated!
Live version available at: congress.digitango.com/test/results.php
Full code snippet below:
<div class="output"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function scriptWrapper(){
displayJson();
}
function requestJson(_callback){
$.ajax({
url: "/test/senate.php",
success: result,
});
function result(jsonData){
console.log (jsonData);
}
_callback();
}
function displayJson(){
requestJson(showData());
function showData(){
$(".output").append(jsonData);
}
}
$(document).ready(scriptWrapper);
</script>