This question already has an answer here:
How to invoke a JSF managed bean on a HTML DOM event using native JavaScript?
(1 answer)
Closed 1 year ago.
I have a JSF file that needs to get populated from the data I get from the JS function that I get from Ajax call to a web-service. The latter part works like a charm. I am able to retrieve the JSON data from the ajax call. I need to parse this json data and take data and use that to populate the JSF. I am unsure as to how I would access the JS variables from the JSF/xhtml.
Is is possible to do it in someway? I was going through some DWR stuff that would send ajax post from JS to the Java bean and I could use the bean variable from the JSF. But, I want to know if there is any other way of doing this.
I would greatly appreciate any help. I am using JSF 2.x btw.
Thanks,
S.
You can use the following 'hack' to get JS to submit information to JSF.
Create an invisible JSF form with <f:ajax> hook:
<h:form prependId="false" style="display:none;">
<h:inputText id="input" value="#{bean.input}">
<f:ajax event="change" execute="#form" listener="#{bean.process}" render=":something" />
</h:inputText>
</h:form>
Let JS update the input field and trigger the change event:
<script>
function somefunction() {
var input = document.getElementById('input');
input.value = 'your JSON string';
input.onchange();
}
</script>
Do the Java/JSF job in the listener method:
private String input; // +getter +setter
public void process(AjaxBehaviourEvent event) {
doSomethingWith(input);
}
Put the desired JSF markup in a <h:someComponent id="something"> which will be re-rendered by <f:ajax render=":something"> when the listener has done its job:
<h:panelGroup id="something">
The JSON string was: <h:outputText value="${bean.input}" />
</h:panelGroup>
That said, I'd prefer to do the webservice call in the constructor or action method of the managed bean instead of in JS. Your approach is literally a roundabout.
I think this is not possible.
JSF runs on server.
JavaScript runs on client (browser).
So, JSF runs BEFORE action in JS.
Of course, you can make a servlet that will be called from JavaScript, receiving information stored in JavaScript variables. But, this will be in next step:
JSF assembles the page
JavaScript call WebService, getting JSON data
JavaScript send JSON data to server (servlet)
You could revisit the design a bit and probably accomplish what you're looking for. Rather than accessing the webservice via ajax on the client you could access it server side by communicating with it directly in an action method or a method that occurs before the view is created (prettyfaces actions handle this kind of work nicely). Then you can construct your view dynamically based on the results of the response from the web service.
I'm not 100% sure that will accomplish what you are looking for but that general idea might work for what is sounds like you're going for.
If you've already rendered a view and you want to do it with ajax you could use f:ajax with the same principle -- hit action method, communicate with webservice server side in that action method, change state of variables that determine the view layout and render the response.
Related
I am doing a POST-request using jQuery which seems to succeed. But how can I work with that on server side and modify the response?
Do I need another servlet because the Faces Servlet is just not designed to deal with this?
$.ajax({type:'POST', data:{"status":status}, success: function(response) {
alert("Qapla'");
}});
It is used for the following process:
user inputs address and hits commandButton which invokes JS
JS retrieves geodata using google maps and sends it to server (which I am considering to use the above code for)
the servers responds sending some close places from database
JS retrieves exact distances using google maps again and sends them to server
server redirects client to next page with results
There is one case where a failing validation for the used inputText might be needed: At point 2 the server rates the geodata as not valid.
If sending the ajax POST by usual JSF means (UICommand component, jsf.ajax.request(), etc, in flavor of <h:commandButton>, <p:remoteCommand>, <o:commandScript>, etc) is really not an option for some reason left unspecified in your question, then you'd indeed better create a separate servlet or even JAX-RS or JAX-WS webservice listening on those requests and returning e.g. XML, JSON, etc. JSF is a HTML form based MVC framework not a web service framework.
You only need to take into account that you deal properly with JSF view state when you manipulate the HTML representation of JSF components afterwards. E.g. when you use custom JS/ajax to enable a disabled HTML button as generated by <h:commandButton> without involving/notifying JSF, then it won't appear as enabled in JSF component state and its action would never be invoked.
See also:
How to use Servlets and Ajax?
How to generate JSON response from JSF?
How to invoke a JSF managed bean on a HTML DOM event using native JavaScript?
What is the need of JSF, when UI can be achieved from CSS, HTML, JavaScript, jQuery?
I am trying to learn Spring MVC and I wanted to get hands on in MVC. I have a simple web application where I am inputting a string from the user and displaying some results from a database back to the user. All this is happening in a single page without the page refresh. We can use RequestParam in the controller and access the elements in the JSP page. ( I am using Bootstrap for this project)
For example in home.jsp,
<form class="navbar-form navbar-right">
<input type="text" name="myValues" class="form-control" placeholder="product..." >
</form>
and, in the controller,
#RequestMapping(value={"", "/", "/home"}, method = RequestMethod.GET)
public String home(Locale locale, Model model,#RequestParam(value="myValues", required=false) String myValues) {
logger.info("Welcome home! The client locale is {}.", locale);
This will help me get the form query string in the controller.
I can then do the necessary processing and use addAttribute in the controller to return the list. (Retailerdetail is my class to implement the backend database)
ArrayList <RetailerDetail> rlist = mydata.getData();
model.addAttribute("name",rlist);
return "home";
and display it in the jsp page.
<c:forEach items="${name}" var="element">
<tr>
<td>${element.name}</td>
</tr>
</foreach>
At this point of time I am doing this without using Jquery or js. I have seen some code where people use jquery or js for ajax implementation in Spring MVC.
My question, is this AJAX? We are getting similar functionality as AJAX without using Javascript or Jquery. Why is jquery or js used for implementing AJAX when using Spring MVC. Can you please give a specific example where I might have to do the same? I have gone through tutorials of MVC as well as AJAX quite a bit, but dont have a complete understanding of the concept. I realize that I am missing some basic concepts here. But it will help me get a lot of clarity if you could explain.
To quote from What is AJAX, really?
This is the answer by Nosredna:
"The rough idea in English: You have a web page. Some event (can be
a button press or other form event, or just something triggered by a
timer) occurs and triggers JavaScript code that asks the server for
fresh information (like the latest value of GOOG stock). There's a
piece of code on the server that collects the info you passed and
sends some info back. That's different from the page-serving job the
server usually has. When the server answers, a callback function
(that you specified in the JavaScript call to the server) is called
with the info from the server. Your JavaScript code uses the info to
update something--like a GOOG stock chart."
In my code the same functionality is achieved without using Javascript? That means we can implement the AJAX functionality without using any Javascript? When do we really have to use Javascript for implementing AJAX in this case?
If you open developer tools in your browser (f12), open the network tab, and then perform the request from your web-page, you will see the the entire html page is returned in the response.
Using AJAX, the server will return just a JSON key-value map. Your javascript code can then use this to populate a section of your page, leaving most of the page unchanged.
This is more efficient and quicker.
I've got the following problem: I made a js that generates multiple hidden fields with the same name (in this case 'vak')
I want to be able to post all that data to a JSF method so I can write it to the database.
Thing is, I want to do this without binding the data to variables in the controller
in short, I have a save button that serializes a form(with js generated fields) on click
vak=0&vak=1&vak=2&vak=3
I want this to end up as an array(list) in the JSF controllers method "handleSave()"
EDIT: this can be closed. I ended up doing it the proper way by handling each change to the calendar as an ajax request and the js just be in charge of the rendering
You can get all parameter values by ExternalContext#getRequestParameterValuesMap().
String[] vak = externalContext.getRequestParameterValuesMap().get("vak");
You'll only need to write some boilerplate code yourself inside the action method in order to convert, validate and update the values (which is what JSF would basically already be Do for you when used the right way).
first of all i want to excuse me for my last question. Didn`t know how the system works here :-)
I have a question cocerning JSF and Ajax.
My webapplication is dynamic. The whole page loads just one time at the beginning.
When the user navigates through the menus, just the center table changes it output.
I have some components like primeface`s datatable or just simple buttons which execute functions in my bean. My webapplication connects to a backend server and informations are shared between JSF and backend and will then be displayed to the users.
When a user clicks e.g. on the "Search" button function, the results should be displayed in my datatable. The method {#searchBean.doSearch} will be executed. A message is sent to the backend with user`s informations. After some seconds JSF receives those informations.
This is my principe.
Now i want to render manually the datatable and tell him "all search results have been received. please update the results"
Is it possible to render manually components via JSF? Or is there another solution.
And my second question.
When a message is sent to the backend it may take some seconds to receive the results,
what is the best way to display a "Waiting" message to the user (with a dialog)?
When i receive the results from my backend i want to update manually my components so the received informations will be displayed and then i need a way to remove this "Waiting" dialog.
I hope.. you understand what I want because my english is not the best :-)
I dont know how to start solving my problems... i think i just need a way to update HTML elements via JSF and render components manually. But i didnt find anything on the internet. Maybe I looked for the wrong things?
Regards,
Johnny
Since you are using Primefaces (which was built with pre-2.0 jsf in mind), you can use a more specific way of handling Ajax (than the one described by BalusC).
You will notice that most components have an attribute called "update". You use this attribute to tell JSF which components should be updated after something happens. For example if you had a button marked as:
<p:commandButton value='test' action='#{bean.search}' update='panelContainingDatatable' />
It would always refresh a component with client id of 'panelContainingDatatable' after executing bean.search() method.
Also, if you want to notify your users about an ajax request pending, use p:ajaxStatus (http://www.primefaces.org/showcase/ui/pprAjaxStatus.jsf)
Be careful, there are caveats:
we are talking about client id here, not component id (best look it up in the page sources)
there are edge cases when mixing ajax with ui:repeat and h:dataTable; frankly, it's best that you try to avoid such cases than solve them. They come from bugs in implementations and from suboptimal design decisions concerning ui:repeat.
You can use <f:ajax> for this. It has a render attribute which should point to (relative or absolute) client ID of the component you'd like to re-render. Starting with : means absolute (as it is in generated HTML), otherwise it's relative to the current naming container (like as <h:form>).
Here's a simple basic example:
<h:form>
<h:inputText value="#{bean.query}" />
<h:commandButton value="Search" action="#{bean.search}">
<f:ajax execute="#form" render=":results" />
</h:commandButton>
</h:form>
<h:panelGroup id="results">
<h:dataTable value="#{bean.results}" var="result" rendered="#{not empty bean.results}">
<h:column>#{result}</h:column>
</h:dataTable>
</h:panelGroup>
Where the Bean look like this:
#ManagedBean
#ViewScoped
public class Bean implements Serializable {
private String query;
private List<Result> results;
public void search() {
results = resultDAO.list(query);
}
// ...
}
I want to show a list of options to the user when he/she clicks on an inputText component. I need to call a bean method by JavaScript using onclick attribute in IceFaces.
<ice:inputText id="inputText1" partialSubmit="true" value="" onclick="" />
How can I achieve this?
As #Neall said, you need to initiate an XMLHttpRequest and return the data to the client. There are many ways to do this and I don't know the framework you are referring to, but in general, you initiate the XMLHttpRequest passing some parameters -if needed- to a web method, for example, and then return the data in JSON format. When you issue the request it usually has a callback function for success and one for error. On the sucess event, you parse the JSON response and do whatever you need to do with it.
Look at here, for example:
http://elegantcode.com/2009/02/21/javascript-arrays-via-jquery-ajax-to-an-aspnet-webmethod/
It looks like you are trying to run server-side code when the user takes some action on the client side. You probably want to initiate an XMLHttpRequest.
The XMLHttpRequest basically just hits a URL, optionally returning some data to the browser. This is what people usually call AJAX. (For Asynchronous Javascript And XML - although people usually use JSON instead of XML.)