What is the most effective way to transfer a variable from one function to another or retrieve a global variable?

My application utilizes ajax in a specific section to send form variables to a php script, which then communicates with my api.

Below is the form:

<input name="answer_id" id="answer_id<?= $i;?>" type="radio" style="width: 21px" value="<?= $ans_id; ?>"> <!-- A for loop provides 3 different answers for the radio button here -->
<input name="question_id" id="question_id" type="hidden" style="width: 21px" value="<?= $question_id; ?>">
<input name="all_answers" id="all_answers" type="hidden" style="width: 21px" value='<?= serialize($answers); ?>'>
<input name="Submit" onclick="post_question()" type="submit" value="Submit" class="btn btn-success">
<input type="hidden" id="campaign_id" value="<?= $campaign; ?>">

The post_question() function:

var responseData = [];
function post_question(){
    var data = new FormData(),
        obj,
        campaign = document.getElementById('campaign_id').value;
    data.append("all_answers", document.getElementById('all_answers').value);
    data.append("question_id", document.getElementById('question_id').value);
    data.append("campaign_id", document.getElementById('campaign_id').value);
    load_post("controllers/post_question.php", data);
    var tempVar = responseData['response'];
    console.log("tempVar variable: " + tempVar);
    console.log(tempVar);
}

The load_post() function:

function load_post(url, params){
    // Code for loading post request goes here...
}

The variable responseData stores a json array containing an object:

[{"id":"10082","question_id":"26","answer_id":"46","profile_id":"42121","correct":"1","attempts":"8"}]

When attempting to access this JSON object within the post_question() function, issues arise. Despite various attempts, such as storing it in a global variable or passing it to another function, the global variable remains empty. Yet, using tools like firebug reveals otherwise.

After seeking help from resources like Stack Overflow, I am still facing challenges in handling the responseData variable effectively. As a novice in javascript, any assistance on either passing or accessing this global variable would be greatly appreciated.

Answer №1

This particular snippet of code

load_post("controllers/post_question.php", data);

operates asynchronously, meaning the subsequent line will attempt to access an empty array within responseData.

To effectively manage the asynchronous behavior of the AJAX call, it is necessary to include a callback function that gets triggered upon completion of the AJAX task. An example implementation is demonstrated below:

function load_post(url, params, callback){
    new imageLoader(cImageSrc, 'startAnimation()');
    var xhr,
        response = [];
    if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest();
    else {
        var versions = ["MSXML2.XmlHttp.5.0",
            "MSXML2.XmlHttp.4.0",
            "MSXML2.XmlHttp.3.0",
            "MSXML2.XmlHttp.2.0",
            "Microsoft.XmlHttp"]
        for(var i = 0, len = versions.length; i < len; i++) {
            try {
                xhr = new ActiveXObject(versions[i]);
                break;
            }
            catch(e){}
        } // end for
    }
    xhr.onreadystatechange = ensureReadiness;
    function ensureReadiness() {
        if (xhr.readyState !== 4) {
            return;
        }
        responseData['response'] = xhr.responseText;
        responseData['code'] = xhr.status;
        callback(responseData);
    }

    xhr.open('POST', url, true);
    xhr.send(params);

  }

  function post_question(){
    var data = new FormData(),
        obj,
        campaign = document.getElementById('campaign_id').value;
    data.append("all_answers", document.getElementById('all_answers').value);
    data.append("question_id", document.getElementById('question_id').value);
    data.append("campaign_id", document.getElementById('campaign_id').value);
    load_post("controllers/post_question.php", data, processNewData);
  }

  function processNewData(newData){
    var tempVar = newData['response']; // or you can use responseData at this point as well
    console.log("tempVar variable: " + tempVar);
    console.log(tempVar);
  }

In the provided scenario, I am passing responseData as an argument of the callback function. However, since it is a global variable, you also have the option to invoke the callback without any arguments and access it as needed.

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

Disabling specific time slots in the mat select functionality

