You’ve read the previous post about the basics of ajax requests in Wicket, but you’re stubborn and still want to write some JavaScript. You also want the ability to execute your Wicket page code from JavaScript, which is actually very useful. Well this is the article for you!
I can think of lots of reasons why you would want to do this:
- Having a sortable list of items, and persist the changes upon changing the sort order.
- Doing periodic polling using setTimeout.
- Reduce the number of ajax wicket components and behaviors.
- You might just want more control over your client-side code and/or using frameworks that are client-side centric such as Reactjs.
Creating a callback URL
The first step to accomplish this is to create a Wicket behavior which will render it’s callback URL to the page it’s added to. The callback URL is what our JavaScript will use to interact with the behavior.
add(new AbstractDefaultAjaxBehavior() {
private static final long serialVersionUID = 1L;
protected void respond(final AjaxRequestTarget target) {
//TODO handle the call from JS
}
@Override
public void renderHead(Component component, IHeaderResponse response){
super.renderHead(component, response);
String callbackUrl = getCallbackUrl().toString();
response.render(JavaScriptHeaderItem.forScript("our_callback_url = '" + callbackUrl + "';", "our_callback_url"));
}
});
When we add this to our WebPage and look at the source code, we will see in the <head> section a JS variable called ‘our_callback_url’ which provides the URL our JS can use to interact with this specific behavior and for this specific page.
Sending a request from Javascript
The second step is to write the JS code that will send a request to our_callback_url. We utilize helper functions provided by Wicket that are analogous to using jQuery.ajax(). In this example we will make the call inside of a button click handler:
<script type="text/javascript">
$('#doCall').click(function() {
Wicket.Ajax.get({ u: our_callback_url });
});
</script>
<a href="#" id="doCall">Do Call</a>
The above code is the equivalent of using jQuery.ajax(). The difference is we define the success handler inside of the respond() method of our behavior as opposed to using the success callback in jQuery.ajax().
Passing additional data
We can also pass additional data with our requests by using the “ep” parameter:
$('#doCall').click(function() {
Wicket.Ajax.get({
u: our_callback_url,
ep: {'data1': "abc", 'data2': "gregregre"}
});
});
We can than retrieve the values of ‘data1’ and ‘data2’ in our behavior’s respond() method as follow:
protected void respond(final AjaxRequestTarget target) {
StringValue data1 = getRequest().getRequestParameters().getParameterValue("data1");
StringValue data2 = getRequest().getRequestParameters().getParameterValue("data2");
}