JavaScript - Struggles with developing a personalized AJAX function

I have been working on creating a function to manage my AJAX post requests. While I have successfully sent the data, I am encountering difficulties with receiving the response.

The function in question is named ajaxPost(paramArray, target). It takes parameters and forms a string to send to the specified target.

I suspect that the problem lies within ajaxReq.onreadystatechange, as it seems to be skipping over this portion and terminating the script prematurely.

Here is the script for reference:

function ajaxPost(paramArray, target){
    var param = '';
    var key;
    for (key in paramArray){
        param = param + key + '=' + paramArray[key] + '&';
    }
    param = param.substring(0, param.length - 1);

    var ajaxReq = new XMLHttpRequest();
    ajaxReq.onreadystatechange = function(){
        if(ajaxReq.readyState == 4 && ajaxReq.status == 200){
            return ajaxReq.responseText;
            document.write('Test?');
        }
    }
    ajaxReq.open('POST', target, true);
    ajaxReq.setRequestHeader('Content-type', "application/x-www-form-urlencoded");
    ajaxReq.send(param);
}

This function performs the necessary actions. Below is an example of another function that utilizes the above one:

function submitPost(form){
    var title = form.title.value;
    var text = form.textBody.value;
    var name = form.nameOfPoster.value;
    var paramArray = {};
    paramArray['title'] = title;
    paramArray['text'] = text;
    paramArray['name'] = name;
    if (ajaxPost(paramArray, 'post.php')){
        location.reload(true);
    }
}

The parameters are passed to ajaxPost(). If a response is received, the page reloads.

It appears that there might be a delay in retrieving the data mentioned earlier. I am exploring JavaScript without using jQuery, so any suggestions or tips are welcome.

Thank you! Feel free to provide additional advice if you have any.

Answer №1

Understanding AJAX's asynchronous nature is key. Your current approach won't work because the ajaxReq.onreadystatechange function runs after the request completes, while script execution continues. This means that:

if (ajaxPost(paramArray, 'post.php')){
        location.reload(true);
}

gets executed before ajaxReq.onreadystatechange.

To address this issue, consider passing a callback function to your method:

function ajaxPost(paramArray, target, callback){
    var param = '';
    var key;
    for (key in paramArray){
        param = param + key + '=' + paramArray[key] + '&';
    }
    param = param.substring(0, param.length - 1);

    var ajaxReq = new XMLHttpRequest();
    ajaxReq.onreadystatechange = function(){
        if(ajaxReq.readyState == 4 && ajaxReq.status == 200){
            callback(ajaxReq.responseText);
            document.write('Test?');
        }
    }
    ajaxReq.open('POST', target, true);
    ajaxReq.setRequestHeader('Content-type', "application/x-www-form-urlencoded");
    ajaxReq.send(param);
}

Then modify your code like so:

function submitPost(form){
    var title = form.title.value;
    var text = form.textBody.value;
    var name = form.nameOfPoster.value;
    var paramArray = new Array();
    paramArray['title'] = title;
    paramArray['text'] = text;
    paramArray['name'] = name;
    ajaxPost(paramArray, 'post.php', function(res) { 
        if(res) {
            location.reload(true); 
        }
    });
}

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 integrate a calendar feature within an Angular 2 application?

I am brand new to Angular 2 and have a question: I need to integrate a calendar into a page where users can add events. Something similar to the following example: I'm unsure if the angular material calendar project is designed for Angular 2 or for ...

Transforming a jQuery menu into an active selection with Vue JS

I am looking to transition away from using jQuery and instead utilize Vue for the front end of a menu. Specifically, I need to add an active class and a 'menu-open' state to the appropriate nested list items, similar to what is achieved in the pr ...

What is the method to update an element when any of the items in an array is marked as "Confirmed"?

{submissions && submissions.files_set.map((el) => { if (el.confirmed_status === null) { return <DataToConfirm />; } else if (el.confirmed_status === "CONFIRMED") { return <DataSent />; } })} This ...

Using Python and Selenium WebDriver to execute a JavaScript function in a web application

Attempting to obtain a link for checkout on an e-commerce site, I attempted to click on the span that triggers a JavaScript function: <a id="checkout-btn" class="btn btn-lg btn-success pull-right" href="javascript:shop.orders.save()" rel="nofollow"> ...

