Unable to halt operation when xmlhttprequest.responseText is equal to a particular value

Currently, I am incorporating XmlHttp with Java servlets in the following manner:

function btnSave_onclick(){

var xmlHttp;
var responseText;

if (condition){

    var para= "someParamsHere";

    var url = "urlHere";

    if (window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    }

    else if (window.ActiveXObject) {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlHttp.open('post', url, true);
    xmlHttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=UTF-8');
    xmlHttp.setRequestHeader("Content-length", para.length);
    xmlHttp.setRequestHeader("Connection", "close");

    xmlHttp.send(para);

    xmlHttp.onreadystatechange=function() {
        if (xmlHttp.readyState==4) {
            if(xmlHttp.status==200){
                responseText=xmlHttp.responseText;
                if(responseText=='error'){
                    alert("Fatal Error Occurred");
                    return;
                }
           }
        }
    }

}

// additional code goes here

}

The information is sent to the servlet and if an exception arises, the response text containing the word 'error' is displayed. The issue is that the error alert pops up but the code proceeds to the section // additional code goes here without exiting the JavaScript function on return. Any suggestions on this matter would be much appreciated.

Answer №1

Understanding the essence of "A" in AJAX is crucial, as it signifies the asynchronicity. The code housed within the inner function (

xmlHttp.onreadystatechange=function() {...HERE...}
) operates asynchronously. This implies that the entire outer function (btnSave_onclick()) will finish and at a later point, the onreadystatechange will trigger (if at all). In simplified pseudocode where condition === true, your current code can be visualized as:

function btnSave_onclick() {
    doAjaxAndWhenItFinishesRun(function(responseText) {
        if( responseText=='error' ) handleFatalError();
        else handleSuccess();
    });
    doStuff();
}

To enhance clarity, I propose a revised version without the inner function:

function ajaxFinished(responseText) {
    if( responseText=='error' ) handleFatalError();
    else handleSuccess();
}

function btnSave_onclick() {
    doAjaxAndWhenItFinishesRun(ajaxFinished);
    doStuff();
}

The updated structure demonstrates that btnSave_onclick() initiates two operations - an asynchronous call followed by doStuff(). Subsequently, upon completion of the async call, ajaxFinished() is executed. To ensure that doStuff() runs exclusively on success, you would need to invoke it from handleSuccess() or integrate it within this segment of your code:

function btnSave_onclick(){
    ...
    if (condition){
        ...
        xmlHttp.onreadystatechange=function() {
            if (xmlHttp.readyState==4) {
                if(xmlHttp.status==200){
                    responseText=xmlHttp.responseText;
                    if(responseText=='error'){
                        alert("Fatal Error Occurred");
                    }
                    else {
                        // additional code here
                        // ... this section executes upon success
                    }
               }
            }
        }
    }

    // any code placed here will execute regardless and BEFORE the AJAX call concludes
}

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

Class for Eliminating the Background Image Using Bootstrap

Is there a Bootstrap class that can be used to remove a background image from a div? Currently, I have this style defined in my CSS: background-image: linear-gradient(to bottom, rgba(0,0,0,0.1), rgba(0,0,0,0)); I would like to remove it using: bg-img-non ...

Building an interactive chat feature with jQuery/AJAX and Pusher: A step-by-step guide

explore: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script src="https://js.pusher.com/4.4 ...

Populate Chart.js with a specific set of JSON data

As I delve into the world of JavaScript, I'm faced with a challenging issue that I need help resolving: I have a JSON file housing an array of data. What I aim to do is extract specific arrays from the month of August (Reports, Average, Global) and d ...

Adaptive Container with Images that are not stretched to full width

Is there a way to achieve the same effect as seen in images 2 and 3 here: Although these images already have their own "padding," I'm curious if it can be replicated using just jQuery and CSS? I would appreciate any help or insights on this. Thank y ...

Endless Keycloak redirection loop

We have integrated Keycloak 2.3.0.Final into our system and are utilizing the Javascript adapter located at /auth/js/keycloak.js. Our application, built using React+Redux, encounters an issue during the authentication process outlined in the documentation. ...

Verifying the "select" dropdown option prior to final submission

My website features multiple select dropdowns that require validation before submission. For instance, there may be a situation where seven select dropdowns are present as described below. My desired validation criteria is: If there are 5 or more "sel ...

Exploring the functionalities of can-deactivate without incorporating routing

I'm facing an issue with a parent component and multiple child components. The parent component contains a form, while each child component also has its own form. Unfortunately, all child components share the same route as the parent component and hav ...

encountering a problem with retrieving the result of a DOM display

private scores = [] private highestScore: number private studentStanding private studentInformation: any[] = [ { "name": "rajiv", "marks": { "Maths": 18, "English": 21, "Science": 45 }, "rollNumber": "KV2017-5A2" }, { "n ...

Mobile Devices Experiencing Issues with Proper Resizing of Three.JS Panorama

I'm currently working on a project using Three.Js and its device orientation library to create a panorama that users can navigate by moving their phones. Initially, everything looks great as intended: Proper Panorama However, upon refreshing the pag ...

Exploring the documentation of JQuery's $.Ajax Function

Can anyone help me locate the parameters in the JQuery Docs? jqXHR.done(function( data, textStatus, jqXHR ) {}); http://api.jquery.com/deferred.done/ I've been trying to determine what data represents but haven't had any luck. I've notic ...

Using the built-in http module in node.js to upload images via multipart/form-data

I have encountered an issue where I need to send two images and an API key as part of a multipart/form-data HTTP request to an API. The images are retrieved from an AWS S3 bucket, which works fine. However, when attempting to send the image data as part ...

Configuring a Selenium Firefox profile

While performing our tests, we came across an issue with how FireFox handles events when the browser is not in focus. We discovered that this problem can be resolved by setting up a FireFox profile with the preference "focusmanager.testmode" set to true ( ...

Explaining how to iterate through objects (one by one) in the This.questionnaire.Profile at every click using JavaScript (answer not found in forums)

Creating a series of questions, each part being stored in This.question = {p1: {...}, p2: {...}, p3: {...}, p4: {...}, p5: {...} etc. (and many more). I want to be able to switch from one article to the next every time I click a button... click => next ...

Vue 2 checkbox form array data

Creating a checkbox list with a dynamic id and name: Data: yards[{id:1,name:'test'}] etc HTML: <ul class="checkbox-list"> <template v-for="(yard, index) in yards"> <li> ...

An issue arises when attempting to utilize URL parameters within a loader

In my React project, I am utilizing React-Router. The code for my movie page is as follows: import React from "react"; import axios from 'axios' export async function loader({ params }) { const movieId = params.movieId; const mov ...

Tips for continuing code execution in an ajax success function following the completion of a nested ajax call within the success block

I am facing an issue with a function that utilizes $.ajax. In the success section of the function, I have three nested functions. The first one executes properly, but the second one contains another $.ajax call. While the internal $.ajax call works fine, t ...

Validating usernames with parsley (version 2.8.1) using php

Despite reading all the documentation on the Parsley Js website, I am still struggling to understand how to set up custom validation based on AJAX responses. My specific challenge is to validate a username and check if it already exists in the database. I ...

Exploring Angular2: A Guide to Interpolating Expressions in Templates

Is it possible to interpolate different types of Javascript expressions? Along with displayed properties like object.property and short expressions such as {{1+1}}, what other valid Javascript expressions can be used for interpolation? ...

Struggling to make the controller karma test pass

I am currently working on developing a "To Do list" using angular js. My goal is to allow users to click on a checkbox to mark tasks as completed after they have been finished. While the functionality works fine in the index.html file, I am struggling to p ...

"An issue with AngularJS ngTable causing a delay in the rendering of Ajax

Struggling with ngTable Setup Having trouble mastering the use of ngTable by going through the ngTable ajax demo. I attempted to follow along with the example as closely as possible, but I'm encountering a deviation in defining an ngResource inline w ...