javascriptjqueryajaxstruts2synchronous

Call Struts 2 action from javascript synchronous


I am trying to call a Struts 2 action with JavaScript synchronous. I found several examples but none of them had been worked.

The only thing I've got work is to call the action asynchronous like this:

function toggel(id) {
    var url = "./ToggelProcess.action";
    $.post(url, {id : id}, function (resp) {
        // resp is the response from the server after the post request.
    });
}

need an example like this that work.


Solution

  • I suggest that you should never actually intend to send synchronous requests, as they prevent your JS from doing further tasks while waiting, as JS is single-threaded. Your intention of sending synchronous request makes it really probable that your intention is a result of the lack of understanding asynchronous requests or the result of bad design. Instead of $.post I humbly suggest $.ajax:

    $.ajax({
      type: 'POST',
      url: url,
      data: {id : id},
      success: function (resp) {
            // resp is the response from the server after the post request.
      },
      async:false
    });
    

    But instead of that I suggest that you should rethink your code, write separate functions for what you intend to run when the response arrives and gall those functions in the callback.