skip to Main Content

I’m new here.

$.each(a, function (i, obj) {
    $('#labelid').html("inserting this data: "+obj.somedata);
    // some other code

    $.ajax({
        // ajax request with insert
    });
});

I have an each loop and inside of it is an ajax request that will just insert some data, along with some other code mostly for changing a sort of “status” label (“inserting this: (some data)”).

My problem is when the loop executes, the code inside it except the ajax request iterates all the way to the end, showing in my label something like “inserting this: (last element row)” while the ajax request is still running in the background.

I want to achieve something like this:
1. Label shows “inserting 1st set of data”
2. ajax request inserts 1st set of data
3. Label shows “inserting 2nd set of data”
4. ajax request inserts 2nd set of data

Is this possible? I don’t want to use async: false.

Thanks

4

Answers


  1. Because, Ajax Requests are asynchronous, So Your loop will not wait for its response and immediately move to next one. To perform Ajax as Synchronous You need to add following option.

    $.ajax({
        async: false,
        // your other options
    })
    
    
    Login or Signup to reply.
  2. A for loop will not work in this case because the requests are async. You have 2 options.

    1. If you want to use a for loop set async to false in $.ajax
    2. Take a recursive approach i.e. send the next request only when the response
      of a request arrives. This can be done by creating a recursive function.
    Login or Signup to reply.
  3. Here is little promise wrapper over jQuery Ajax. I think it’ll work with $.each.

    const _ajaxAsync = url => new Promise((accept, reject) => $.ajax({
        url: url,
        type: "POST",
        success: data => accept(data),
        error: (request, status, error) => reject({ request, status, error })
    }));
    
    $.each(a, async function (i, obj) {
        $('#labelid').html("inserting this data: " + obj.somedata);
        // some other code
    
        let res = await _ajaxAsync('https://example.com').catch(e => console.log(e));
        console.log(res);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    Login or Signup to reply.
  4. Wrap your ajax request inside a promise and use await to call the promise, hence the execution of code wait for the promise to return response of ajax request and you can set the label in the required format.

    const response = await new Promise((accept, reject) => $.ajax({
      url: url,
      type: "POST",
      success: data => accept(data),
      error: (request, status, error) => reject({ request, status, error })
    }));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search