Search code examples
ajaxwicket

Call several different JavaScript within AjaxLink one after the other


When I click on an AjaxLink, I would like to have a validation via JavaScript on the client side first (because the LocalStorage is queried) and then depending on the result, further JavaScript calls are made. How can i achieve this? In a pseudo code it would look like this:

new AjaxLink<>("myId", myModel) {

    @Override
    public void onClick(AjaxRequestTarget target) {
        boolean isCounterValid = target.appendJavaScript(checkCounter()); // i know that this is not possible, therefore pseudo code
        if(isCounterValid) {
            target.appendJavaScript(someOtherJavaScript());
        }
        else {
            target.appendJavaScript(anotherJavaScript());
        }
    }

    private String checkCounter() {
        return "var count = window.localStorage.getItem('myCounter'); return count !== 1;";
    }

    private String someOtherJavaScript() {
        return "change something";
    }

    private String anotherJavaScript() {
        return "change other thing";
    }
};

Solution

  • You need to send extra request parameters with the Ajax call when the link is clicked. For that you should override updateAjaxAttributes(AjaxRequestAttributes attributes) method of AjaxLink:

    @Override
    protected void updateAjaxAttributes(AjaxRequestAttributes attributes)
    {
       attributes.getDynamicExtraParameters().add("var count = window.localStorage.getItem('myCounter'); return [{\"name\":\"count\", \"value\": count}]");
    }
    

    This way inside AjaxLink#onClick() you can read the count via:

    int count = getRequest().getRequestParameters().getParameterValue("count").toInt();