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

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 )

Related

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

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?

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.

Pass PHP class instance through AJAX?

I recently wrote a PHP wrapper class for a new API we are using and have been asked to setup a demo which makes use of it. Certain features can be called directly from PHP, however things such as performing actions on button clicks requires I make use of JS/AJAX.
As I already have an instance of the object in my main PHP file, can I pass this as a parameter to JS and then pass it through Ajax to my handler or is it necessary to establish two separate instances?
The closest thing to doing what you want that I can think of would be copying the PHP object to a JavaScript variable via json_encode and then passing that variable back to your PHP code during the AJAX event via the data parameter. PHP code doesn't persist in the way that you seem to be describing - once a page has been requested by a browser, your PHP code for that page is done, there are no variables persisted by the server after that point.

Acessing Gorm object in JS

i developed a web application using grails/gorm about traffic reports. Basically, its possible to find for traffic reports like (in road xx there was an accident yyy and the traffic is very slow.)
now i need to integrate the map in the application. My map is in javascript, how can i access gorm objects in js (if it is possible)?
standard groovy i use:
<%
def road1 = packagename.Road.list()
out << road1.name
%>
Can i have the same kind of access in JS ?
typically for this type of thing you make some sort of request to the server, which returns the data to the browser via JSON or XML. If your map is coming from some javascript library, you can use Ajax to query your server for the data. Which JS library are you using? Whatever it is, it probably has a mechanism to make an ajax request -- you would pass the params on the ajax request that the server needs to get the appropriate data, and when the request returns a callback that define will do something with the data.
As a note, its not a bad idea to set up your application code as follows.
You have your domain object, 'Road'
Generate a RoadService, with a method listAllRoads
Generate a RoadController, with an action listAllRoads
The controller calls the service, the service uses the Domain objects to retrieve the list. In your action, you can take the list and render in whatever form you need (json, xml, or as a gsp).
Grails is all about conventions; the above is how you conform to those conventions.

Best practice for rails-javascript interaction?

I have a page which shows a Google map. I'd like to use Javascript to fetch several points from my database and place them as markers on the map. So the flow is:
Javascript calls a Rails action with parameters.
Rails queries the database.
Rails returns the response.
Javascript updates the page (Rails can't do this since it must be aware of the JS map object).
What is the current best practice for implementing such a scenario? I know I can use a Prototype Ajax.Request to call the Rails action but how should I call the Javascript function which updates the page when the Rails action returns its results? Should I update some hidden HTML and have an event listener listen on it? Or is there a better way?
You have a couple options.
1) Your ajax request can be of type 'script' which will allow you to write an action_name.js file that your rails app renders. This has access to all of your page items (it's not likely to have access to your map object however unless that's public)
2) My preferences is to have your javascript query for json data (type 'json') which then allows you to use that data as you please in your JS. I don't use prototype but the general flow would be.
initialize your map
query for some json data using ajax (ie. locations with lat/long)
rails reponds_to do |f| f.json { render :json => some_hash} end
in your ajax callback (back in javascript), iterate over json data and add points to your map appropriately. (or do whatever you like)

Categories

Resources