What is the reason behind the CSS not rendering when async:false is used?

I find it peculiar and am actively seeking an explanation for this anomaly. In my code snippet, the AJAX call seems to be causing unexpected behavior:

    $('.edit-config').click(function() {
        var that = this;
        var msg; 
        ipt = $(this).closest('tr').find('input');
        $.ajax({ url: ajaxurl,
                 method: 'POST',
                 data: { 'action' : 'config_update', 'name' : ipt.attr('name'), 'val' : ipt.attr('value') },
                 beforeSend: function ( ) { $(that).addClass('updating').text("Updating ... "); },
                 complete: function ( ) { $(that).removeClass('updating').text("Update"); },
                 success: function ( submitted ) { 
                                if ( submitted === 'true' ) { msg = "Successfully updated configuration in database";  }
                                else { msg = "Error when trying to update database"; }
                          },
                 error: function ( ) { msg = "Unspecified internal error"; }
         });
         alert(msg); // This line may execute before AJAX is completed
    });

To ensure that alert(msg); is only called after the completion of $.ajax(...), I decided to introduce the async: false parameter. However, upon implementing this change, I observed that the CSS styling associated with addClass('updating') was no longer being applied as expected. Interestingly, this styling did appear correctly when the default value of async was set to true.

Answer №1

Running a network call synchronously means tying up your only thread, causing it to be unresponsive while waiting for the call to complete. It's important to avoid using async: false in your code.

It cannot be stressed enough that using async: false is a poor practice that is no longer supported by some browsers.

If you need certain actions to occur after the network call, utilize success/error callbacks rather than blocking the main thread with synchronous calls.

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

Issue encountered while attempting to load external JSON file from server in AngularJS

Currently, I am attempting to load a JSON file from the server. Below is my services.js file: angular.module('starter.services', []) /** * A simple example service that returns some data. */ .factory('Friends', function($http) { ...

"Every time an Ajax call is successful, the 'else' clause in

When it comes to using Ajax for user login in the system, I encountered an issue where the Ajax success function would always run the else statement even if the server returned a true Boolean value. This meant that even when the login credentials were vali ...

Find an idle event loop

Can you check for an idle event loop? Take these two examples: // Example 1 setInterval(() => console.log("hi"), 1000); // event loop not empty // Example 2 console.log("hi"); // event loop is now clear ...

Creating an HTML Canvas using an AngularJS template

I am facing an issue with rendering html elements on a canvas using html2canvas JS. I am utilizing AngularJS for data binding on the html page, but unfortunately, the dynamic data is not showing up on the canvas generated from these html elements. For inst ...

I'm interested in knowing if it's feasible to develop unique jQuery selectors that can navigate ancestors, such as a :closest or :parents selector

As a developer who frequently creates jQuery plugins, I often find myself using custom jQuery selectors like :focusable and :closeto to simplify common filters in my code. For example, the :focusable selector is defined as follows: jQuery.extend(jQuery.e ...

Tips for displaying the attributes of a product when making edits within a modal utilizing jquery, ajax, and Laravel

Struggling to update product details through a modal populated with inputs, including dropdowns and radio buttons. Using jQuery AJAX for data retrieval from the table. // show editing modal $('body').on('click','#editrentalhsedeta ...

Expanding the `div` element to visually occupy the entire vertical space

I'm facing a design challenge with my webpage layout. I have a fixed header and footer, but I need the content section to dynamically adjust its height between the two. The goal is to fill the remaining vertical space with a background-image in the co ...

Show dynamic HTML Dropdowns with nested JSON data

I've been racking my brains trying to implement this specific functionality in the UI using a combination of HTML5, Bootstrap, CSS, and JavaScript. My goal is to create dropdown menus in the UI by parsing JSON input data. Please Note: The keys withi ...

encountering issues when attempting to transmit data through an AJAX GET request

In my Spring-MVC project, I am encountering an issue while making an AJAX GET request to a .jsp page with some data. The error message I am receiving is shown below. Can someone assist me with this problem? Error WARNING: Failed to read HTTP message: org ...

"When utilizing a jQuery AJAX request to communicate with a Node.js server, the functionality only seems to

I'm diving into the world of AJAX and feeling a bit lost. On my webpage, I use an AJAX GET request to fetch comments on a post. However, there's a glitch where the request only succeeds after refreshing the page. I even tried disabling the cache, ...

Using importNode in the context of Microsoft Edge involves transferring a

I am facing an issue with a dynamic page that has the ability to change its main div content using a bar button. The pages are mostly static except for one which contains JavaScript (RGraph charts). To make it work, I am currently using the following code ...

What are the methods for choosing various boxes using the UP/DOWN/RIGHT/LEFT arrow keys?

This code snippet displays a 3x3 matrix where boxes can be hovered over and selected. The goal is to navigate around with keys and select boxes using ENTER. Can anyone provide guidance on how to achieve this functionality? <link rel="stylesheet" href ...

What is the best way to link one element to another element?

Apologies for the mismatched title, but here's my issue: I need to create hidden checkboxes for each Polymer's paper-button div in jsp/style related problems. <%int i; %> <form ACTION="Computation.jsp"> <% for(i=0; i<n; ...

What could be the reason why both the add and remove functions are unable to work simultaneously within a JavaScript function?

Hi there! I recently started diving into JavaScript and encountered a little hiccup. I've been working on a dice game where images change randomly whenever a button is clicked. The images transition from one to another, but I wanted to add a rolling ...

Angular version 1.6 with ES6, no errors in the application

Can you help me understand this? Note: I am using ui-router, and I suspect that is the issue. $stateProvider .state('login',{ url:'/', /*controller:'loginController',*/ controller: function(){aler ...

Error message "Unknown web method DoesUserExist. Parameter name: methodName" occurs when trying to pass a JSON value to a Web Method

Greetings, here is the JavaScript code I am working with: <script type="text/javascript"> $(document).ready(function () { function validateEmail(email) { var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2, ...

Guide to creating a parallax scrolling effect with a background image

My frustration levels have hit an all-time high after spending days attempting to troubleshoot why parallax scrolling isn't functioning for a single image on a website I'm developing. To give you some context, here's the code I've been ...

What's preventing me from using the left click function on my published blog post?

This is my first time creating a blogger template and everything seems to be working correctly. However, I have encountered one problem. For some reason, I am unable to left click on my blog post. I have not installed any right/left click disabler and I&a ...

The sinuous waveform in JavaScript

track : function(x, y, top, ampl) { return { top : top + 2, x : x + ampl * Math.sin(top / 20), y : (top / this.screenHeight < 0.65) ? y + 2 : 1 + y + ampl * Math.cos(top / 25) }; } This specif ...