0

If loop runs two times it shows alert in success function two times. I have tried with writing a condition inside this success function but that also doesn't work. What needs to be done, so that I get only one alert...

for(var k=0;k<array.length;k++)
{

$.ajax({
        url: parts[0]+"_api/web/lists/GetByTitle('Certifications')/Items",
        type: "POST",
        data:  JSON.stringify({ '__metadata': { 'type': 'SP.Data.CertificationsListItem' }, 
  '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("Items Inserted!"); 
        },
        error: function() {alert("Failed to Insert Items!");}
});
}
  • are you trying insert multiple items or single item? – Atish Dipongkor - MVP Nov 15 '15 at 9:41
  • multiple items.. – KumarV Nov 15 '15 at 12:22
  • So why do you need to show the alert only once? Are you trying to show the alert when all items will be inserted? – Atish Dipongkor - MVP Nov 15 '15 at 12:23
  • yes, wen all items are inserted – KumarV Nov 15 '15 at 12:24
  • total items are equal to array.length? – Atish Dipongkor - MVP Nov 15 '15 at 12:29
2

This is simple logic which can be achieved in several ways and I think you might have that logic but you would have confused of that Asynchronous call. but anyways here is another logic to it.

first store the length of array in variable

var arrayLength=(array.length-1);

for(var k=0; k < array.length; k++ ) {

$.ajax({

        url: parts[0]+"_api/web/lists/GetByTitle('Certifications')/Items",

        type: "POST",

        data:  JSON.stringify({ '__metadata': { 'type': 'SP.Data.CertificationsListItem' },  '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) {if(k == arrayLength){
    alert("Items Inserted!"); }
        },

        error: function() {alert("Failed to Insert Items!");}});}

All the best,

Happy Coding

2

Based on the comment, you said that you need to show the alert only once when all items will be inserted. I am assuming that your total items are equal to array.length. Try following

var numberOfItemInserted = 0;

for (var k = 0; k < array.length; k++) {

    $.ajax({
        url: parts[0] + "_api/web/lists/GetByTitle('Certifications')/Items",
        type: "POST",
        data: JSON.stringify({
            '__metadata': {
                'type': 'SP.Data.CertificationsListItem'
            },
            '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) {

            numberOfItemInserted++;

            if (numberOfItemInserted == array.length) {
                alert("Items Inserted!");
            }

        },
        error: function() {
            alert("Failed to Insert Items!");
        }
    });
}

But for this requirement, you can use $.when. doneCallback will be fired automatically once all items are inserted. So you can try it in the following way.

Define a separate function for adding new item

function addNewItem(data, url) {
    var deferred = $.Deferred();
    $.ajax({
        url: url,
        type: "POST",
        data: data,
        headers: {
            "accept": "application/json;odata=verbose",
            "content-type": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function(d) {
            deferred.resolve(d);
        },
        error: function(err) {
            deferred.reject(err);
        }
    });
    return deferred.promise();
}

Now declare an array to store all promises

var addNewItemPromises = [];

Now push all promises in the above array

array.forEach(function(item) {
    addNewItemPromises.push(addNewItem(someData, "some url"));
});

Finally resolve all promises

$.when.apply(null, addNewItemPromises).done(function() {
    // this function will be fired once all items are added. call alert here.
    alert("Items Inserted!");
});
1

It's the logic issue. I have edited for code you, Hope it may be help you

var showAlert = 0;
for(var k=0;k<array.length;k++)
{

$.ajax({
        url: parts[0]+"_api/web/lists/GetByTitle('Certifications')/Items",
        type: "POST",
        data:  JSON.stringify({ '__metadata': { 'type': 'SP.Data.CertificationsListItem' }, 
  '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) {showAlert = 1},
        error: function() {alert("Failed to Insert Items!");}
});
}
if(showAlert == 1) alert("Items Inserted!");

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.