Tips for combining JavaScript functions effectively

Here is the JavaScript code utilized on my HTML page

<script type="text/javascript>
function loadXMLDoc(HTTP)
{
    var xmlHttp;
    try {  
        xmlHttp=new XMLHttpRequest();
    } catch (e) { 
        try {    
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");   
        } catch (e) {   
            try {     
                xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");   
            } catch (e) {      
                alert("Your browser does not support AJAX!");      
                return false; 
            }    
        } 
    }

    xmlHttp.onreadystatechange=function() {
        if (xmlHttp.readyState==4) {
            alert(xmlHttp.responseText);
        }
    }  

    var params ="dd=123";
    xmlHttp.open("POST",HTTP,true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");
    xmlHttp.send(params);
}
</script>

In this JavaScript, I want to trigger each ajax function

<script type="text/javascript>

// Here I want to run functions together
return (loadXMLDoc('Page1.asp') && loadXMLDoc('Page2.asp') && loadXMLDoc('Page3.asp')); 
</script>

The issue here is that only the first function works and I do not receive the "return" value (meaning 2nd & 3rd functions do not work)

I am looking forward to your feedback

Answer №1

Keep in mind that the following statement:

return (loadXMLDoc('Page1.asp') && loadXMLDoc('Page2.asp') && loadXMLDoc('Page3.asp'));  

can be logically interpreted as:

if (loadXMLDoc('Page1.asp')){
    if (loadXMLDoc('Page2.asp')){
        if (loadXMLDoc('Page3.asp')){
            return true;
        }
    }
}
return false;

Hence, each subsequent call to the loadXMLDoc() function will only occur if the previous one returns true.

Answer №2

Ensure that your function loadXMLDoc() returns a value by adding "return true" to the end of the function.

    xmlHttp.send(params);

    return true;
}

When loadXMLDoc() returns true, it indicates that an AJAX request has been successfully initiated. The request will be completed at a later time, triggering the onreadystatechange function. Thus, multiple AJAX requests can run concurrently.

If you prefer to have sequential AJAX calls, consider using the following approach:

function doAjaxRequest( url, onreadystatechange )
{
    // code for creating XMLHttpRequest object and setting up parameters

    xmlHttp.onreadystatechange = onreadystatechange;

    // additional code for making the POST request
}

function loadXMLDocs( HTTP )
{
    var loadNextFile = function() {
        if (HTTP.length != 0) {
            var url = HTTP.unshift();
            doAjaxRequest( url, onreadystatechange );
        }
    }

    var onreadystatechange = function() {
        if (this.readyState==4) {
            alert(xmlHttp.responseText);

            loadNextFile();
        }
    }

    loadNextFile();
}

loadXMLDocs( ['Page1.asp', 'Page2.asp', 'Page3.asp'] );

Answer №3

Well, isn't this just a mess of indentation. Let's tidy it up;