I have a scenario where I need to display time slots at 30-minute intervals using Mat Select. export const TIME=["12:00 AM","12:30 AM","01:00 AM","01:30 AM","02:00 AM","02:30 AM","03:00 AM&qu ...

Ways to implement a percentage for scrollTop

I'm currently troubleshooting the code below. My goal is to understand why I'm unable to scroll the .post div with jQuery and input range properly using a percentage value like this: $("[type=range]").on('input',function(){ var v ...

Leveraging R's Plumber library, develop a GET endpoint for serving CSV-formatted data instead of JSON

While I find this to be a great demonstration of R's plumber library overall, my main challenge lies in serving data in a csv format. My current project involves using R's plumber package to create an API endpoint for sports data. Specifically, ...

Steps for executing Mocha tests in a specified sequence

Background Currently, I am developing a Node.js program where I am creating test suites in Mocha using Chai and SinonJS. The program involves a core graphics module that manages access to a node-webgl context. Due to the nature of node-webgl, I want to i ...

Guide on using javascript to alter a json structure

Recently, I discovered a method to manipulate a JSON file using JavaScript. Although I don't have any formal training in JavaScript, I understand that it is primarily utilized on web browsers. Can someone guide me on how to execute this script? I cons ...

The HTML status code is 200, even though the JQuery ajax request shows a status code of 0

My issue is not related to cross site request problem, which is a common suggestion in search results for similar questions. When attempting to make an ajax request using jquery functions .get and .load, I'm receiving xhr.status 0 and xhr.statusText ...

Utilize the --stream function to break down a sizable object into smaller, more manageable components

Here is a functional jq transform script using input file (input.jsonl): {"key": "key1", "value": {"one": 1, "two": 2}} {"key": "key2", "value": {"three": 3, "four": 4}} The jq transform command: $ jq --compact-output '.key as $key|.value|to_entrie ...

My images are receiving a hidden style display none from Bootstrap js

My images are not loading properly when using Bootstrap v5 on my website. I have no issues with images in other parts of the site. This is the HTML code I am using for the image: <img border="0" src="example.com/img/kitties-long.png" ...

`In a React class, member variables are linked by reference and are considered 'shared'.`

Whenever I create multiple instances of a React class using React.createElement, I notice that some member variables are shared among the instances. It seems like arrays and objects are shared, while strings and booleans are not. This realization is unsett ...

Utilizing an array of objects to import images

Within the data file, there exists an array of objects where icons are described as properties of these objects. The question arises: how can we utilize these icons as links? export const socialLinks = [ { url: "https://www.youtube.com", ...

What is the relationship between three.js transforms and CSS3 3D-transforms?

I am developing a unique open-source tool for exploring and visualizing the complexities of human anatomy. At the center of this tool is a dynamic 'chessboard' that occupies the majority of the screen. As you drag the board, various CSS3 3D-tran ...

Error: The JSON data contains an unexpected token at the beginning Express

I am currently following a tutorial (here) to establish a connection between Express and React Native. I have a server.js script running which connects to the client (App.tsx) on my IP address using port 3000. The server and app are running simultaneously ...

The functionality to hide one div and display another in its place is disabled for popups and is not currently working as

For easy access, feel free to download my project files here. (Size: 2mb) In my webpage, there is a popup containing two images and a heading inside a div. I want to implement a functionality where upon hovering over the div, it will hide and show another ...

Is it possible to convert an Object's property into a String resembling "Object.property"?

I am attempting to create a custom function that can convert the keys of an object I am accessing into a string representation. Here is an example: const test = { propertyOne: { propertyTwo: 0 }, propertyThree: { propertyFour: 0 } } functi ...

The selection box for sorting data using PHP, jQuery, and AJAX

I have a checkbox labeled Active, which is always checked when staff enter the system to display data of active workers. However, when I uncheck the checkbox, it should show inactive worker data but currently, it's not working as expected. Please revi ...

Resetting form fields once data has been successfully posted to MongoDB

I have successfully set up a form that sends data to a MongoDB database. However, I am facing an issue with refreshing the input fields after the form is submitted without reloading the entire page. After calling the resetBooks() function, it seems like i ...

What is the process for implementing a click event and accessing the DOM within an iframe using react-frame-component?

I am working on using the react-frame-component to create an iframe. I am trying to bind a click event on the iframe and retrieve the DOM element with the id of "abc" inside the iframe. Can anyone guide me on how to achieve this? The code snippet provided ...

Is it possible to develop a tagged template for a function that accepts parameters?

I came up with a special function that can act as a tagged literal: function generateStringFromTemplate(strings, ...keys) { // Object containing the values to interpolate return dict => { return keys.reduce( (acc, value, idx) => `${acc} ...

Injecting information into an input field using the :before pseudo-class in CSS when focus

In order to have a static part "+91" displayed in an input field upon focus, I have successfully replaced the placeholder during onFocus and onBlur events. However, I am unable to add a listener to read content from :before. <div class="goal-mobile"> ...

The hover effect is not altering the color

$(document).ready(function() { $(window).scroll(function() { var scroll = $(window).scrollTop(); if (scroll > 200) { $(".nav-bg").css({ "background": "#fff", ...