Obtain the Ajax function to provide a result of either true or false

I'm struggling to make an Ajax function return a true or false value for validation purposes. The other function needs to receive this value to determine the next steps.

I'm certain I've accomplished this before, but for some reason, it's not working now. I've experimented with synchronous and asynchronous calls, placing the return statement inside and outside the onreadystatechange function, but nothing seems to work.

Here is the Ajax code:

function saveBooking(){
    var service_ids=document.getElementById("allservice_ids").value;
    var provider_ids=document.getElementById("allprovider_ids").value;
    var chosen_time=document.getElementById("chosen_time").value;
    var chosen_date=document.getElementById("chosen_date").value;
    var message=document.getElementById("message").value;

    var parameters="service_ids="+service_ids+"&provider_ids="+provider_ids+"&time="+chosen_time+"&date="+chosen_date+"&you=<?php echo $_SESSION['user_mail']; ?>&message="+message

     if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
     }
     else
     {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
     }

     xmlhttp.open("POST","include/save_booking.php",true);
     xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
     xmlhttp.onreadystatechange = function() {//Call a function when the state changes.
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var yesorno=xmlhttp.responseText;
            if(yesorno=="ok"){
                return true;
            }
            else{
                document.getElementById("booking_error").innerHTML = xmlhttp.responseText;
                return false;               
            }
         }
     }
     xmlhttp.send(parameters);

   }

Currently, the save_booking.php file only contains <?php echo "ok"; ?>, simplified for testing purposes.

Can someone guide me on how to resolve this issue? When I try the following in the other function:

if(saveBooking()){
        alert(saveBooking());
     }

It only alerts 'undefined'.

Please keep in mind that I am not well-versed in jQuery, so suggesting 'use jQuery' would not be helpful for me.

Answer №1

Your current code is only affecting what the onreadystatechange method returns, which may not be useful for accessing its return value. To influence the return of saveBooking instead, you could try something like this:

 var responseOk = false;
 xmlhttp.onreadystatechange = function() {//Call a function when the state changes.
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        responseOk = (xmlhttp.responseText=="ok");
        if(!responseOk) {
            document.getElementById("booking_error").innerHTML = xmlhttp.responseText;
        }
     }
 }
 ...
 return responseOk;

On another note, unless you have specific reasons to avoid jQuery, I recommend looking into it as it can simplify your tasks significantly.

I also echo MilkyWayJoe's point - waiting for the return value of an asynchronous HTTP request doesn't align with the nature of asynchronous operations. In most cases, the example above would likely return false because the request hasn't finished by the time the script reaches the return statement. It's important to separate the function making the request from its callback.

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

Hi there, I am facing an issue with the modal window. Whenever I click on the image, it always displays the same image instead of the right one. Can you please suggest

The window opens, but instead of showing the image I clicked on, it displays the last image in the table. How can I fix this error? Below are my modal and map templates, which are the parent components of the modal. Thank you. <template> <di ...

CSS: Concealing a separate div

I am working with a parent div in my code that has 2 child divs. I am hoping to find a way to hide the second child when hovering over the first child, using only CSS or JavaScript. Take a look at my Fiddle here <div class="parrent"> <div id ...

Click on the next tab within the ExtJS tab menu

I am looking to deactivate a tab and if it happens to be active, I want the system to automatically switch to the next tab. I attempted myPanel.tab.disable(); if(myPanel.tab.active) myPanel.NextSibling().tab.setActive(); and myPanel.tab.disable(); ...

When working with an array of objects in Vue.js, what is the optimal approach: replacing the entire array or modifying individual values?