Is Apollo Client in NextJS failing to refresh data post mutation?

On this page, you can create a new User const [createType, { loading, data }] = useMutation(CREATE_USER_CLASS) //mutation query const createUserClass = async (event) => { event.preventDefault(); try { const { data } = await createType({ ...

Embedding an external form using POST method within an iframe

My goal is to have a page containing a POST form load inside an iframe so that users can confirm actions like deleting a listing. I've managed to load the JS and form page within the iframe, but when I interact with the form, it just refreshes the pag ...

What is the best way to add up values from text fields with the same ID?

I am working with input fields that are set up like this <input id="nilai" name="nilai" type="text" value="10" readonly /> <input id="nilai" name="nilai" type="text" value="10" readonly/> <input id="nilai" name="nilai" type="text" value="10 ...

Experiencing difficulties with implementing a PHP and AJAX search feature

I am still relatively new to working with php, ajax, and mysql. Currently, I have successfully created a search function that is returning the desired data. Essentially, I have established a mysql database and developed a php website with a functional sea ...

Top method for identifying genuine users and preventing bots

Utilizing a Maps API can be costly, especially with the fees per request To minimize requests, I heavily rely on caching techniques The API is invoked on every pageload, but unnecessary for non-human users like googlebot What would be the most effective ...

Instructions for calculating the product of two text fields and showing the result in a separate text field without hitting submit in Rails (using jQuery or JavaScript)

Hello, I'm attempting to multiply the values of two text fields in Rails and display the result in another text field. In jQuery, we achieve this by performing a specific function. You can test it out on this link. However, I'm struggling to impl ...

Ext 4.1 - Accessing a class instance using Ext.define()

In my code, I have a class with a method defined like this: Ext.define('MY.class.Manager', { .... .... .... manageStuff: function(){ } } Initially, the manageStuff function was only needed in one place and everything worke ...

Collapse the stacked navigation menu upon clicking a new item, utilizing Bootstrap 4 features

One issue I am facing is with my layered navigation setup. https://i.sstatic.net/xyz123.png Whenever I click on two items that have children, both of them remain open causing the menu to get a scrollbar. However, I do not want to hide the scrollbar. htt ...

Tips for decreasing the size of an individual division within the grid system in Bootstrap

<div class="col-sm-2" style="text-align: right;" > mytext1 </div> <div class="col-sm-2" style="text-align: right;" > mytext2 </div> <div class="col-sm-2" style=&qu ...

What is the best way to access the references of 'child controllers' in NavigatorIOS within a React Native app?

After diving into react-native for the past few days, I've encountered a dilemma regarding the NavigatorIOS component. Is there a way to access and manipulate 'child controllers' of NavigatorIOS similar to how it's done in native object ...

What is the process for accessing a website using Java programming language?

Currently, I have a jar file up for sale that requires users to sign up on a particular website in order to download it. My issue lies in wanting to verify if purchasers have a valid login for the site when they run the jar file. Despite my attempts with h ...

Incorporating a class into ever-changing Bootstrap Table rows

Looking to enhance my table rows with a class, excluding the header. Struggling to find a way to do this. Any ideas? This is the table in question: <table id="table" class="hidden table table-bordered table-striped table-hover"> <thead> ...

What causes the imported constant in Vue to fluctuate in value?

In my Vue component, I am importing an array named CHART_CARDS. This array is used to set the initial state for another array called chartCards, which can be modified by the user. import { CHART_CARDS } from '~/constants/chartCards' ... export ...

Using JavaScript and jQuery to compare two JSON objects, then storing the result in a separate object

I am currently working on an API call that provides an updated JSON object, as well as a static JSON object file. My goal is to compare a specific value in the objects for teams with the same name. For example, if Team John had 22 members in the old file ...

Ways to trigger an event or invoke a function after initializing Stripe JS

My checkout page is optimized with the new Stripe Payment Element for fast loading using SSR. However, I am facing an issue where the element sometimes causes the page to reload 2 or more times before functioning properly. Occasionally, it also displays ...

Retrieve the identifier of the parent li element

We have an HTML structure shown below. A jQuery function is triggered when the click me link is clicked. Is it possible to retrieve the id of the enclosing li element from this function? If yes, how can this be achieved? <ul> <li id="20"> &l ...