Storing retrieved data from an Ajax request into a variable

Presented below is a function that utilizes Ajax:

function fetchSource(callback){
    var ajaxRequest;  
    try{
        ajaxRequest = new XMLHttpRequest();
    } catch (e){
        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try{
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                alert("Your browser broke!");
                return false;
            }
        }
    }   
    ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4 &&ajaxRequest.status==200){
            var sourceData = ajaxRequest.responseText;  
            callback(sourceData);
        }
    }
    ajaxRequest.open("POST", "takesource4.php", true);
    ajaxRequest.send(null); 
}

In addition, we have the following code snippet:

var response4;
function executeFunction() {
    fetchSource(function(sourceData){   
        response4 = sourceData;
    });
    alert(response4);
}

The above function is called using the button below:

<div id="run">
  <button id="button_run" class="button" onclick="executeFunction()">Run</button>
</div>

Upon clicking the button, instead of displaying the expected response from the Ajax request, it appears to be showing an undefined value (undefined), as evident in the line below:

alert(response4);

Answer №1

My recommendation is to update the callback function within the run method like this:

let testVariable;
function run() {
    fetchSourceData4(function(data){   
        testVariable = data;
        alert(testVariable);
    });
}

Answer №2

Alert somous4 in advance of any changes made by the request callback. In this scenario, the commands block takes precedence over the request callback.

Languages like PHP on the server-side handle this automatically, eliminating the need for events there. They pause until the request is completed. This happens because the commands block shifts to become the event callback.

Answer №3

When dealing with asynchronous code, it is important to understand that it executes concurrently. This means that your alert statement may be triggered before your callback function runs (the callback function only runs after receiving data from the server). To ensure that the alert shows the correct value, place it inside the callback like so:

var somous4;
function run() {
    ajaxtakesource4(function(sourcetest){   
        somous4 = sourcetest;
        alert(somous4);
    });
}

Edit: In response to the OP's comment, instead of focusing on return values, try the following approach:

function foo(soumous4) { // use somous4 for whatever you want... }

// Call this function foo inside the callback.
ajaxtakesource4(function(sourcetest){   
    somous4 = sourcetest;
    foo(somous4);
});

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

Is there a way to automate the clicking of a button on this webpage if using .click() is not effective?

Currently, I am developing an extension that facilitates purchasing products from Flipkart during flash sales. However, on the product page, I am unable to click the "Buy Now" button using JavaScript as it returns undefined. Here is the code for the Buy No ...

Concealing overflow in a sticky container when a fixed child element is present

I am currently working on a website where I have implemented slide-up section panels using position: sticky while scrolling. However, I am encountering issues with fixed elements within the sticky panels not properly hiding outside of the respective sectio ...

Transferring JSON data through AJAX to a PHP backend

I have been working on a solution to convert a CSV file into JSON and then send it to BigCommerce using their REST API. Initially, I planned to use Javascript for the entire process, and everything was successful until I encountered issues with CORS when t ...

Error: It seems like Material UI has updated their export structure and now `makeStyles` is no longer available in the

The export of makeStyles from @mui/material/styles has been deprecated. Despite importing from @mui/styles throughout my project, this error continues to appear. I have already tried removing the node_modules folder and reinstalled, but the issue persis ...

filling out a form with data retrieved through an ajax request

After retrieving JSON data from an MVC controller, I am attempting to populate a form with this data but encountering difficulties. The returned data consists of only one row with three properties. Despite confirming that the data is being returned success ...

A guide on adding two fields together in AngularJS and displaying the output in a label

I am facing a unique issue on my webpage. Including two inputs and a label in the page, I want the label to display the sum of the values entered into these two inputs. My initial attempt was as follows: Sub-Total <input type="text" ng-model="Propert ...

Extract the value of an HTML tag and store it in a PHP variable

I have successfully implemented JavaScript code to dynamically update the value of an input tag in my popup. However, when I try to echo out this updated value using a PHP variable within the same popup, it doesn't seem to work as expected. Despite un ...

What are some best practices for utilizing `element.offsetParent` in HTML SVG elements?

I'm currently updating some JavaScript code that relies on the .offsetParent property. The recent changes in the application involve the use of SVG elements, which are causing issues with the JavaScript as mySvgElement.offsetParent always returns unde ...

Toggle the visibility of components based on the selected value of h:selectOneRadio

I have a page that includes a p:selectOneRadio component, and I am trying to display a specific datatable based on the selected value from the radio options. However, I am encountering the following error: GRAVE: javax.el.MethodNotFoundException: ..... ...

Trigger a JavaScript function upon clicking a link

Is it possible to have a CMS that loads articles using ajax, where the article is loaded through a function with parameters, and when a certain link is clicked, it redirects to the target page and launches the function on that page? For instance, let' ...

The getInitialProps function in Next.js is not functioning properly in mobile browser environments

My app runs perfectly on desktop without any errors. However, when I switch to a mobile device, I noticed that the pages fail to trigger the getInitialProps method on the client side, only if I navigate through the Link component. This is my code: return( ...

Tips for adjusting the time interval on an automatic slideshow when manual controls are in play

I'm having trouble with my slideshow. I want it to run automatically and also have manual controls, but there are some issues. When I try to manually control the slides, it takes me to the wrong slide and messes up the timing for the next few slides. ...

Using AJAX to dynamically update a div's class following a POST request

Upon double clicking a row, I am attempting to trigger the function outlined below. Despite my efforts, I have not been able to update the div class with any changes. function book(id) { $.ajax({ type: "POST", url: "ajax_servlet. ...

What is the best way to incorporate CSS into an AJAX request?

I am facing a challenge in creating a tree menu within my PHP code that is located in an ajax php file. The issue arises due to the presence of classes used inside the tree code: $html .= '<li><span style="min-width:200px" class="folder"> ...

Enforcing Single Menu Accessibility in React: Only One Menu Open at a Time

Just starting out with React and JavaScript, so please bear with me for any formatting issues or lack of knowledge on best practices. I'm using Tailwind UI for my website, which includes navigation menus that require JavaScript to open and close. I h ...

What causes JavaScript to be unable to run functions inside other functions?

Functional languages allow functions to be executed within the argument brackets of nested functions. In JavaScript, which drew inspiration from Scheme, what is the equivalent? f( f ( f ( f))) console.log( 1 + 1 ) //2 How does JavaScript execut ...

JQuery - Select element by clicking outside

I'm trying to figure out how to hide an element when clicking outside of it. Found a solution at: https://css-tricks.com/dangers-stopping-event-propagation/ $(document).on('click', function(event) { if (!$(event.target).closest('#m ...

Using jQuery to create an AJAX request for a basic website

I created a website where users can enter an access code to reveal a secret message, and it's working perfectly. Now, I want to enhance it by automatically sending an email to the user once the secret message is revealed. I plan to use ajax to call ...

Press the button to eliminate

Is there a way for users to add tags by typing text and then clicking on an add button? Once the tag is added, it appears with a delete button, allowing users to manage their list of tags. The JavaScript code below enables users to add tags successfully, ...

What causes the transformation of [{"value":"tag1"} into [object Object] when it is logged?

Currently on my node.js server, the code I'm using is as follows: var tags = [{"value":"tag1"},{"value":"tag2"}]; console.log("tags: " + tags); My expectation was to see this in the console: tags: [{"value":"tag1"},{"value":"tag2"}] However, what ...