I am currently utilizing Vue and Vuex to dynamically generate components from an array retrieved from SQLite using the library better-sqlite3. let table=[ { id:1, column_1:'data', column_2:'data', column_3:{'1&apo ...

What is the best way to toggle the enablement of a textbox with jQuery?

Welcome all! Initially, all controls are disabled. Upon clicking the Add or New button, I want to enable textboxes and the Save button while keeping the Edit and Delete buttons disabled. Once the Save button is clicked, I wish to disable all textboxes and ...

Unable to execute script tag on PHP page loading

When I make an AJAX request to fetch JavaScript wrapped in <script> tags that needs to be inserted on the current page, how can I ensure that the code executes upon insertion? Here's the snippet I'm using to add the code: function display ...

Using TypeScript, implement a function that is called when a React checkbox's state changes to true

Currently, I am experimenting with the react feature called onChange. My goal is to update local data by adding a value when a checkbox is selected. Conversely, when the checkbox is unselected, I just want to display the original data. However, I find that ...

What is the process for sending a selected option using AJAX?

Using Ajax within Laravel to save data involves a form with input fields and a select option. Here is the form structure: <form class="forms" method="get" action=""> {{ csrf_field() }} <div class="form-group row ...

Having trouble pinpointing the source files that are loading .js in the <head> section of my Magento website

My console is showing me three 404 errors related to missing .js files in the head section of my website. Even though I don't actually need these files, I want to stop receiving the 404 errors as they are affecting my analytics and SEO. The files caus ...

Combining multiple rows into one using either mysql or lodash was achieved by Node

Currently in my Javascript framework, I am utilizing the Node MySQL library for executing MySQL queries. I encountered an issue with a left join that resulted in multiple rows being returned. This is because the left join generates duplicate rows with diff ...

Reactivate IntelliJ IDEA's notification for running npm install even if you have previously selected "do not show again" option

One of the great features in Intellij IDEA is that it prompts you with a notification when the package.json has been changed, asking if it should run npm install, or whichever package manager you use. I have enjoyed using this feature for many years. Howe ...

Organizing textual maps within a 2D array for rendering on an HTML5 Canvas

In my spare time, I am working on creating an HTML5 RPG game. The map is implemented using a <canvas> element with specific dimensions (512px width, 352px height | 16 tiles across, 11 tiles from top to bottom), and I'm wondering if there's ...

Creating Web Components using JavaScript on the fly

I tried to create web components directly from JavaScript, but I encountered an issue where the public constructor could not be found. Here's a basic example to illustrate the situation: The HTML Template: <polymer-element name="wc-foo" construct ...

Need for input

I am working on organizing my routes in a separate file from app.js. The login route requires access to a Firebase instance. routes/auth.js var express = require('express'); var router = express.Router(); module.exports = function(firebase) { ...

Exploring Sanity npm package with Jest for mocking tests

I am encountering an issue with mocking some code in my sanity.ts file: import sanityClient from '@sanity/client'; // eslint-disable-next-line @typescript-eslint/no-var-requires const blocksToHtml = require('@sanity/block-content-to-html&ap ...

Error: The terminal reports that the property 'then' cannot be found on the data type 'false' while trying to compile an Angular application

In my Angular application, which I initiate through the terminal with the command ng serve, I am encountering build errors that are showing in red on the terminal screen. ✔ Compiled successfully. ⠋ Generating browser application bundles... Error: s ...

The execution of Node.js callback function is not triggered

After setting up an API that queries a MongoDB and returns JSON Objects, I decided to modularize the code. I moved the MongoDB functionality to a separate file called queryMongo.js, which is now called in the POST request of main.js. Here is the main.js co ...

Creating a dynamic mouse trail effect using CSS and JavaScript without compromising element clickability

I'm looking to create a mouse trail that follows the cursor as it moves, made up of small icons or images that gradually fade out over time. I attempted to achieve this by overlaying a grid on top of all other elements on the page. The grid consists o ...

Showcasing the values of JavaScript

How can I resolve the issue depicted in the second picture? I need the value of 3 only in the USD column, with all others having a value of zero. <div class="span3"> <ul class="nav nav-tabs nav-stacked" > <?php foreach ( ...

a class instance in Java Script returned as undefined

Having sought resolution for this question once before, I find myself revisiting it as the issue still persists. My apologies for the duplicate post. The first file in question is block.js: class Block{ constructor(timeStamp, lastBlockHash, thisBloc ...