Askar Ibragimov Askar Ibragimov - 3 months ago 21
Javascript Question

ASP.NET: how to commit postback only after client ajax is complete

I have a button encoded as such:

<asp:Button ID="save_all_filt" runat="server" Text="All data for filtered subjects"
ClientIDMode="Static" OnClientClick="a= saveAllFilt(); return a; "
OnClick="save_all_filt_Click" />


saveAllFilt is a function that invokes usual JQuery ajax call. Something like this:

function saveAllFilt() {
jQuery.ajax({
async: false,
dataType: 'json',
contentType: "application/json; charset=utf-8",
type: "POST",
url: contentURL,
data: dataarray,
success: function (msg) {
// Some processing here. ONLY WHEN IT IS DONE, I NEED TO HAVE POSTBACK.
},
error: function (data) {

}
}); // end of ajax call.


}

I want such a thing: the onClick should proceed only after ajax call is complete. How I can do that?

Answer

You can remove the OnClick attribute from the button and return false in the OnClientClick attribute like:

<asp:Button ID="save_all_filt" runat="server" Text="All data for filtered subjects"
            ClientIDMode="Static" OnClientClick="saveAllFilt(); return false;" />

and set a hidden button with that OnClick attribute like:

<asp:Button ID="hdnButton" runat="server" Text="" Visible="False" 
            ClientIDMode="Static" OnClick="save_all_filt_Click" />

and in the success method of your ajax call click that button like:

success: function (msg) {
    // Some processing here. ONLY WHEN IT IS DONE, I NEED TO HAVE POSTBACK.
    $('#hdnButton').click();
},