Can we call JSF controller method from jquery ajax? [duplicate] - javascript

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?

Related

How to mix python and javascript in the server side

I'm creating an application that needs to pull certain data to show it to the user. This data is pulled via a JavaScript function that ideally I'd like to have on the server side, not on the source code of the page.
The flow should be:
User chooses 1 parameter in the website and clicks ok
Send a POST request to Django with that parameter
Django's view uses that parameter to pull another 4 parameters from the Django database
Somehow use this 4 parameters in the JavaScript function to get some timeseries data
Pass this data from JavaScript to the view, and from the view update the browser's template without the user refreshing the page
How can I pass the 4 parameters from Python to the JS function, and then the result of the JS function back to Python?
The reason I need to use JavaScript and not Python for retrieving that data is because JS has a specific library that would make my life so much easier.

Do we need AJAX in Spring MVC? When?

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.

Accessing Javascript variables from JSF [duplicate]

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.

Flow of Jsp -> Javascript webpage (Ajax?)

I am making a website but I get a bit lost programming dynamic sites.
The user needs to enter x (inside a textbox), click submit, process in java (serverside) and present outcome as a report to the user (using javascript).
I'm at the moment using JSP to process the users input but now I need to pass the JSON code into the javascript. The javascript requires JSON data.
At the moment I have JSP which returns the necessary JSON code and the Javascript which works with hardcoded JSON code. I need to somehow store the returned JSON (from the JSP) in a variable and pass it to the Javascript. I have a vague understanding of AJAX - i'm just unsure if this is possible and how to link it all together.
Thank you.
Your JSP "page" can simply generate JSON directly. There's no reason the output from JSP has to be HTML. From the client, therefore, you POST to the server, the JSP runs, and the result (pure JSON from your JSP) is sent back to the client as the ajax response.
Sounds like the perfect place for AJAX - you can submit the request with javascript, and when it comes back process it further with javascript. Unless you want the page to refresh.
If you are using jQuery, you can look here to see how to implement it, should be relatively painless: http://api.jquery.com/jQuery.post/

How can I send Javascript events back to Rails to process?

If I have user interactions in my Javascript layer, can I have Javascript actions trigger Rails controller actions and pass data from Javascript to those Rails methods?
Yes. You make asynchronous calls back to your Rails application using XMLHttpRequest, typically through Prototype or some other Javascript library. You pass data back to the server using query parameters, much like any other request, and your application returns HTML fragments or Javascript code that is used by the browser to update the relevant parts of the page.
The PrototypeHelper class is useful for generating the right stuff in the server. Ajax.Request is what you'll use on the client.
I believe you can make AJAX requests back to your controllers. Rails by default includes prototype so you can use its AJAX functionality ( http://www.prototypejs.org/api/ajax/request )

Categories

Resources