0

Environment SP 2010

I am creating Visual Webpart. And on btnAdd button click adding a row with 5 controls in it using js. On button Save click I am saving those 5 fields to a SharePoint list. I can have any no of such rows available. I am storing ItemID's of those to a hidden control to read it at server side.

The problem here is after this async ajax calls I am calling serverclick method. By the time these controls gets lost on postback.

How can I track if all ajax calls are successfully executed, So I can call code behind event?

  function createListItem(webUrl, listName, itemProperties, index, success, failure) {

    $.ajax({
        url: webUrl + "/_vti_bin/listdata.svc/" + listName,
        type: "POST",
        processData: false,
        contentType: "application/json;odata=verbose",
        data: JSON.stringify(itemProperties),
        headers: {
            "Accept": "application/json;odata=verbose"
        },
        success: function (data) {
            success(data.d);
            document.getElementById('<%=hdnComponentIDs.ClientID%>').value += data.d.Id + ",";
            componentCounter++;
        },
        error: function (data) {
            failure(data.responseJSON.error);
        }
    });
}

call to the above method :

createListItem(siteUrl, 'CAPEXObjective', alldata, index,
               function (data) {
                        componentCounter++;
                        console.log("Component Created");
               },
               function (error) {
                       console.log(JSON.stringify(error));
                        }
               );
1

You have to use JQuery Deferred & Promise methods. Basically your AJAX call will return a promise and you can call our server button click event after the deffered action is resolved. See this api documentation and read this good post about the same.

    /* ajax calls returns promise by default*/
    function doAjaxCall(){
            return $.ajax({/*your ajax call configuration here */});
    }

     //in you main code 
      doAjaxCall().then(function(data){
                        //success handler 
                 }).fail(function(error){
                     //fail handler
                 });
3

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.