Establishing a secondary setTimeout function does not trigger the execution of JQUERY and AJAX

// Custom Cart Code for Database Quantity Update

$('.input-text').on('keydown ' , function(){

var tr_parent = $(this).closest("tr");

setTimeout(function () {

$(tr_parent).css('opacity', '0.3');

}, 4000); 

var input_value = $(this).val();
var input_value_length = input_value.length;
var product_id_update = $("#product_id").attr('data');

if(input_value_length > 0 ) {

// Delay execution using setTimeout

setTimeout(function () {
$.ajax({
url: "includes/ajax_code.php",
data:{input_value:input_value, product_id_update : product_id_update},
type: "POST",
success:function(data) {

$(tr_parent).css('opacity', '0.9');

}
});

}, 5000); 
}

});

In this code snippet, the opacity of an input element is set to 0.3 to indicate data transfer. However, a problem arises when trying to change the opacity to 0.9 after the AJAX request finishes.

Despite setting up a second setTimeout function in the success callback of AJAX, the input element remains at an opacity of 0.3 instead of transitioning to 0.9 as intended.

Answer №1

My suggestion is to adjust the initial opacity of an element to 0.3 before triggering an ajax call, signaling that a process has begun. After the ajax request completes (in success/error/done callback), you can revert the opacity back to 0.9.

