How can I make the outer function in AJAX's onreadystatechange function return 'true'?

Within my Javascript/AJAX function below, I am striving for a return of true or false:

function submitValidate() {
    var xmlhttp;
    xmlhttp = null;
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        try {  xmlhttp = new XMLHttpRequest();
            } 
        catch (e){}
    } else if (window.ActiveXObject) { 
        try {  xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
            } 
        catch (e){
            try {  xmlhttp = new ActiveXObject('Microsoft.XMLHTTP'); // code for IE6, IE5
                } 
            catch (e){}
        }
    }

    if (xmlhttp) {   
        xmlhttp.open("GET","registerTest.php",true);
        xmlhttp.send();

        xmlhttp.onreadystatechange=function() {
            if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                if (xmlhttp.responseText==="true") {
                    return true;
                } 
            } // if xmlhttp.readyState && xmlhttp.status
        }// xmlhttp.onreadystatechange
    }// if

    return false;   
} //submitValidate()

The challenge arises when attempting to directly 'return true;' within the onreadystatechange function as shown here -

    xmlhttp.onreadystatechange=function() {
            if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                if (xmlhttp.responseText==="true") {
                    return true;
                } 
            } // if xmlhttp.readyState && xmlhttp.status
        }// xmlhttp.onreadystatechange

.. If there's a method to have submitValidate() return true in that scenario, kindly share.

Your feedback is greatly appreciated.

Answer №1

Essentially, there are two options available to you:

  1. If you send a request with the parameter async=false, your code will be forced to wait until the request is completed. However, this method is not considered user-friendly.

    var myValue;
    xmlhttp.open("GET","registerTest.php",false);
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            if (xmlhttp.responseText==="true") {
                myValue = true;
            } 
        } // if xmlhttp.readyState && xmlhttp.status
    }// xmlhttp.onreadystatechange
    xmlhttp.send();
    alert(myValue);
    
  2. Alternatively, you can leave things as they are and allow your code to continue executing while xmlhttp.onreadystatechange processes asynchronously after the request is complete (although the exact timing may vary due to network constraints).

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

Navigating additional information in D3 Node Link Force diagram

Recently delving into the world of D3, I have been pleasantly surprised by its capabilities and decided to experiment with the Directional Force Layout. My Objective Initially, I successfully created a json object using a for loop to prepare my items for ...

The element's height appears to be fluctuating unexpectedly when I attempt to adjust it using percentage values within a narrow range

I'm utilizing React and Bootstrap in this project. Here's an overview of my code: I have an element with height set to 0, in rem. My goal is to make the height of this element increase as I scroll down the page, creating the illusion that it is ...

Using jQuery's .live('click') method will only bind to the initial element found on the webpage

I developed a custom jQuery plugin that attaches to 8 different elements on a webpage. Within each element, I intended to utilize the .live() method to bind a click event to a link, triggering a form submission via ajax. However, I encountered an issue whe ...

What is the most effective method for identifying a specific row or record based on a user ID among a large set of user

Within my database lies a table filled with records, each having their own primary ID key and user ID key. On the client side, my JavaScript code contains an array brimming with numerous user IDs. My goal is to search for and select the records in the tabl ...

Creating a jquery DataTable from HTML generated by angular $sce can be done by following these steps

I have created an Angular controller that takes data and generates an HTML table from it. The generated table is being displayed on the page. Now, I want to apply jQuery data tables using that scope variable. The variable contains the HTML code of the tabl ...

The function responsiveTable does not exist

I recently added the following code to my aspx page: <script src="../Scripts/jquery.responsivetable.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $('#grdStudent').responsiveTable( ...

Move the element that can be dragged with the identifier X to the designated drop area with the identifier

I am attempting to create a function that will allow me to drag a draggable element and drop it into a designated container using their IDs. However, I am unsure of how to get started. dropToContainer("myDraggable", "div3"); function dropToContainer(co ...

What could be the reason behind the child component updating without triggering a re-render in Reactjs?

I am encountering an issue with my main component and child chart component. Even though the main component updates the state of the child chart component upon connecting to a websocket, the chart does not redraw as expected. Interestingly, when I click on ...

Attempting to route a selector, yet on the second attempt, the entity is successfully transferred

I am currently working on developing a function that will switch the image every half second for 10 iterations. During the final iteration, the image src will be set to the actual value. Everything seems to work fine for the first loop, however, when the s ...

Swapping out the JSON data from the API with HTML content within the Vue.js application

I am currently working on a project involving Vite+Vue.js where I need to import data from a headless-cms Wordpress using REST API and JSON. The goal is to display the titles and content of the posts, including images when they appear. However, I have enco ...

What is the best way to search for a CSS selector that includes an attribute beginning with the symbol '@'?

Whenever I want to target an element with a click event, I usually use the following jQuery selector: $('div[@click="login()"]') <div @click="login()"> Login </div> However, when I tried this approach, it resulted ...

Trouble with toggling div visibility using jQuery and AJAX

I'm trying to display a specific div based on the result of an SQL query. The problem I'm facing is that I can't seem to toggle the divs asynchronously. Currently, the page needs to be reloaded for the div to reflect the changes. <?ph ...

Pass a parameter to an AJAX request in order to retrieve data from a JSON file that is limited to a specific

I am working with a JSON file named example.json, structured as follows: { "User1": [{ "Age":21, "Dogs":5, "Cats":0 }], "User2": [{ "Age":19, "Dogs":2, "Cats":1 }] "User3 ...

Entity Framework and the GET request error: Connection Reset

Currently, I am working on developing a straightforward notes application using Entity Framework in ASP.Net Core for the backend and AngularJS for the frontend. The main objective is to have the app load a pre-existing list of notes from my MySQL database ...

Creating a JQuery slider that efficiently loads and displays groups of elements consecutively

Currently, I am in the process of developing an infinite horizontal tab slider using jQuery. My main objective is to optimize loading time by having the slider display only the first 10 slides upon initial page load. Subsequent slides will be loaded as the ...

Change the className of an element in React upon clicking it

I just finished developing a menu bar using ReactJS with some basic routing features. Here is the JSX code for the component: class TopBar extends Component { state = { menus: [{id:0,menu:"Home"}, {id:1,menu:"Contact"}, {id:2,menu:"About"}] } a ...

What is the proper way to input a Response object retrieved from a fetch request?

I am currently handling parallel requests for multiple fetches and I would like to define results as an array of response objects instead of just a general array of type any. However, I am uncertain about how to accomplish this. I attempted to research "ho ...

Removing the navigation button from the hamburger menu

I am working on creating a semi-progressive top navigation bar. For the mobile viewport, the navigation bar will only display the logo and a hamburger button. When the button is clicked, various navigation menu options as well as the Log In and Sign Up bu ...

Issue encountered while serializing data in next.js when utilizing getServerSideProps function

Encountering An Error Error: The error message "Error serializing .myBlogs returned from getServerSideProps in "/blog"" keeps popping up. I'm facing a problem while attempting to log the data! Initially, when I was fetching data using use ...

The select2 option seems to be malfunctioning as it is not

I have implemented a dropdown using Select2. Although I am able to retrieve data from the backend and display it successfully in Select2, I'm facing an issue with certain data that contains multiple spaces between words. For example: Test&nbsp;& ...