Rendering html.erb templates in javascript - javascript

I'm running rails 4.0.4. I have a form I'm using a partial in to add a subset of fields. The user has the option to remove those fields and replace them with other fields once they're on the page. I'd like to be able to add those fields back in in the event that they want to undo their decision.
Render isn't available in javascript files (which seems odd for js.erb files). I've gotten as far as using the following to read the text of the file into a variable.
var master_quantity = "<%= data='';File.open("#{Rails.root}/app/views/shared/_a2a_master_quantity.html.erb","r").each_line{|x| data+=x};data %>";
Unfortunately escape_javascript doesn't appear to be available in the asests folder either, so I'm unable to use this string as it breaks the javascript.
Anyone have any suggestions on cleaning the string or alternate methods to get the partial into my javascript?

You could try,
controller = ActionController::Base.new
controller.send(:render_to_string, '/shared/a2a_master_quantity')
Whatever you pass to render_to_string above are params for that method.
You may or may not need that leading '/' for '/shared'.

If I understand your question, and the partial never changes, you won't need to get it from the server. Just hide it in CSS (such as with JQuery's $('#selector').hide() )
On the other hand, if you need Ruby to customize your partial each time the user restores it, you can send an AJAX request from the browser to your server to request a new version of the partial.
Add a line to a suitable controller action that renders your partial:
render :partial => 'a2a_master_quantity' and return if request.xhr?
Make a suitable XML HTTP Request in your JavaScript to get this partial (such as JQuery's $.ajax().)
Then use JavaScript to add it to the DOM in the appropriate place.

Related

Rails API - helpers for AJAX

I have a normal rails app website, but on some pages I need to use AJAX.
I already have some working AJAX Javascript code using jQuery, but so far I haven't used any rails helper to do that, writing strings corresponding to paths manually.
But is there a more convenient way to do it in javascript ? Suppose I have a javascript function which takes an ID as argument, and must call an AJAX action. So far I've been doing it this way
var url = "/tags/tagID"
function getTag(tag_id){
$.get(url.replace("tagID", tag_id) +'.json')
.fail(function(data){
alert('Oops error !');
})
.success(function( data ) {blabla ] )
}
Is it possible to rename the .js to .js.erb and use path helpers ? So I could get rid of this url variable and write
routes.rb
resources :tags
tags.js.erb
$.get(tag_path("tagID").replace("tagID", tag_id)....
Or is there a more convenient way to do this ? I only need very little AJAX, so I don't want to use a frontend framework (Angular, etc.), just jQuery
EDIT My scenario
A user searches for a given tag thanks to an autocomplete searchbar. This searchbar will return the ID somehow.
The user can select several tags this way, and their IDs will be stored in an array. Now, upon clicking a button, I want to send a query to a non-RESTful (with the ID array as parameter) controller action via AJAX. For now I will focus on sending one item at a time (so just one ID string), for it is easier/more reactive.
This action is actually going to look in my models for projects and ingeneers that possess this tag, and return a JSON with formatted results.
Yes, you can use *.js.erb to use Rails helpers. Rails provides some handy helpers to work with Ajax. Normally with rails you can use them by using the the tag remote: true.
In your case something like
<%= link_to 'Tags', tags_path(<tag.id>), remote: true %> (roughly),
Read more about using Rails helpers with Ajax here, and this explains it nicely.
Update
Rails is using CSRF token to validate requests (except GET), so if you are going to use pure HTML/JavaScript, you want to add the token to your request. Have a look at this post on the same.
I agree there is no out-of-the-box way of doing that, but there are few workarounds.

Django modify model instance from HTML

I want to know if it is possible to directly modify and save a model instance in the HTML Template and not via a view and extra URL.
My user has a Boolean Property, I want to display it as a toggle button on the website and the user should be able to toggle it on or off without leaving the website or reloading it.
class User(AbstractBaseUser, PermissionsMixin):
...
autoplay_enabled = models.BooleanField(default=True)
...
Is this possible without an extra view or form?
Basically I just need to set
request.user.autoplay_enabled = False (or True)
and then save() it
If I can't modify the object directly in the HTML template is it at least possible to just execute a function I have defined somewhere in my Python code, without having the need to create a new view?
What you're asking doesn't make any sense at all. HTML is just sent to the browser for display. You can't do anything "from HTML" without making some kind of request to the server, and the server won't do anything unless that request is received by some code - eg a view connected to a URL.
If you want something to happen without refreshing the page, you need to use Ajax. You can use a simple Ajax POST to a view that toggles the value and saves it - it only needs a dozen lines of code between front and back end.

rails js/ajax updating div not properly updating with information

continuation: Entry level javascript with rails: updating a div on form submit (3.1/jquery)
I'm able to return 'something' now, just not what I want.
CONTROLLER
class ThisController < ApplicationController
respond_to :js
def update
#do stuff
if resource.save
respond_with(resource)
end
end
VIEWS/RESOURCE
update.js.coffee
$(".testdiv").text('<%= escape_javascript(render(:partial=>"resource"))%>')
_resource.slim
p= resource
p whhhhy
Basically, I have a form that posts remote (i.e. remote=true) that updates a db field and then the update controller returns that field. This form posts, the data changes, and when I change the text in _resource.slim the text will change....but the 'p= resource' does not get evaluated at all. I want the .testdiv to watch for changes made via the form.
So, I've been able to rig a minimal version one step closer to what I want....only I can't actually get variables to pass into the template. Closest tutorial I've referenced, but I'm not actually using the code, just trying to get a working ajaxy version within something I have that was already working.
I cannot see the problem atm, but it isn't right. I don't have access to manipulating the resource variable, but I am unable to. It seems simple enough (though I'd like to do with out a partial and extra files in views/resource, just put js in the assets/controller.js.coffee)
As stated in the comment, I changed the local variable to an object variable. This resolved the issue.

How to generate a Javascript AJAX POST method and handle it in Ruby on Rails 3.0

I want to do something quite simple. Click a button on my html javascript page which sends a bunch of data to the server using the AJAX Post method. The server uses the data sent by the POST method to generate an xml file which it then sends back to the user so they can save it.
My knowledge of ruby on rails is very limited and I've looked at tutorials but none of them seem to simply explain how to handle POST requests. I don't need anything modified on the HTML page itself so the entire html page is static with the sending data part looking like:
//data is a huge string already xml > 1mb
xmlhttp=new XMLHttpRequest();
xmlhttp.open('POST', "http://localhost:3000/xmlsave", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(data);
In rails 3.0 I have /xmlsave routed to an action in a controller I made:
class MyController < ApplicationController
def xmlsave
#Read data sent with POST and put it in generated xml file and send to user
end
end
If I am even doing this correctly, can anybody explain to me or point me in the right direction to what I need to put under the xmlsave method to:
Read data which was sent with AJAX POST
Generate xml file from data string which is already xml.. just want to copy paste it into the contents of xml file I want to send back
Send xml file to user (send_file ?)
I apologize if what I am trying to do is just completely bizarre or I have a completely wrong idea. Most of the tutorials I read go in the direction of creating partials using to edit parts of the html page the user is already looking at which I don't want to do. None of the tutorials I read seem to explain exactly where requests go and where data goes and where I should call functions etc and I am confused.
Thank you.
I think you shouldn't use AJAX for that, since you want the user to get the XML in response and be able to save it. It should work as a form submit button or link. The form would send a POST request with the XML (I assume the XML is already in the document somewhere?) to your xmlsave method.
Normally this would render the response as application/xml and the browser would probably display the contents (default configuration). To avoid it, you could set content type to application/octet-stream - this way the browser would prompt to save the file and the page wouldn't be refreshed (so no AJAX required).
To "cut/paste" fragments of the incoming XML into the result, you'd probably have to parse the incoming data and then pass the resulting DOM model or its fragment into a template of the new XML. You can use hpricot or nokogiri to parse and then render xmlsave.xml.erb as a result.
Here's a rough idea how it could work:
xmlsave.html.erb:
<%= form_tag xmlsave_models_path(:format => :xml) do %>
<%= hidden_field_tag :data, '<input><justatest id="tagid">test content</justatest></input>'%>
<%= submit_tag %>
<% end %>
model_controller.rb:
def xmlsave
input = Hpricot.XML(params[:data])
respond_to do |format|
format.html
format.xml {render :content_type => 'application/octet-stream', :locals => { :input => input } }
end
end
xmlsave.xml.erb:
<myxml>
<input>
<%= (input/"#tagid").inner_text %>
</input>
</myxml>
NOTE: this code is using Rails 3 templates
I think it's better to use a Javascript library like jQuery. after you can do you Ajax request more easily
You don't really need Ajax to do that. a simple link is enough.

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