$('.input-text').on('keydown change', function() {
    var table_row = $(this).closest("tr");
    
    var input_value = $(this).val();
    var input_value_length = input_value.length;
    var product_id_update = $("#product_id").attr('data');
    
    if (input_value_length > 0) {
        $(table_row).css('opacity', '0.3');// Move this line here
        $.ajax({
            // AJAX request details...
            
            // Upon successful response, set opacity back to 0.9
        });
    }

It seems like you are sending data on every keystroke which might not be efficient. Consider implementing a throttle mechanism for the ajax function by setting a timer when user types in an input field. This way, the ajax request will only be triggered after a one-second pause since the last keystroke, optimizing the process.

*Edit - I have created a demo on jsfiddle to demonstrate the optimized approach * demo - http://jsfiddle.net/rainerpl/49mjkagv/

<input type="text" class="input-text">
<img src="http://www.minefornine.com/pages/tpl/front/images/ajax_loader_big.gif" style="width: 24px; float: left;display: none;" id="loader" >

$(document).ready(function() {
    var input = $('.input-text');
    var timer;
    var loader = $("#loader");
    var loadStuff = function() {
        input.css("opacity", 0.4);
        loader.show();
        setTimeout(function() {
            input.css("opacity", 1);
            loader.hide();
        }, 2000); // Simulating ajax call  
    };
    input.on('keydown', function() {
        if (timer) {clearTimeout(timer);}
        timer = setTimeout(loadStuff, 1000);
    });
});

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

One class seems to be causing issues with hover functionality while the other works perfectly fine

HTML: <div class="channellist"></div> Through the use of Ajax, I am able to dynamically retrieve channels when the page loads and then append them within the channellist container. Once appended, my HTML structure appears as follows: <div ...

Utilizing various layouts in ASP.NET MVC with AngularJS

I am setting up two different layouts, one for visitors and one for management. Routes: app.config(['$routeProvider', function ( $routeProvider) { $routeProvider .when('/', { templateUrl: 'Home ...

What is the correct way to start a typed Object in TypeScript/Angular?

As I delve into the world of Angular and TypeScript, I am faced with a dilemma regarding how to initialize an object before receiving data from an API request. Take for instance my model: //order.model.ts export class Order { constructor(public id: num ...

Struggling with adding icons to the home screen in a Create React App?

When working with the manifest.json file, various icon sizes are specified as shown in this example: { “src”:”images/icons/apple-icon-57x57.png”, “type”: “image/png”, “sizes”: “57x57”, } In the index.html file, the ...

jQuery: Issue with functionality of dynamically generated "Remove" button

I currently have a setup where there is a form containing a button, which has the ability to dynamically insert a div that includes a paragraph along with a "remove" button: <!--form--> <form></form> <!--dynamically add div with para ...

"Is there a way to align a span element on the same line as an h

I'm attempting to align a text-number (span) next to an entry-title (h2) on the same line, with the entry-meta block on the following line, including having the reading time float left. I could use some help with my CSS implementation. Thank you. Ex ...

Skipping a JSON field in HTML/JavaScript when it is blank: A guide for developers

To develop an interactive program based on JSON input, I aim to display headers, subheaders, and choices derived from the JSON data. Some input fields may remain unfilled. For instance: Header Subheader Choice 1 Choice 2 Subheader2 Choice ...

When the function $(document).width() is called, it may yield varying results depending on the timing of the call

Every time I use $(document).width(); within $(window).load(function(){}) or $(document).ready(function(){}), the result differs from when it is called inside $(window).resize(function(){}). The discrepancy is approximately 100px, and it's not due to ...

Encounter a Config validation error while trying to utilize Nest.js ConfigService within e2e tests

I'm encountering an error despite having the NODE_ENV=development variable in my .env file. The error message reads: ● Test suite failed to run Config validation error: "NODE_ENV" must be one of [development, production] 11 | imports ...

Increment by 1 until a specific number is reached instead of displaying all numbers within an array

I have an array of numbers and for each number in the array, a request is sent to an external website using the number as a URL variable. The webpage content is then displayed. Instead of manually listing the numbers (1, 2, 3, 4, 5, 6, 7, 8, 9) in the arr ...

The issue arises when the mat-panel-description is not properly aligned with the shrinking panel

Within my HTML, I have a mat-panel with a description that is populated by a variable from the TS file. However, I am encountering an issue where if I shrink the panel and the description is too long, the text is cut off at the top and bottom. Is there a w ...

Is it possible for a Node.js server to specifically generate dynamic HTML, with Nginx handling the distribution of static data, and then automatically deliver the content to the client?

After primarily working with Apache and PHP, I've recently started exploring Nginx and Node.js and have been really enjoying the experience. Initially, I set up an Express server to handle website files and HTML rendering using Handlebars. However, I ...

Vue application experiencing issues with applying Sweet Alert CSS styles

I successfully integrated vue-sweetalert2 into my Vue app (version 2.6). The setup in my main.js file looks like this: import VueSweetalert2 from 'vue-sweetalert2'; Vue.use(VueSweetalert2); In one of my components, I have a basic button with a ...

Using JavaScript to manipulate an HTML canvas

I currently have an index.hTML file that is set up to display a canvas using the following code: <body> <canvas> </canvas> <script src="./JS/index.js" type="module"></script> </body> Within my JavaScript fi ...

Using three.js to create a rotating analog clock in Javascript

I currently have a traditional clock displayed in my setting that I want to synchronize with the current time. I am able to keep the clock running by calculating each hand's rotation every second, but I am encountering peculiar issues with the minute ...

I'm attempting to access a PHP file by clicking a button using AJAX and jQuery

I am just starting to learn the basics of jQuery and AJAX. I have already attempted to solve this problem by checking previous answers on Stackoverflow, but the code provided did not work for me. I have created two pages, index.php and testing.php, with a ...

Apply the CSS style to make one element identical to another, while modifying a single property

I am currently working with the following CSS: input[type="text"] { border: 2px solid rgb(173, 204, 204); height: 31px; box-shadow: 0px 0px 27px rgb(204, 204, 204) inset; transition:500ms all ease; padding:3px 3px 3px 3px; } My goal i ...

utilizing Typescript object within an array of objects

How can I optimize typing this nested array of objects? const myItem: Items[] = [{ id: 1, text: 'hello', items: [{ id: 1, text: 'world' }] }] One way to approach this is by using interfaces: interface It ...

Developing a MySQL DB-driven Node.js dashboard without the need for a poller

After exploring various StackOverflow posts on the topic, I haven't been able to find a solution that fits my specific situation. We have multiple monitoring instances across our network, each monitoring different environments (such as Nagios, Icinga ...

Choosing options from Bootstrap dropdown using Protractor

I am working with a Bootstrap single-button dropdown and I need to programmatically click on one of the options in the dropdown using Protractor. How can I achieve this? <div class="btn-group" ng-if="!persist.edit" dropdown> ...