Search code examples
jqueryaemsling

How to read data from Sling to Jquery?


As part of AEM UI development I have written one Sling Servlet and Jquery. I need to trigger Servlet use Jquery and Read data from Servlet to Jquery? any Help?

My Jquery:

window.location.href = Granite.HTTP.externalize("/bin/dam/TimelineVersion"); 

var val=""; // Here I need to Read String Data from Servlet
alert(val);

My Sling Servlet:

@SlingServlet(paths="/bin/dam/TimelineVersion", methods = "GET", metatype=true)
@Properties({
        @Property(name = "service.pid", value = "com.hpe.dam.author.support.servlet.TimelineVersion", propertyPrivate = false),
        @Property(name = "service.vendor", value = "HPE", propertyPrivate = false) })
public class TimelineVersion extends SlingSafeMethodsServlet{

    @Reference
    private SlingRepository repository;

    public void bindRepository(SlingRepository repository) {
        this.repository = repository; 
    }

    @Override
    protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {

        try {
            String Data="This value i have to get in Jquery";
        } catch (Exception e) {
        }
    }
}

Solution

  • You need to refactor your servlet to actually write out the response (I recommend you send JSON to the browser):

    @SlingServlet(paths="/bin/dam/TimelineVersion", methods = "GET", metatype=true)
    @Properties({
            @Property(name = "service.pid", value = "com.hpe.dam.author.support.servlet.TimelineVersion", propertyPrivate = false),
            @Property(name = "service.vendor", value = "HPE", propertyPrivate = false) })
    public class TimelineVersionServlet extends SlingSafeMethodsServlet {
    
        @Reference
        private SlingRepository repository;
    
        private static Logger log = LoggerFactory.getLogger(TimelineVersionServlet.class);
    
        @Override
        protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
            try {
                String data = "This value i have to get in Jquery";
                response.getWriter().write(data);
            } catch (Exception e) {
                 log.error(e); // handle appropriately
            }
        }
    }
    

    And the following for your Javascript:

    $.get('/bin/dam/TimelineVersion')
        .success(function(data) {
            console.log(data);
        })
        .error(function() {
            console.log('[ERROR] Could not perform request');
        });
    

    Here's a working example of a Sling Servlet called using jQuery: https://github.com/mickleroy/aem-ajax-search