How to return Javascript as partial response?

javascript, jsf-2

Solution

writer.write("alert(’Works!’);");

Curly quotes are not a valid string delimiter in JS. Use straight quotes.

writer.write("alert('Works!');");

Unrelated to the concrete problem, based on your question history you're using PrimeFaces, or at least familiar with it. In that case, just use `RequestContext#execute()` instead of this mess.

Problem

As response to an Ajax-request I want to return Javascript that is executed on the client immediately. I tried it like this but it doesn't work: ``` <html xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html"> <h:head></h:head> <h:body> <h:form> <h:commandButton value="js"> <f:ajax event="click" listener="#{myBean.js}"/> </h:commandButton> </h:form> </h:body> </html> ``` the bean: ``` package mypackage; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.faces.context.PartialResponseWriter; import javax.inject.Named; @Named public class MyBean { public void js() { System.out.println("called"); FacesContext ctx = FacesContext.getCurrentInstance(); ExternalContext extContext = ctx.getExternalContext(); if (ctx.getPartialViewContext().isAjaxRequest()) { try { extContext.setResponseContentType("text/xml"); extContext.addResponseHeader("Cache - Control ", "no - cache"); PartialResponseWriter writer = ctx.getPartialViewContext() .getPartialResponseWriter(); writer.startDocument(); writer.startEval(); writer.write("alert(’Works!’);"); writer.endEval(); writer.endDocument(); writer.flush(); ctx.responseComplete(); } catch (Exception e) { System.out.println(e); } } } } ```

Original source