Your achievements

Level 1

0% to

Level 2

Tip /
Sign in

Sign in to Community

to gain points, level up, and earn exciting badges like the new
Bedrock Mission!

Learn more

View all

Sign in to view all badges

SOLVED

Return Ajax Response to HTL

Avatar

Level 2

Hello Guys,

 

I am binding a click action from HTL in a script which does an ajax call to a third party server, and it returns a JSON response. I need to call this script from HTL and use JSON to frame the HTML. Can anybody please help in this?

 

Thanks

Divya

1 Accepted Solution

Avatar

Correct answer by
Employee

It might sound obvious, but can you please confirm:
1. Ajax call is being triggered, residing inside callServlet.js?
2. If the servlet is returning 200 response, in json format?

 

A screen shot would really help

View solution in original post

5 Replies

Avatar

Employee

@divyak96999766 
Please see if below snippet of code helps:

 

Call Ajax from HTL
<sly data-sly use.jsondata='callServlet.js'/>

 

Pass the response to the model
<sly data-sly-use.slingPOJO="${'com.aem.SlingPOJO' @jsondata=jsondata}"/>


callServlet.js:

use(function() {
var resp;

var url="/bin/path";

$.ajax({url, success: function(response){
resp = response;
}});
return resp;
}
SlingPOJO.java

@Model(adaptables = SlingHttpServletRequest.class, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class SlingPOJO{

@Inject
private String jsondata;
}

Avatar

Level 2

js value is not returned to the sling model, using the below syntax.
<sly data-sly use.jsondata='callServlet.js'/>

Avatar

Correct answer by
Employee

It might sound obvious, but can you please confirm:
1. Ajax call is being triggered, residing inside callServlet.js?
2. If the servlet is returning 200 response, in json format?

 

A screen shot would really help

Avatar

Employee Advisor

HTL does not have "click actions"; it's rather that the markup generated by HTL is rendered in the browser, and then the browser will execute the action you specified.

I don't think that this is specific to AEM or HTL, as long as you create the correct markup and provide the correct Javascript on the frontend to execute that backend request and consume the JSON in the browser. (I am not a frontend developer so I cannot provide you further links here, sorry.)

Avatar

Community Advisor

Hi @divyak96999766 ,

We can use javascript use api  as mentioned here - Day 08: Dueling with JavaScript Use API (redquark.org)

We can have a js servlet call on click to fetch the json. In the use api js "use function" we can use the response from servlet call, set the return object to the json. "text in this example. In htl we can print whatever is required

Probably same is meant in the previous response from @krati_garg, and looking to see if we may not need java api?