2

In the below code, the alert will come three times but i need it only once. I have also tried by keeping the alert outside the ajax code but then the alert is coming once but the problem is that it is coming before the ajax code is executed.

I need the alert to come once and also after for loop has completed execution.

function Insert()
{  
var ArrayVal=['A','B','C']
  for(var i=0 ; i<3 ; i++ )
    {
      $.ajax({
                url: "URL",
                type: "POST",
                data:  JSON.stringify({ '__metadata': { 'type': 'SP.Data.TeamListItem' }, 
                     'Title': ArrayVal[i]}),
                headers: { 
                    "accept": "application/json;odata=verbose",
                    "content-type":"application/json;odata=verbose",
                    "X-RequestDigest": $("#__REQUESTDIGEST").val()
                },
                success: function(d) {
                alert("Inserted");
                },
                error: function ( xhr, status, error) {
                    alert("error");
                }
        });     
    }
}

I tried one small example and it is working

var promises=[];

    $(document).ready(function(){
    $("#DelButton").click(function(){

    for (var i=1; i<5; i++){ 
            /* $.ajax returns a promise*/      
            var request=  $.ajax({
            url: "URL",
            type: "DELETE",
            headers: {
                "accept": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                "If-Match": "*"
            },
            success: function (data) {
               alert("success");
            },
            error: function (error) {
                alert(JSON.stringify(error));
            }
        });        
           promises.push( request);
    }        
     $.when.apply(null, promises).done(function(){        
           alert('All done')
      })});});

I got success alert 4 times and then once "All Done" alert as expected.

But again when I applied the same to my real code then it is not working as expected.

var promises1=[];
var promises2=[];
var promises3=[];
var request1;
var request2;
var request3;
$(document).ready(function () {  
$('#test').click(function(){   
var idCount=0;    
if(idCount!=0)      
        {       
    request3 = $.ajax({
                url:"URL",
                type: "GET",     
                headers:    {
                            "accept": "application/json;odata=verbose",
                            },
                success: function (data) {
                        for(var s=0;s<dlength;s++)
                            {
                                if(data.d.results[s].Is_x0020_Manager==true)
                                    {                                                                   managerarray[m]=data.d.results[s].Title;                                        
                                    }                   
                            }                   
for(var k=0;k<dlength;k++)
{
for(var l=0;l<managerarray.length;l++)
        {

        if(data.d.results[k].Title==managerarray[l])
        {
            managername=managerarray[l+1];
        }
        }

request2 = $.ajax({
        url: "URL",
        type: "POST",
        data:  JSON.stringify({ '__metadata': { 'type': 'SP.Data.XYZListItem' }, 
             'Title': data.d.results[k].Title}),
        headers: { 
            "accept": "application/json;odata=verbose",
            "content-type":"application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function(d) {
        alert("Inserted to teams list");
        },
        error: function ( xhr, status, error) {
        }
});   
 promises2.push( request2);
}   
                    },
                        error: function ( xhr, status, error) {
                            }
                    });         
promises3.push( request3);                                  
        }   

$.when.apply(null, promises2).done(function(){   
       alert('Promises2')
  })                
$.when.apply(null, promises3).done(function(){   
       alert('Promises3')
  })                            
})    
});

In this case again the promises alerts are coming first and them the ajax alerts are coming. Where is the mistake?

3

You need to look at promises the ajax call returns a promise you can keep them in a array and use jquery's when method to execute once all promises have been run to completion.

(Btw this is not really a SharePoint question, but a jquery or javascript question, that have been asked several times before on stackoverflow, so you can see a lot of examples there on how to solve it). E.g. https://stackoverflow.com/questions/20291366/how-to-wait-until-jquery-ajax-request-finishes-in-a-loop

  • +1, this is really what the OP needs to look into, jquery promises. – Mike Jan 23 '16 at 6:07
  • I have tried but still i see that ajax is running last – KumarV Jan 23 '16 at 7:27
2

set Ajax property

async : false

Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called. If you set async: true then that statement will begin it's execution and the next statement will be called regardless of whether the async statement has completed yet.

  • async: false is the worst practice! – Atish Dipongkor - MVP Jan 23 '16 at 11:49
  • Then what are other options @AtishDipongkor – KumarV Jan 25 '16 at 5:47
0

I have added async: false, to code and it worked

request2 = $.ajax({
        async: false,
        url: "URL",
        type: "POST",
        data:  JSON.stringify({ '__metadata': { 'type': 'SP.Data.XYZListItem' }, 
             'Title': data.d.results[k].Title}),
        headers: { 
            "accept": "application/json;odata=verbose",
            "content-type":"application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function(d) {
        alert("Inserted to teams list");
        },
        error: function ( xhr, status, error) {
        }
});   
  • async: false is the worst practice! – Atish Dipongkor - MVP Jan 23 '16 at 11:49
  • You are right Atish, but we better not educate them on recursion We need average programmers so the better programmers are valued. I only hate it when average programmers answer their own question as the correct answer, and don't search more to find a better answer – Danny '365CSI' Engelman Jan 30 '16 at 20:56
  • Danny, u seem to be a better programmer from the very first day U started programming.. – KumarV Feb 1 '16 at 7:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.