Leveraging the callback function to display information from a JSON file

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>

Answer №1

Your code appears to be excessively complex, with empty functions calling each other needlessly. Simplify it by condensing it into just 3 lines:

<div class="output"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script type="text/javascript">
  $.getJSON("/test/senate.php").done(function (data) {
    $(".output").append(data);
  });
</script>

Answer №2

The function you define as success serves as the callback function. It gets invoked with the response from the request:

function fetchJsonData () { 
  $.ajax({
    url: "/test/senate.php",
    success: handleResponse // invoke the 'handleResponse' function upon completion
  });

  function handleResponse (jsonData) {
    // process the received data
  }
}

You can also do something like this:

function fetchJsonData (callback) { // pass the callback function as a parameter
  $.ajax({
    url: "/test/senate.php",
    success: callback, // execute the specified callback when finished
  });
}

function displayFetchedData () {
  fetchJsonData(displayData); // utilize 'displayData' as the callback function

  function displayData (jsonData) {
    $(".output").append(jsonData);
  } 
}

Answer №3

Here's a suggested approach to improve and streamline the code:

<script type="text/javascript>

function scriptWrapper(){
  requestJson();
}

function requestJson(){ 

  $.ajax({
    url: "/test/senate.php",
    success: displayJson,
  });

}

function displayJson(jsonData){

  $(".output").append(jsonData);

}

$(document).ready(scriptWrapper);  

</script>

I'm unable to execute the code presently, but you might consider changing $(".output").append(jsonData); to $(".output").first().append(jsonData);

For more information on using callbacks, refer to JQuery's $.ajax documentation that includes helpful examples.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Mysterious JSON deserialization

When trying to establish a connection with RouteXL, I am encountering an issue with the JSON response received from the API. The JSON data appears to be invalid as it contains a sort of array starting with a string index under the 'route' tag. Ty ...

Adjusting the size of HighCharts HighMaps with a custom function

Simple query here (I believe) I have a DIV with the class "container" acting as my Map. The Highcharts plugin I'm using is responsive, but it only resizes when the window does. I'm looking to manually trigger a resize without adjusting my windo ...

What is the typical output value that fluctuates?

I only have one input to work with. My goal is to set the input value to "5", then display "3" in the "total" field and "4" in the "total2" field. Additionally, for every increment of +1 to the input value, I want the "total" and "total2" fields to also in ...

Manipulating Strings in JavaScript Arrays

I am working with an array of arrays of data that is being retrieved from a csv file. My goal is to filter out specific indexes of an array based on the titles they contain. For instance: If an array index includes the title "Retail", I want to return the ...

Dealing with undefined Ajax values in PHP

Every time I call the function, I receive an undefined value and it's baffling me as to what could be causing this issue. You are logged in as undefined, Error undefined Ajax script: function Submit() { console.log('asd') $.ajax({ ...

Attempting to output numerical values using Jquery, however instead of integer values, I am met with [Object object]

I am struggling to figure out how to display the value contained in my object after attempting to create a Calendar using Jquery. I attempted to use JSON.toString() on my table data, but it didn't solve the issue. Perhaps I am not placing the toString ...

Leveraging asynchronous data in a synchronous manner

I am dealing with tax rate data stored in the database to ensure easy updates when necessary. However, JavaScript's asynchronous nature complicates accessing this data as it requires promises or callbacks to retrieve query results. Is there a solution ...

The jQuery functionality is not functioning properly within the aspx file

I came across some JavaScript code on stackoverflow that is not working in my own code, but strangely it works perfectly fine in the jsFiddle: https://jsfiddle.net/rxLg0bo4/9/ Here is how I am using inline jQuery in my code: <nav id="menu"> < ...

What could be causing my Mocha reporter to duplicate test reports?

I've created a custom reporter called doc-output.js based on the doc reporter. /** * Module dependencies. */ var Base = require('./base') , utils = require('../utils'); /** * Expose `Doc`. */ exports = module.exports = ...

Error: Attempting to access an undefined property ('call') on Next.js is causing a TypeError

Exploring the realms of Next.js and Typescript for a new project! My goal is to utilize next.js with typescript and tailwind CSS by simply entering this command: npx create-next-app -e with-tailwindcss my-project Smooth sailing until I hit a snag trying t ...

Querying JSON Data with PHP API

I have been working on creating a query.php file along with a query_result.php page to handle an API JSON feed. My issue is that even when I specify a specific "year" in the query, such as YearBuilt = "1999", the results still include vessels from all year ...

How to assign the 'src' attribute to an HTML element using Node.js

I am currently using 'express' in Node.js and have implemented the following code to send a URL input into text: <form method="GET" action='/download' class="my-5"> <div class="form-group"> ...

The error message "Blazor WebAssembly JSRuntime.InvokeVoidAsync - blazor.webassembly.js:1 Uncaught (in promise) TypeError: Converting circular structure to JSON" indicates that

I have implemented the drawio-integration project in my Blazor WebAssembly application. https://github.com/jgraph/drawio-integration This is how the simple helloworld sample appears: <img onclick='DiagramEditor.editElement(this);' src=" ...

Encountering the error message "Module 'request' not found" despite the fact that I've already included the request module

I'm currently facing an issue with my Cloud Function that involves using the request library. After installing the request package using npm install request, I noticed it's located in the node_modules directory, just like all the other packages: ...

Guide on efficiently parsing JSON in Java using a top-notch parser

My application receives an array with around 2,000 elements every second, sometimes multiple times within a single second. Each element in the array consists of 3 Big Decimals. The slowest part of my otherwise fast application is Jackson (com.fasterxml), ...

Retrieving information from an Angular service using a specified function

I have been working on accessing data from a method within a service that returns coordinates, which are used to make HTTP requests in my application. I have integrated my Leaflet code into the controller to be able to access the lat,lng coordinates for ...

Tips for dynamically updating the div class based on the model's value

How can I dynamically change the CSS class of a bootstrap element based on a value? I would like to display a div in green if the value is "OK" and red otherwise. If status = "OK", it should look like this: <div class="small-box bg-green">, else < ...

Capturing user-selected option from dropdown menu using npm

I am a beginner when it comes to node.js and async programming. My current project involves creating a program that shuffles a Spotify playlist. I have managed to store the user's playlists in an array for easier access. My goal is to present this ar ...

I am looking to customize the color of my Material UI switch

I am having difficulty changing the color of my Material UI switch based on my preference. I have tried several ways, but have not achieved the desired outcome. const useStyles = makeStyles((theme) => ({ toggle: { '& .Mui-checked': ...

Selecting options using AngularJS to parse through a list

I am faced with a challenge involving a collection of strings representing years. Here is an example: $scope.years = ["2001", "2002", "2003", ...]; My goal is to display these values in a select tag within a web page. However, whenever I attempt this usi ...