Requesting Data with JavaScript using Ajax

I'm puzzled by the behavior of an AJAX request. When I call the "done" function, I expect it to be done immediately. However, I only receive the values after using a setTimeout function. Why is this happening?

{"status":"1","msg":"Return Successful","callbackFunct":"LinkMenu.setMenuItems()","return":[{"name":"save","image":"","action":"","status":""},{"name":"back","image":"","action":"","status":""},{"name":"delete","image":"","action":"","status":""}]}

class ServerQuery {

constructor(request, level) {
    console.log("Starting server query for " + request + " at level " + level );
    this.lev = level;
    this.file = "http://" + location.hostname + "/" + this.lev + "/" + request;
    this.values = new Object();
    this.data   = new Array();
    this.result      = null;
    this.setRequiredValues();
}

setRequiredValues() {
    console.log("Setting required values");
        let ses = document.getElementById("key").value;
        let orgid = document.getElementById("OrgId").value;
        let userid = document.getElementById("userid").value;            
        this.values['key'] = ses;
        this.values['orgid'] = orgid;
        this.values['userid'] = userid;
        console.log("Loaded required values: " + JSON.stringify(this.values));           
}

addValue(key, insert) {
    console.log("Adding value " + key + ": " + JSON.stringify(insert));
    this.r = new Object();
    this.r[key] = insert;
    this.data.push(this.r);
    console.log("Values added: " + JSON.stringify(this.data));              
}

// Use this method to trigger a return callback
sendRequest() {
    console.log("Server Query sending Request");
    connect_ajax();

    // this.values is an object
    this.values['linked'] = this.data;
    let req = JSON.stringify(this.values);
    let uandp = "requesting=" + req;
        console.log("Data being added: " + uandp);
        $.post(this.file, uandp)
            .done(function done2(result) {
                console.log("Server query finished with result: " + result);
                this.r = JSON.parse(result);
                if (this.r.status == 1) {
                    console.log("ServerQuery after parse: " + this.r);
                    console.log("Output: " + this.r.callbackFunct);
                    if (typeof this.r.callbackFunct != 'undefined') {
                        setTimeout(function() {
                            this.r.callbackFunct(this.r.callbackVars);
                        }, 500);
                    } else {
                        alert("Callback not set");
                    }
                }
                else if (this.r.status == 3) {
                    alert(this.r.msg);
                }
            })
            .fail(function processFailed() {
                console.log("An error has occurred");
            })
            .always(function processAlways() {
                console.log("Finished");
            });
        console.log("Requesting URL: " + this.file);

}   

// Use this method to get a static response from the server
callRequest() {
    console.log("Starting serverquery process()");
    let answer = this.process();
    console.log("Process returned: " + answer);
    return answer;

}

process() {
    this.values['linked'] = this.data;
    let req = JSON.stringify(this.values);
    let uandp = "requesting=" + req;
    let file = this.file;
        console.log("Data adding " + uandp);
    let return_first = function () {
    let tmp = null;
    $.ajax({
        'async': false,
        'type': "POST",
        'global': false,
        'dataType': 'html',
        'url': file,
        'data': uandp,
        'success': function (data) {
            tmp = data;
        }
    });
    return tmp;
    }();
    return return_first;
}

cleanUp() {
    delete this.file;
    delete this.values          
    console.log("Removed values from global scope: " + this.values);
    console.log("Removed file from global scope: " + this.file);
}  
}

Answer №1

The reason for this behavior is due to the asynchronous nature of the $.post method. Even though a method returns, the $.post call is still being executed in the background and has not yet completed. This may result in unexpected outcomes.

