What steps can be taken to halt an ongoing AJAX call and initiate a new one with different parameters?

I recently implemented an ajax call using the jQuery.everyTime() function. The setup involves a combo box where users can select different graph names, triggering dynamic calls to an ajax function that returns JSON data and populates a chart in the View every 10 seconds.

While everything seems to be working smoothly, I encountered an issue when selecting a new graph name. Instead of just retrieving the new graph data, the old one is also requested simultaneously. This results in multiple requests being sent out, with only the latest one actually being displayed (although all previous requests are visible in Firebug).

This is the code snippet for my ajax function:

var selected = $("#name_list :selected").val();

    $(".title_graph").text(selected);

    var j = jQuery.noConflict();
    j("#hour").everyTime(10000,function(i){
        j.ajax({
          type: "GET",
          url: "getchartdata?graphName=" + selected +"&subgroup=hour",
          cache: false,
          success: function(jsonData){
              var data = eval(jsonData);
              drawChart(data, data[0][0], data[0][1]);
          }
        })
    });

I am looking for a way to cancel the previous ajax calls without having to refresh the page. Is there a method to achieve this, such as adding a "stop" at the beginning of the function? I have come across suggestions like using ajaxName.abort(), but it doesn't seem applicable to my specific case.

Thank you in advance for any insights or assistance.

UPDATE:

Following Travis' suggestion, here is the updated version of the code:

function getChartsByGraphName() {
    var selected = $("#name_list :selected").val();
    var ajaxCallHour;
    $(".title_graph").text(selected);

    var j = jQuery.noConflict();
    j("#hour").everyTime(10000,function(i){
        ajaxCallHour && ajaxCallHour.abort();
        ajaxCallHour = j.ajax({
          type: "GET",
          url: "getchartdata?graphName=" + selected +"&subgroup=hour",
          cache: false,
          success: function(jsonData){
              var data = eval(jsonData);
              drawChart(data, data[0][0], data[0][1]);
          }
        })
    });
    }

However, the issue of sending old ajax requests still persists.

Answer №1

Check out this solution: How to Cancel Ajax Requests using jQuery

To prevent multiple Ajax requests from overlapping, you can store the xhr variable outside of your everyTime function and abort it before sending a new request.

var xhr;

j("#hour").everyTime(10000,function(i){
    xhr && xhr.abort();
    xhr = j.ajax();
});

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

Display a dropdown list using ng-repeat to prevent selecting the same value multiple times

Within my ng-repeat loop, I have a drop-down menu and an add button that allows users to add new drop-down menus to the list. However, I am looking for a way to restrict the second drop-down menu from selecting the same value as the first one. In other wor ...

Securely encoding information with PHP and decrypting it using JavaScript

I'm currently working with 2 servers. My goal is to generate a pair of keys, store the private key in local storage, and send the public key to my PHP server. The main objective is to encrypt data using the public key in PHP and decrypt it using Jav ...

Cloned bootstrap nav tabs are controlled just like the original version

I have a unique scenario where I need to generate a series of "cards" with tabs on top (each card having tabs). To accomplish this, my plan was to use a template element that I can clone and then populate. Everything seems to work fine, except for the tabs ...

Obtaining an output from a function during an asynchronous Ajax request using the `then` method

