The AddClass function fails to function properly after an ajax form is submitted

I am facing a challenge in setting up validation for my ajax form. My goal is to have a red border appear around the input field if it is submitted empty.

Unfortunately, when I try to use addClass(), it does not seem to have any effect. The alert message appears, but the border remains unchanged.

$(function() {
  $('#form').on('submit', function(e) {
    e.preventDefault();

    if ($('.required').val() === '') {
      $('.required').addClass('error');
      alert("error");
    }

    $.ajax({
      type: "post",
      url: 'php/php.php',
      data: new FormData(this),
      processData: false,
      contentType: false,
      success: function() {
        document.getElementById("text").innerHTML = "success";
        document.getElementById("add").style.border = "2px solid green";
      },
      error: function() {
        document.getElementById("text").innerHTML = "error";
        document.getElementById("add").style.border = "2px solid red";
      }
    });
  });
});
.error {
  border: solid 2px red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form id="form" method="POST" action="php/php.php">
  Name:
  <input type="text" name="Name" id="name" class="required"><br>
  <input type="submit" name="Add" id="add">
</form>

Despite checking other resources and posts, I am still unable to find a solution to this issue.

Edit: It turns out that xampp was encountering problems with importing external CSS files (or updating the data). Fortunately, the problem has now been resolved.

Answer №1

Have you incorporated jquery UI into your project? It seems that the addClass function in jquery UI is asynchronous, causing the alert statement on the following line to execute first and potentially block the main thread.

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

Opera browser having trouble with sidebar rendering

On my best days, I struggle immensely with troubleshooting browser display issues. The left-hand sidebar on this page () appears incorrect in Opera. While in all other browsers, the sidebar displays with an orange and tan background, for some unknown reas ...

Injecting SVG styling into HTML using the content tag and CSS

I am working with 3 different files: index.html <!DOCTYPE html> <html> <head> <link type="text/css" rel="stylesheet" href="style.css" /> </head> <body> <i class="logo myRed" aria-hidden="true"></i> ...

Ways to adjust the ngx-pagination color scheme?

I am looking to customize the background color of ngx-pagination Here is my current code: <pagination-controls class="custom-pagination" id="indicadorPaginationResults" (pageChange)="p=$event" maxSize="9" directionLinks="true" autoHide="true" previ ...

What is the best way to enforce a required bindings property in an AngularJS component?

Suppose I have the following component defined: angular.module('myApp').component('myComponent', { templateUrl: 'myComponent.html', bindings: { myPropOne: '<', myPropTwo: '<' ...

Typing the url in the address bar when using Angular's ui-router

Two distinct states are present: .state('test', { url: '/test', templateUrl: 'js/angular/views/test.html', controller: 'UserController', }) .state('test.list', { url: ' ...

What is the best method for uploading images and form content simultaneously in a Vue application?

How can I simultaneously upload images and form content? Is it possible to upload both to the client first and then to the server together with the form content? I'm looking to submit the form content along with the image to the server in one go when ...

Unleashing the Potential: Integrating a Scanner Device with

Currently, I'm facing the challenge of integrating a Scanner device with my Angular application. On one of the pages dedicated to scanning, users are able to view an alert indicating the connection status of the Scanner as well as any scanned document ...

Timeout for AngularJS Bootstrap UI Modal

I am having some trouble with opening a bootstrap modal using the $timeout function. The issue I am facing is that the modal keeps opening multiple times as the timeout fires repeatedly. Any assistance or suggestions on how to resolve this problem would be ...

The operation of my NodeJS application suddenly halts

In my project, I have a Server.js file that I run from the command line using: node server Within the Server.js file, a new instance of class A is created Class A then creates instances of both class B (web socket) and class C (REST API) If the web socket ...

Is it possible to restart an animated value in React Native?

I'm facing an issue in my react native app where I have created a simple animated progress bar, but I am unsure how to reset the animation. I attempted the following approach without success: progressValue = 0; How can I reset the animation? Also, w ...

No data is being retrieved through AJAX requests

Recently started diving into AJAX but still feel like I'm not fully getting the hang of it. My aim is to send partial data to the server, execute an SQL query, and receive the results back. Here's what I've been working on: Using jQuery j$ ...

Only a select few expandable elements in the jQuery accordion

How can I create an accordion menu with only a few expandable options? I am looking to include the following items in my menu: Home, Support, Sales, Other The "Home" option is just a link without any sub-menu. Clicking on it should direct users to a spec ...

Disable page scrolling after making changes to the DOM

When my JavaScript function executes on page load and at set intervals, it cycles through images supplied by another PHP script. However, every time the function manipulates the DOM, the page scrolls back to the top of the containing div, which is quite fr ...

Removing an appended value in jQuery: A step-by-step guide

Here is my code that successfully appends the first item: After clicking the "show count" button, a pop-up dialog box will display the count. However, to remove the appended item or refresh the page, additional steps are required. function showcount() { ...

Using Node.js, Express.js, and Redis.io for efficient order processing

Currently, I am working on a project that involves Node.js with express.js and redis.io as the database. I have implemented a get resource with query parameters to retrieve the IDs of libraries containing a specific book. However, I am struggling to unders ...

sticky bootstrap datepicker anchored to the top of the screen

Currently, I am working on a form that includes a date picker using the bootstrap datepicker In this setup, I have hidden the main bootstrap field and added three custom fields. When any of these fields are clicked, the calendar should open next to them. ...

Guide to configuring the overflow-y property for individual cells or rows in a Bootstrap-Vue table

Hello there, I am currently using Bootstrap-vue to display data that has been queried from a database. My goal is to have it displayed with an overflow-y style similar to this image. If you know how to achieve this effect, please share your solution. Here ...

Acquire Category Permissions when making a channel in discord.js v14

I am in the process of setting up a channel that will grant specific roles access while automatically blocking out @everyone. I also want this setup to be compatible with categories, allowing for other roles to have permissions within them. let customPermi ...

Display the active item in ng-repeat using conditional ui-view

Here is the situation: I'm working with a list of items that are displayed using ng-repeat. Each item has its own template. When a user clicks on an item, that particular item is marked as "active" and gets a different template compared to the rest ...

Unable to highlight text within a div container

I am currently facing an issue with my layout that involves three columns stacked to the left and four inner columns with three floated left and one floated right. This configuration is causing a problem where I cannot select any text on the page. Removing ...