JavaScript function execution fails following an AJAX request

One of my functions is functioning properly with the alert:

function RequestNext() {

    var xhr = getXMLHttpRequest();

    xhr.onreadystatechange = function() {

        if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
            MyCard = GetCard(xhr.responseText);
            **alert(MyCard.GetNo());**
            return MyCard;
        }
    };

    xhr.open("GET", "../../HttpRequest_Next.php" , true);

    xhr.send(null);                                             
}

However, in another function where the first one is called, the same alert does not work:

function Start(){

    var MyCard = RequestNext();

    alert("Patience.js");
    **alert(MyCard.GetNo());**
    alert("test2");
    //alert(Card.GetKind());
    //WriteCard(Card);
    alert("test3");
}

Just to provide context, these functions are located in separate files.

Answer №1

In this scenario, utilizing a callback function proves to be extremely beneficial. By passing a function as an argument, you can execute that function once the asynchronous ajax operation is complete. While the syntax might need some adjustments, you could implement something like this:

function FetchData(callback) {

  var xhr = getXMLHttpRequest();

  xhr.onreadystatechange = function() {

    if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
        ProcessedData = AnalyzeData(xhr.responseText);
        **alert(ProcessedData.GetID());**
        if (typeof callback=='undefined') return ProcessedData;
        else {
          return callback.call(ProcessedData);
        }
    }
  };

  xhr.open("GET", "../../DataFetcher.php" , true);

  xhr.send(null);                                             
}
function InitiateProcess(){
  var ProcessedData = FetchData(function() {
      alert("Async.js");
      alert(this.GetID());
      alert("test2");
      //alert(this.GetType());
      //ManipulateData(this);
      alert("test3");
      return this;
  });
}

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

Obtain a unique HTML ID dynamically with Selenium and VBA

I am currently working on automating a web form using Selenium and VBA. The form includes a search box that generates an autogenerated list when a value is entered. While I can successfully input a value into the search box and trigger the javascript to cr ...

What are the methods for providing both successful and unsuccessful promises, with or without data?

Seeking guidance on how to return a promise and an object named output before or after the $http call in AngularJS, specifically using Typescript. How can I ensure it works correctly? topicNewSubmit = (): ng.IPromise<any> => { var self = t ...

Obtaining the IP address of the client's request

In an effort to prevent others from wasting time in the future, I am sharing this post even though it's not really a question anymore. Objective: Obtain the client IP address and set specific values based on certain octets in the IP address. While w ...

how to use jQuery to sort appended data

I have a loop that retrieves data from the server in descending order, but when I use "append()" to add the data, it doesn't maintain the correct sorting. For instance, the first row shows up in the second position. Is there a way to append the data ...

Guide to organizing the legend section into two columns within Apache Echarts

I'm looking to customize the legend area layout in Apache Echarts for a two-column display. Can anyone provide guidance on achieving this using legend options? I have been unable to locate any examples demonstrating this particular layout. For refere ...

The form will only display results after the "Submit" button is clicked twice

Recently, I built a flask website where the form and results are displayed on the same page. However, there seems to be an issue that arises upon clicking the 'submit' button for the first time after running 'flask run'. The error messa ...

Leverage the power of both ui-sref and $state.go for seamless state transitions in Angular's ui

Currently, I am in the process of constructing a sign-up form that will collect user input and then transition to a logged-in state with a template tailored specifically for this new user. To achieve this, my understanding is that I need to utilize ng-sub ...

Verify whether the user is obstructing third-party domain

I've encountered a recurring issue where many of our support calls pertain to images not loading due to users blocking Amazon S3 or a similar third-party service. I rely on third-party services for hosting images, videos, and certain JavaScript elemen ...

Tips for configuring jQtree to initially display the tree structure from the HTML source

Up to this point, I have utilized jQuery TreeView for the navigation menus on my website. However, as the main navigation menu has grown significantly in size (40869 bytes out of 67054 bytes), I am seeking a way to streamline it by using AJAX calls to fetc ...

ReactJS: Dealing with issues in setting a dynamic index for the setState key

I have been attempting to utilize setState within a for loop using index in the following manner: for (var i = 0; i <= 9; i++) { this.setState({ location_option[i]: resourceData.location_option+i, location_option[i]_type: resourceData.locatio ...

When should ng-repeat be utilized: only when the object type is an array?

I have a detailed object structure below: $scope.document = { "GENERAL_FIELDS": { "Source_Type": "custom", "Annotations": [ "216/content/Factiva_CM_001/Proteins", "216/content/Factiva_CM_001/Fact" ], "Content": [ " ...

What is the best option: using a Javascript template or exploring another

Just starting out in web development. I want to include the same menu on every page of my new website, but I don't want to manually update it in each file whenever there's a change. Is there an easy template engine for JavaScript or another sol ...

Unraveling HTML elements within a string using MongoDB: A step-by-step guide

Currently, I am in the process of creating a blog from scratch as a way to enhance my skills. The posts' content is stored as a long string in MongoDB with some random HTML tags added for testing purposes. I am curious about the conventional method fo ...

Getting image blob data with Cropper Js in a Laravel controllerNeed help on how to get image blob data

I've been working with Cropper.js and Laravel. I managed to crop an image, put it into FormData, and send it to the Laravel controller using jQuery Ajax. However, I encountered a problem where I am not receiving any data in the controller, only an err ...

Combining multiple JSON objects into a single array in AngularJS

Currently, I am facing a challenge in merging two API calls. The first call involves fetching data by filtering the account_id on the backend, while the second call retrieves data based on the test_id. Let's start with the JSON response for /api/test ...

A Comprehensive Guide: Obtaining the Final Tab from a JSON using API

What is the method to extract the last tab from a given JSON code? { "claimed_levels": { "level_1", "level_2" } } I want to display the level when someone types "!levels". The desired output format should be: Your current level is "2" ...

Experiencing difficulty with setting up the ReactJS pagination component

Each time I click on a page number, the maximum size of the pages is returned as a handler parameter (for example, clicking on 2 returns 4). What could be causing this issue? UPDATE class PagingControl extends React.Component{ constructor(props) { ...

Validation of PO Box Addresses Using Regular Expressions

I'm having trouble getting the alert to work with my code. $(document).ready( function (){ $("[id*='txtAddress1S']").blur(function() { var pattern = new RegExp('\b[P|p]*(OST|ost)*\.*\s*[O|o|0]*(ffice|FFICE)*& ...

Utilizing AJAX to dynamically populate an HTML list from a database and then saving the user's newly selected value back to the database

I'm working on dynamically populating a list from a database using AJAX and then updating the selected value back to the database with a servlet. What's the best approach for achieving this? Typically, I use the following code for dynamic update ...

Extract the value/values enclosed within double quotation marks using a regular expression

Struggling to create a JavaScript form validator; The value follows a specific format and can appear one or more times. When testing the value, it is crucial to ensure that the entered value is enclosed within double quotes. For example: one value: "C:GS ...