Just started exploring these new techniques. Defining an async ajax request like this: async function makeAjaxRequest(email) { let response; try { response = await jQuery.ajax({ url: ajaxurl, type: 'POST' ...

Struggling with dragging Vue.js modals?

I am currently utilizing the vue-js-modal library, and I'm encountering an issue with it. Whenever I set my modal to be draggable by using :draggable="true", I can drag it around but then I am unable to input any text in the form fields. It seems to c ...

I am looking to have the first option in the dropdown menu appear as a placeholder text

In my form, I have two phone number fields - one for mobile phone and the other for home phone. I need to make only one of them mandatory. Can someone please advise me on how to accomplish this? ...

Concealing specific HTML elements with ng-view in AngularJS

I recently started a project in AngularJS and I'm utilizing ng-view with $routeProvider for templating. However, I've encountered a minor issue where I don't want the navbar to display on specific pages like the landing, login, and registrat ...

Inject the value of a JavaScript array into an HTML element

Is it feasible to transfer a global javascript array value to an HTML tag, particularly within an img (title) tag? I'm curious if the following is achievable: <img src="_info.gif" height="26" width="37" title=myArray[5]/> If it is possible, p ...

Neglecting specific packages in package-lock.json

Currently facing a perplexing dilemma with no clear solution in sight. In our ongoing project, we rely on npm for package management. Although we haven't been utilizing package-lock.json file lately, the need to reintroduce it has emerged. The issue ...

Fixed-bottom footer in Bootstrap 5 that overlays content

Having trouble creating a fixed footer using the fixed-bottom class in react & bootstrap. The issue is that it's covering some content and I've tried various solutions without success. Any suggestions on how to fix this? (Code and Demo provided b ...

Enhance Your Website with Interactive Tooltips Using Twitter Bootstrap

In Twitter bootstrap, the default trigger for tooltips is hover. If I want to make the tooltip display on focus instead, I can add data-trigger="focus". But how do I make it so the tooltip displays both on hover and on focus? ...

Is there a way to send a variable to PHP and execute it on the current page?

I need to integrate an inventory search feature on a local clothing store's website. The challenge lies in setting up the PHP script that pulls and organizes the data to run on the same page as the search form itself. Given my limited experience with ...

Utilizing Vue: Attaching click event to dynamically added elements

I am working on a Vue application that retrieves HTML content from an API. This HTML contains blocks with the class <div class="play-video">...</div> Using axios to call the API and a promise, I insert the content into the DOM like this: < ...

Utilize Jquery Loop to Showcase JSONP Array

I've gone through a multitude of similar questions, attempted to implement the solutions provided but still can't quite seem to make it work. I'm pretty sure it's just a simple mistake since I'm new to this. I have removed the URL ...

Arranging items in Angular based on selection from the database

i have data in table: Id, word, score , score_list. score are 0.4, 0.2, -0.5, 0, -0.3 .... in score_list i have positive, negative , neutral. How can i sort data with select by score_list? This is html <select class="form-control"> <option> ...

Once the GeoJson data is loaded with map.data.loadGeoJson, the circle events are obscured by the polygons from the

When I use map.data.loadGeoJson() to load a Geo Json file, the markers and circles on my map are being covered by polygons and their events cannot be clicked. Below are some sample codes for reference. How can this issue be resolved? Is there another way ...

Sending a string data from client to a MongoDB database using Express.js and Node.js with the help of Sails framework

Need help with sending a string from client to mongoDB using Sails The "val" variable represents a string sent in real time from the client to the server database POST Form( is using HTML the best approach here? ) <!DOCTYPE html> <html> < ...

Nuxt.js is throwing a TypeError because it is unable to access the 'minify' property since it is undefined

When I try to generate a Nuxt app using "npm run generate" or "npm run build", I encounter an issue where it throws a TypeError: Cannot read property 'minify' of undefined. Does anyone know how to solve this? TypeError: Cannot read property &apo ...

Experiencing difficulties when trying to pan and zoom the data obtained from d3.json within a line chart

I am currently working on developing a trend component that can zoom and pan into data fetched using d3.json. Here is the code I have written so far: <script> var margin = { top: 20, right: 80, bottom: 20, left: 50 }, width = $("#trendc ...

Stop YouTube Video in SlickJS Carousel, Remove Placeholder Image Forever

Feel free to check out the CodePen example: http://codepen.io/frankDraws/pen/RWgBBw Overview: This CodePen features an ad with a video carousel that utilizes SlickJS. There are a total of 3 YouTube videos included in the carousel, with the SlickJS ' ...