Return Ajax Response to HTL | Community
Skip to main content
divyak96999766
Level 2
October 29, 2022
Solved

Return Ajax Response to HTL

  • October 29, 2022
  • 3 replies
  • 1695 views

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

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
Best answer by krati_garg

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

3 replies

krati_garg
Adobe Employee
Adobe Employee
October 29, 2022

@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;
}

divyak96999766
Level 2
November 7, 2022

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

krati_garg
Adobe Employee
krati_gargAdobe EmployeeAccepted solution
Adobe Employee
November 7, 2022

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

joerghoh
Adobe Employee
Adobe Employee
October 29, 2022

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.)

Shubham_borole
Community Advisor
Community Advisor
October 30, 2022

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?