Reordering Javascript code using Ajax with synchronization set to false

I encountered an issue with a button click event triggering an ajax call in my code. To ensure that the ajax call is synchronous, I set async:false. In order to provide user feedback during the call, I included the following code snippet:

$('#ajaxBtn').on("click",function() {
    $('#ajaxBtn').html("processing ...");
    $.ajax({
        type: "Get",
        url: "example.php?data=test",
        async: false,
        success: function(){
            alert("success");
        },
        error: function(){
            alert("failure");
        }
    })
}

Interestingly, when testing on Chrome (not tested on other browsers), upon clicking the button, the browser freezes until the completion of the ajax call. However, the text on the button doesn't update until after the success alert is shown. When debugging and stepping through the code, the behavior is as expected - the text changes before the ajax call begins.

Upon setting Async: true, the functionality seems to work correctly. The text updates instantly and then proceeds to the success function.

This leads me to question whether Chrome is reordering the ajax call to execute before updating the text on the button. Can anyone shed some light on this behavior?

Answer №1

How about considering this alternative approach.

$('#ajaxBtn').on("click",function() {

    $.ajax({
        type: "Post",
        url: "sample.php?data=trial",
        //please note the exclusion of async: "true",
        beforeSend:function(){
             $('#ajaxBtn').html("processing ...");
        },
        success: function(){
            alert("great job!");
        },
        error: function(){
            alert("oops, something went wrong");
        }
    }).done(function(data){
        //process your form based on the data received

    });
}

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

EffortlessDrop.js and anchors

Currently using EasyDropDown.js to style a select element, which creates a modern dropdown menu using jQuery. I'm curious if it's possible to include a hyperlink in one of the select options. Here's an example of what I'm trying to ach ...

Sending a javascript variable to an angularjs scope

Currently, I am utilizing Flask to render an HTML template and wish to transfer the variable add_html_data, which is passed via Flask's render_template, to the scope of an AngularJS controller. I have attempted the following: <body> <di ...

Step-by-step guide on setting up ReactJS in Webstorm

I've been attempting to set up ReactJS in my WebStorm IDE, but I'm having trouble figuring out the correct way to do it. Is ReactJS an external library? Should I just add a new JavaScript file? I already have node.js installed on my computer and ...

"Encountered a corrupt XLSX file when attempting to download through Vue.js with Axios

Hey there, I've been attempting to generate a download using axios for an excel file but unfortunately, I haven't been successful in opening it. Could you please assist me in identifying the problem? const blob = new Blob([result.data], { ty ...

Choose a JavaScript function by clicking on the HTML text

As a beginner in the world of coding, I have been diving into JavaScript, HTML, and CSS. Inspired by fictional supercomputers like the Batcomputer and Jarvis, I've challenged myself to create my own personal assistant to manage tasks, games, programs, ...

Calculating date discrepancies with JavaScript

Two fields are present, one for the start date and one for the end date. I would like to display the date difference in another text box when the user selects dates from a date picker. Although I have made some progress on this, I believe that there are st ...

Struggling to Understand Middleware in Node.js Express

I am currently delving into Express.js and finding myself a bit puzzled by the nuances between middleware functions and route handlers. I grasp the concept that middleware functions typically include the next argument, but I am struggling to discern when a ...

Nesting ng-repeat within another ng-repeat for dynamic content generation

I am currently working on a page that requires displaying boxes (using ng-repeat) containing information about channels and their corresponding cities. The issue I am encountering arises when repeating the second ng-repeat: <table class="table table-c ...

Sending form data using Ajax in codeigniter

I am encountering an error while attempting to submit a form using ajax in codeIgniter. Below is the view code that I have: <div class="form-group input-control"> <p id="error1" style="display: none; color: green"><b>Registered Succ ...

What is the best method for updating the .value property within an AngularJS controller?

I managed to successfully pass a value from one AngularJS module to another using the .value method. Here is an example of it working: var app = angular.module('app', []); app.value('movieTitle', 'The Matrix'); var app1 =ang ...

"Learn how to implement a dropdown menu using Vue.js and Quasar on Cloud Firebase

Hey there, I'm trying to figure out how to retrieve and display a Firebase array in a dropdown using Vue js. Here's what I currently have: I've read some of your articles before, but I'm having trouble displaying the data from an array ...

"Navigate back with just a click - XSL button

My expertise in this area is limited. After some searching, I couldn't find exactly what I need. Hopefully, the solution is simple. I am currently developing a software control system with a built-in web server. Certain points during navigation requi ...

`Disappointing Outcome: Spring MVC - Ajax file upload fails to function`

I'm having trouble dynamically uploading a file using AJAX and Spring MVC. Here is the approach I am taking: JavaScript function: function initializeQwacCertificate(){ $('#qwac').on('change', function(){ var formData = n ...

What sets apart the concept of asynchrony in C# from that in JavaScript?

When working with Python and JavaScript, a common issue arises due to blocking the event loop. This occurs when code is executed in a single thread and only one synchronous operation can be performed at a time. Interestingly, this problem does not seem t ...

Is it secure to edit and save user HTML using JavaScript?

Consider this scenario: I've developed a cutting-edge tool for creating forms with Javascript. Users can utilize links to integrate html elements (such as input fields) and leverage TinyMCE for text editing. The data is saved through an autosave featu ...

Utilizing an external API in Javascript for fetching data

Is it permissible for me to directly initiate an API request from JavaScript to an external API (in this scenario at ) using the XMLHttpRequest object? If not, what steps should I take to retrieve data from this source? Do I need to incorporate a PHP bac ...

Is there a way to reset the dynamic flexslider when a click event occurs?

Seeking a way to refresh the flexslider on a click event. I have embedded the flexslider in a Bootstrap pop-up and need it to update when the user clicks. The issue arises when I try to refresh the slider as it fails to display properly, likely due to losi ...

Is there a way to achieve element scrolling similar to scrollLeft within a scrollable container without using JavaScript

Looking for a CSS Solution: Is there a way to achieve element.scrollLeft functionality in CSS without using javascript? I want to pre-scroll a scrollable container. Situation Overview: I have a scrollable container that houses various items. Some instanc ...

What is the best way to showcase data from an external model without having to constantly refresh the page?

I am attempting to showcase a User's name at the top of a box where they input their Employee # in a form, all done without needing to refresh the page. The process is simple: the user enters their # and upon clicking or tabbing onto the next field, ...

How to maintain a child component's state without resetting it when the parent component's state changes and also retrieve the values of all child components in ReactJS with Typescript

Recently, I've been diving into React and encountered a roadblock while working on a custom dropdown filter for a table in my React application. Each column in the table has a set of dropdown values and an Apply button. To implement this, I created a ...