Hello everyone,
I am working on making Ajax calls from a Panel/JavaScript component. This
component is entirely written in Typescript and uses a canvas element. The
only HTML elements within the Panel are <div><canvas></canvas></div> to
render the canvas.
I would like to retrieve some information from the server when the
JavaScript component initializes. I was thinking of using Wicket.Ajax.get
for this. Throughout the lifecycle of the JavaScript component, additional
Ajax calls will be needed.
On the server side, I believe I need to use an AbstractDefaultAjaxBehavior.
I want to use GET for retrieving data and POST with a JSON body for sending
data.
Here’s my current implementation in the Panel:
ajaxBehavior = new AbstractDefaultAjaxBehavior() {
@Override
protected void respond(AjaxRequestTarget target) {
final StringValue requestValue =
getRequest().getRequestParameters().getParameterValue("request");
if (requestValue.isEmpty() &&
ajaxDispatchers.containsKey(requestValue.toString())) {
final String request = requestValue.toString();
ajaxDispatchers.get(request).execute();
getRequestCycle().scheduleRequestHandlerAfterCurrent(new
TextRequestHandler("application/json", "UTF-8",
jsonService.toJson(Action.builder().action("translations").build())));
}
}
};
add(ajaxBehavior);
Here is the code for the first Ajax call (TypeScript):
Wicket.Ajax.get({
u: ajaxCallbackUrl,
c: componentId,
ep: {'request':'translations'},
dt: 'json',
sh: function (attributes: any) {
console.log("AJAX callback success:", attributes);
},
fh: function (attributes: any) {
console.error("AJAX callback failure:", attributes);
}
});
The call is made to the server, but the JSON response is not parsed
correctly, and I get the following error in the browser console:
Wicket.Ajax.Call.failure: Error while parsing response: SyntaxError:
Unexpected token '<', "<?xml vers" is not valid JSON
Indeed, the server response is and it's not the JSON I'm sending with my
panel:
<?xml version="1.0" encoding="UTF-8"?><ajax-response></ajax-response>
Where did I go wrong?
Thank you for your help!
Regards,
Stef