<script type="text/javascript">
function loadXMLDoc(HTTP){
var xmlHttp;
try{  
    xmlHttp=new XMLHttpRequest();  
}catch (e){ 
    try{    
        xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");   
    }catch (e){   
        try{     
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");   
        }catch (e){      
            alert("Your browser does not support AJAX!");      
            return false; 
        }
    }
}
xmlHttp.onreadystatechange=function(){
    if(xmlHttp.readyState==4){
        alert(xmlHttp.responseText);
    }
}   
var params ="dd=123";
xmlHttp.open("POST",HTTP,true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.send(params);

return true;
}
</script>

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

What is the best way to replicate an Ajax call similar to the way Postman does it?

After successfully retrieving JSON data from a URL using Postman, I received an array as a JSON string. Below are screenshots of the process: https://i.stack.imgur.com/6uLSS.png https://i.stack.imgur.com/vDF0L.png I now want to achieve the same result u ...

What is the best way to retrieve the Axios Post response in React?

I'm facing a small issue. In my ReactJS code, I have a post function that is functioning correctly. However, I want to access the response of this function outside its scope, right where I called it. Is there a way to achieve this? async function che ...

How to grab selected HTML content with jQuery

I have been scouring the internet for a solution to this issue. My goal is to convert text selection start and end points into their corresponding HTML selection values. For example: HTML: test text **some <span style="color:red">te**st t</span& ...

Submitting a form without redirecting (using Facebook static and Magento)

This situation appears uncomplicated at first glance, but there are some complexities... I have a static Facebook FBML page where I am looking to have users sign up for my Magento newsletter. Typically, one would include the form code below in the fbml p ...

What steps can be taken to prevent an event from being triggered once it has already started but has not yet concluded?

Let's talk about the navigation bar on the website. Clicking on it toggles the menu holder to slide in and out from the side. It's a simple interaction. The bar contains an icon with the text 'MENU'. When you open the menu, the icon cha ...

Retrieving and storing data using jQuery's AJAX caching feature

When utilizing jQuery's $.ajax() method to perform an XHR based HTTP GET request to obtain a partial of HTML from a Ruby on Rails website, I encounter an issue. Specifically, every time a user clicks on tabbed navigation, I refresh an HTML table with ...

Encountering an issue in React: Uncaught ReferenceError - require function not recognized

I am currently working on a project that utilizes both react and node (express). When I include react using src="https://unpkg.com/react@16/umd/react.development.js", everything works fine with JSX in the project. However, when I attempt to import like thi ...

AngularJS: Error encountered when trying to assign a value to a read-only property in the ng-submit directive

I've been working on a personal project to practice angularJS, but I've encountered a problem that seems unsolvable to me. The issue arises when I try to utilize the submitLogin() function in my LoginCtrl.js file upon form submission. An error m ...

What is the step-by-step process to upload a file along with JSON data using fetch and multer

My task involves uploading a file along with some metadata on a JSON object using the "fetch" JavaScript native function on the client side and Express with the multer middleware on the server side. Client Side: const formData = new FormData() formData.a ...

Properly accessing a JavaScript object acquired from a JSON file

I have a JSON file with data for 4 different items. Once I parse the JSON file, I see the output below. At that point, do I now have a JavaScript object? My goal is to access each item and add them to a plain object. How can I achieve this? The resulting ...

Angular Material 2: Error - Could not be located

I have successfully installed Angular CLI globally, followed by Angular Material 2. https://i.sstatic.net/xNQqD.png In the process, I configured angular-cli-build.js & system-config.ts as shown below. angular-cli-build.js // Angular-CLI build configura ...

Refresh the component data according to the vuex state

In order to streamline my workflow, I am developing a single admin panel that will be used for managing multiple web shops. To ensure that I can keep track of which website I am currently working on, I have implemented a website object in my vuex state. Th ...

Creating Filled DIVs using JavaScript

Although it may appear to be a common inquiry, my specific needs have not been addressed in any of the Stack threads I've come across. I am dealing with a series of nested DIV statements, as demonstrated here (not all CSS included). I am looking to ...

Differentiate between chrome and chromium with the help of Javascript programming

Can we differentiate between Google Chrome and the open-source Chromium browser using JavaScript? It appears that the navigator.userAgent property is the same in both browsers. ...

An Ajax post request will only display output if multiple echo statements are present

Utilizing ajax to handle a login form, everything within the request is functioning correctly except for one issue. The data is being sent to the file login.php. The relevant code in that file looks like this: $dealer = $stmt->fetch(PDO::FETCH_ASSOC); ...

I am experiencing a problem where my AJAX responses are being downloaded instead of being loaded into the success data

I'm fairly new to using JQuery. I've been trying to send an AJAX request (File Upload) to a WEB API (ASP.NET MVC), but for some reason, my responses are downloading as JSON files instead of loading into the success data. Below is the code snippe ...

Load the iframe element only when the specified class becomes visible within the container div, without relying on jQuery

I am facing a unique challenge where the performance of my page is significantly impacted by loading multiple iframes. These iframes are contained within popup modals, and I would like to delay their loading until a user clicks on the modal. When the mod ...

Combining various JavaScript methods allows for the creation of complex

axis.remove(xaxis).remove(yaxis).remove(zaxis); Is there a way to condense these three removals into a single line (perhaps with regex)? This code snippet is related to the three.js library. ...

React form submissions result in FormData returning blank data

I am having trouble retrieving the key-value pair object of form data when the form is submitted, using the new FormData() constructor. Unfortunately, it always returns empty data. Despite trying event.persist() to prevent react event pooling, I have not ...

"Differences between Angular's $http and jQuery's $ajax: What is the equivalent of dataType

How do I specify the data type for Ajax responses in Angular? For example, it's easy to do in jQuery when wanting the response data to be in html format. jQuery: $.ajax({ url: "script.php", type: "GET", dataType: "html" }); Angular: $http({ ...