Jorge Vega Sánchez
Jorge Vega Sánchez

Reputation: 7590

Execute javascript function after Struts action do some calcul

I want to explain cause the title could be not so clear. We have a jsp form with a submit button which call an action. In this active we go to a service which executes some methods to do some calculus. One of this calculus (value above or under a threshold) must change/execute a javascript function. In other words, after the action calculus in need to be able to execute a javascript function in the same jsp page.

What i've done without success :

I create a hidden property in JSP and 2 conditionals for true or false states. False state is given by default (in the Form in Java) to the property and works fine. But when i change the value of the property in the form nothing change in JSP and the property still have a false value. We can't go to another page, we stay at the same jsp page.

JSP is not evaluating in real time the value of this property ?

Any other option to communicate between action and jsp ?

JSP property

<nested:hidden property="quitProgressBar"></nested:hidden>
            <nested:equal value="true" property="quitProgressBar">
                <script>
            alert('Prueba JVE');
      </script>
            </nested:equal>
            <nested:equal value="false" property="quitProgressBar">
                <script>
        alert('Recien cargado');
      </script>
            </nested:equal>

Upvotes: 1

Views: 2114

Answers (1)

IlGala
IlGala

Reputation: 3419

You can try by calling the Struts2 action via Ajax. For example:

FORM

<form id="myForm">
    <input id="param1" name="param1" type="text" />
    <input id="param2" name="param2" type="text" />

    <button type="submit">Submit</submit>
</form>

JQUERY

$(document).ready(function() {
    $('#myForm').submit(function() {
        var param1 = $(this).find('#param1');
        var param2 = $(this).find('#param2');

        $.ajax({
          url: '/route/to/action',
          type: 'POST',
          data: {
            'param1': param1, /* setParam1(String param1) required!*/
            'param2': param2, /* setParam2(String param2) required!*/
          },
          dataType: 'json',
          complete: function (jqXHR, textStatus) {
              // DO SOMETHING
          },
          success: function (response) {
              // DO SOMETHING
          },
          error: function (jqXhr, textStatus, errorThrown) {
              console.log(jqXhr);
              console.log(textStatus);
              console.log(errorThrown);
              // DO SOMETHING
          }
        });
    });
});

In the Struts2 controller do all the computations you need and the action return type must be JSON (have a look here Strtus2 json plugin. Ajax magics!

Upvotes: 2

Related Questions