0

I have a "Save" button that I need to trigger when the user clicks Next/Previous buttons on my page. When the user clicks next to move onto another window I trigger a "save" button that saves the changed the user had mad and some other functionality. The problem is when I click the next or previous button the save button is triggered but needs time to save the changes and the code keeps on executing. Is there a way I can tell whether the save has finished or delay my code somehow? I know I can do a time delay but it could be different for every user and inefficient. Here is an example:

function prev_next(){
     $('#save').trigger('click');     //This line could take 2-5 seconds to finish
     //Other code here that opens next window
}

Any advice will be appreciated.

Stivan
  • 1,128
  • 1
  • 15
  • 24
  • check this: http://stackoverflow.com/questions/5000415/call-a-function-after-previous-function-is-complete – Oscar LT Apr 01 '16 at 12:43
  • Instead of faking a click, call the underlying logic that is invoked by the click. That is presumably asynchronous, so you can do your "other code" by hanging a promise off it, or doing it in the callback. –  Apr 01 '16 at 12:45

1 Answers1

0

You will have to edit the function that gets triggered by clicking the save button, to allow for a callback function. (I assume there is an ajax request that is sent to some server to save).

Example:

Save function:

function saveEdits(callback){
    $.ajax({
        url: 'urltosavepage.php',
        method: 'post',
        data: {
            somevar: 'somevalue'
        },
        success: function(response)
        {
            callback();
        }
    });
}

prev_next function:

function prev_next()
{
    saveEdits(function(){
        // Code that is here will not get executed until after the ajax request is completed, and the success function gets called.
        //Other code here that opens next window
    });
}
lshas
  • 1,691
  • 1
  • 19
  • 39