What steps can I take to give priority to a particular ajax call?

Every 10 seconds, two ajax based methods are executed. However, when I submit the form for processing, it waits for the previous ajax calls to complete before processing. I want to prioritize the form submission.

Below is the script that I am using:

function refresh_ss_one(){
    $.ajax({
       type: 'GET',
       url: "{{ route('RefreshSessionOne') }}",
       data: {}, 
       success: function(response){ 
        console.log(response);
       }
    });
}
function refresh_ss_two(){
    $.ajax({
       type: 'GET',
       url: "{{ route('RefreshSessionTwo') }}",
       data: {}, 
       success: function(response){ 
        console.log(response);
       }
    });
}
setInterval(refresh_ss_one, 10000);
setInterval(refresh_ss_two, 10000);

I have another method that should run on form submission event and needs to be prioritized. Despite using the async parameter in my ajax function, the issue persists.

$("#check-rate").submit(function(e) {
    var form_data = $(this);
    $.ajax({
           type: 'POST',
           url: currency_route,
           data: form_data.serialize(), 
           success: function(response)
           {
              ...
           }
         });
    e.preventDefault(); 
});

I am looking for guidance on how to resolve this issue...

Answer №1

To achieve a more contemporary solution, consider utilizing a promise:

var promise1 = new Promise(function(resolve, reject) {
   //perform first ajax call here
});

promise1.then((value) => {
//execute second ajax call here
});

For further information on promises, refer to the official documentation.

The promise functionality guarantees that your code will first run the initial ajax call (upon resolving successfully), before proceeding to the subsequent one.

Additionally, you have the flexibility to include multiple promises based on your requirements.

Answer №2

Here is one way to approach it:

<script>
// Here is an example of how you can write your ajax function
$.ajax({
    type: 'GET',
    url: "{{ route('RefreshSessionOne') }}",
    data: {},
    async: false,
    success: function(response) {
        console.log(response);
    }
});

// Make sure to complete this request before moving on to other codes.

$.ajax({
    type: 'GET',
    url: "{{ route('RefreshSessionTwo') }}",
    data: {},
    success: function(response) {
        console.log(response);
    }
});

// This code will be executed after the previous async:false request has completed.

By default, in jQuery, the $.ajax request is asynchronous with the variable name "async" set to true.

You also have the option to call the second function within the success part of the first function.

Answer №3

To seamlessly receive responses in sequence from a list of GET / POST requests, here’s a clever jQuery Deferreds solution for you.

const $ajaxSeq = arr => $.when.apply($, arr.map(data => $.ajax(data))).then(function(_res){ 
     return Array.isArray(_res) ? [].map.call(arguments, res => res[0]) : [_res];
  });

Usage example:

$ajaxSeq([
    {type:'POST', url:'some_url_here', data: {content: "Hello world"}},
    {type:'GET',  url:'some_url_here'},
    {type:'GET',  url:'some_url_here'},
]).then( res => {
    // Upon all requests being fulfilled
    // access the responses sequentially:
    console.log(res[0])
    console.log(res[1])
    console.log(res[2])
});

Answer №4

When AJAX calls are made, they adhere to their name by executing requests asynchronously. This means that one request does not pause to wait for another to finish. As mentioned by @jayoti above, you have the option to make the calls synchronous with async:false. However, it's advisable to create a single method that triggers both methods and then call the second method upon receiving a response.

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

Post the information from a webpage onto your Instagram story

I'm currently developing a web application that generates text content, with future plans to include images as well. I want to integrate a share button that allows users to easily add this generated content to their Instagram story. The intended flow ...

regenerate access credentials using extjs

Utilizing extjs Ext.Ajax.request for making REST API calls in my application. Implementation of oauth authentication is used with the REST APIs. I am seeking a way to automatically refresh the token if it expires during an ext.ajax.request call, allowing ...

What is the method for creating a JavaScript array that closely resembles the provided example?

My task is to create an addRows method using specific data structure as shown below. data.addRows([ ['UK', 10700,100], ['USA', -15400,1] ]); However, the data I have available is in a different format. How can I transform ...

Looping Feature in Ionic Framework's Slides Component

Currently, I am working on developing an application using Ionic-Angular. When it comes to incorporating slides in my app, I opted for the ionic 4 ion-slides component. Everything was going smoothly until I wanted to enable looping for the slides so that u ...