To handle this scenario, you can invoke a function (let's say ProcessResult) once the $.post request is done. This can be achieved by passing the function as a parameter to the sendRequest method.

sendRequest(caller, myDelegateFunction) {
    $.post(this.file, uandp)
            .done(function done2(result) {
                // Invoke the passed function with the result as a parameter.
                myDelegateFunction.call(caller, result);
            });
}

// Example usage:
function ProcessResult(result) {
   console.log(result);
}
sendRequest(this, Hello); // Call sendRequest and pass 'this' as caller and 'Hello' function.

// Or like this:
sendRequest(this, function(result) {
   console.log(result);
});

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

Creating Docker images in a lerna monorepo without the need for publishing

In the context of Lerna monorepos, the primary goal is to facilitate branch building and deployments. The challenge arises from the fact that Lerna monorepos either consolidate dependencies in NPM or utilize yarn workspaces to achieve the same outcome, re ...

Testing the Integration of Angular with Jasmine, utilizing a service that makes real HTTP requests

[Angular version: 2.4.5] As I dive into writing a unit test for an Angular integration component that involves a service using the Angular HTTP library, I'm encountering a challenge with the instantiation of my Service class. Either the Service ends ...

Error: Failed to fetch the data from the Firebase database

I have recently added an edit button to my product list, but when I click on it, the form page opens with no data populated. Upon debugging in my product.service.ts file, I noticed that it outputs null when using console.log(p). I believe this is where the ...

a beginner's guide to utilizing the grunt target

Here is an example of my Gruntfile.js: 'use strict'; module.exports = function(grunt) { grunt.initConfig({ grunt.config.set('targ', grunt.option('target')); cachebuster: { build: { ...

When using a Vue.js component, the value of this.$route can sometimes come back

I am attempting to retrieve the parameters from the URL and pass them into a method within a Vue component. Despite following advice to use this.$route, I am consistently getting an 'undefined' response. I have tried various solutions suggested ...

Guide on utilizing the eval() function to assign a value to a field passed as a parameter

I am interested in achieving the following: function modifyField(fieldName){ eval(fieldName) = 1234; } In simpler terms, I want to pass a specific field name as a parameter and then assign a value to that field. Can someone guide me on how to accomp ...

I implemented a proxy in my project to handle cross-domain requests, however, the requested address changes when I make a

Unable to Cross Domains http://localhost:8080/api/login has to be redirected to http://localhost:8080/index.html proxyTable: { '/api': { target: 'http://47.106.74.67:8080', changeOrigin: true, pathRewrite: ...

Execute PHP script through jQuery request within the context of a Wordpress environment

I want to replicate a specific functionality in WordPress. In this functionality, jQuery calls a PHP file that queries a MySQL table and returns the result encapsulated within an HTML tag. How can I achieve this? <html> <head> <script ...

Measuring values from table data using jQuery

Facing an issue with a jQuery script that involves creating a simple counting loop for each tr. My table structure is as shown below, and I am attempting to select the second td, multiply it by two, add it to the third td, and display the result in the fou ...

Dynamic CSS Changes in AngularJS Animations

I am currently working on a multi-stage web form using AngularJS. You can see an example of this form in action by visiting the link below: http://codepen.io/kwakwak/full/kvEig When clicking the "Next" button, the form slides to the right smoothly. Howev ...

Having difficulty navigating to a different page in Angular 4

I'm currently attempting to transition from a home page (localhost.com) to another page (localhost.com/listing). Although the app compiles correctly, I encounter an issue where nothing changes when I try to navigate to the new page. My approach has m ...

Using React.PureComponent, the list component efficiently renders each item with optimized performance

We've developed a reusable list component in ReactJS. To address performance concerns, we decided to incorporate the shouldComponentUpdate method to dictate when our list component should re-render. public shouldComponentUpdate(nextProps: TreeItemInt ...

Does Openerp or Odoo utilize ajax to transmit POST and GET data seamlessly, without the need for page refresh?

Curious about the technology behind ODOO (Openerp) that allows for sending POST and GET data without refreshing the page - surprisingly, there seems to be no visible AJAX code! ...

Error encountered: When trying to pass an event and two variables, the function e.preventDefault is not recognized as a valid

As a beginner in JS, I thought I had event handlers figured out. After hours of searching for a solution, I'm stuck. I'm trying to create a carousel, and while it mostly works, when I attempt to pass an event handler and two variables from one fu ...

Heroku - Launch your code in development or live environments

I am currently hosting my express API on Heroku with two separate projects set up: one for my Master Branch (Prod) and the other for my Development branch (Dev). Inside my package.json file, I have defined two scripts: "scripts": { "d ...

Transform Dynamic Array to JSON structure

I am currently developing a feature in my SvelteKit application that allows users to create custom roles for themselves. Users can input a role name and add it to an array, which is then displayed below. https://i.stack.imgur.com/oUPFU.png My goal is to ...

Is there a way to ensure uniform display of HTML form error messages across various browsers?

Recently, I completed a login form that consists of username and password fields. For the username, I used a text field with the type email, while for the password, I utilized a text field with the type password which requires validation through a regex pa ...

The Material-ui Drawer does not function properly when used with an external CSS file

For my project, I'm working on a Sidebar design that is inspired by the Mini Variant drawer demo available at this link. However, the project requirements mandate that all CSS styling should be done in a separate CSS file rather than directly within t ...

Conversion from Base64 to image was unsuccessful

I attempted to convert a Base64 string from an ajax post. The request appears to be successful with a proper return. However, when I tried converting it back to an image, I encountered the following error: An exception of type 'System.FormatExceptio ...

Sorting an array of strings that contain years in JavaScript

I am attempting to organize an array of seasons based on season and year, all while eliminating any duplicate seasons. Merely sorting the array did not produce the desired outcome, so I believe utilizing a regex might solve the issue. const myStringArra ...