Discovering the art of line breaks

Imagine I have a random block of text displayed in a single line, like this: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Due to various reasons such as width settings or text-zoom, the text may display as two or more lines on the viewer&apos ...

Differences Between Android and JavaScript: Ensuring Library Validity

Validation in JS is provided by the validator library which can be found at https://www.npmjs.com/package/validator Is there an equivalent library for validation in Android? If so, what is the name of Android's library? ...

React is having trouble loading the page and is displaying the message "Please enable JavaScript to use this application."

Following a tutorial at https://learn.microsoft.com/en-us/learn/modules/build-web-api-minimal-spa/5-exercise-create-api Everything was going smoothly until I reached this step: Add the following proxy entry to package.json: "proxy": "http:/ ...

Receiving a blank array upon calling res.json() in Node.js script

I'm facing an issue with my code snippet that displays all posts, including the username and display picture of each user. Everything seems to be working fine as the log output is perfect. However, I'm struggling to return this data as a JSON obj ...

The sequencing of operations in Node.js streams

I am having an issue with validating an image before saving it to disk. Currently, I am utilizing the GM library. // Express application implementation app.post('/image', function(req, res) { var stream = gm(req) .size({ bufferStr ...

Convert a JSON array into a JavaScript array?

Similar Question: How can I extract property values from a JavaScript object into an array? I am receiving a JSON array from a basic server and need to parse it into JavaScript for use in my web application. What is the best way to convert a JSONP ar ...

What could possibly be causing this element to shift side to side (in IE only) during the CSS animation?

UPDATE: Issue occurring on Internet Explorer 10, Windows 7 When using the transform property to adjust the horizontal position of an element during animation, the vertical value is updated as well. However, despite setting the horizontal value to the same ...

An error occurred while trying to initialize the ui.bootstrap.demo module in AngularJS

Currently, I am in the process of learning angularjs and have encountered a roadblock. An error keeps popping up: ncaught Error: [$injector:modulerr] Failed to instantiate module ui.bootstrap.demo due to: Error: [$injector:nomod] Module 'ui.bootstr ...

When you reach a scrolling distance of over 300 vertical heights,

Is it possible to show and hide a class based on viewport height? I am familiar with displaying and hiding a class after a specified pixel height, but I'm wondering if it's achievable using viewport height instead? Specifically 3 times the viewp ...

Unable to reach controller action with Ajax request

I've been encountering issues trying to make a Get request to hit the specified URL. Initially, I attempted inputting the URL parameter manually in a separate JS file, then transitioning all my JS to cshtml to test out Razor. However, I am still facin ...

Ways to extract the content from the textarea

Currently, I am working on a project that involves using CKEditor. Within the project, there is a panel with various properties used to create a tooltip. I decided to utilize CKEditor to insert content into the tooltip because it provides an excellent user ...

Sequelize does not automatically include a junction table in the associated model data

Imagine having two models, User and Event, established in a many-to-many relationship with User.belongsToMany(Event) and Event.belongsToMany(User). Everything seems to be functioning properly until executing User.findAndCountAll({include: [{model: Event}]} ...

Utilize jQuery ajax to pull in data from an external website

I've been doing some research on using jQuery ajax to extract links from an external website, but I'm a bit lost on where to begin. I'm taking on this challenge just to push my skills and see what I can accomplish. While reading about the S ...

Unforeseen SyntaxError: Unexpected symbol detected

Encountering an issue while attempting to send raw data as parameters in express. Specifically, there is an error occurring at the 'fields' variable... function getWithQuery(req,res){ console.log(req.params); var query = {name: new RegEx ...

Looking for assistance with an Angular2 post request?

I'm having an issue with a post request to obtain a token granting access to another access token. Each time I attempt to make the post request, I encounter an error stating that the access_token property is trying to read something undefined. It seem ...

Order a portion of a JSON array according to another part of the same array

Having a json array that needs sorting in JavaScript. The EventName field should match the respective Age fields like 01-10 Days and 10-20 Days. [ {Age: "01-10 Days", EventName: "Invoice AP Review", Value: 1, ActiveInvoices: []} ,{Age: "01-10 Days", Even ...