AJAX request with Rails 3 and jQuery is being processed as HTML. - ruby-on-rails

I have a form that i want submitting with AJAX, using rails 3 and jquery. The problem that I am facing is that rails is responding to the AJAX request as HTML too. After a little search I found that this has something to do with the correct Accept headers not being passed. How do i fix this?
This is the controller code
respond_to do |format|
format.js { render 'user/create' }
format.html { redirect_to ((params[:feed][:url].nil?)?url_for(:home) : params[:feed][:url]) }
end
It seems to work on a friends firefox, and on my chrome too, smthng wrong with my firefox?
UPDATE: It seems that the error arises only when I use a proxy service as JonDo, which probably changes the accept headers... Is there a way to force rails to use js format if the X-requested-by header is present?
Thanks

Your controller code looks correct. Are you sure that you have added the .js suffix to the AJAX URL in your form? That's how the responder knows what format you want for the response. The default format is HTML so omitting the suffix would look like it's responding to a HTML request.

You likely didn't set the dataType properly. See the docs (this is &.post) If you set dataType to "js" you'll be all good!

Related

Rails 5 after submitting form / action stay on exactly the same spot on page

I have this webshop, and on one page you see
products;
with a submitting form for a booking;
your order with its bookings;
with a removing link for a booking;
and an updating form for a booking.
Both the order.bookings and the products make potentially long lists on a html page.
The whole booking works by only a booking_controller.
What the booking_controller does:
Takings in the (new) params of a single booking or the destroy action.
Saves the new order.
Redirects to the store.
Works fine, just using ruby and html.erb.
Only problem, and this really needs to change, is that obviously after each redirect the browser goes to the top of the page. The browser isn't focussed. Or better to say, the browser should remain, but doesn't.
I get that your doing all these things on the server-side, so a page reload, or better to say, data-refresh, is necessary. What I don't want is building this whole thing again on the client-side (JS).
Can't I simply say something like: after data refresh redirect to exact same spot on page. Ignoring all the difficulties an asynchronous request would give, or am I exaggerating and is a little JS easy?
With Rails, using ajax is very easy however if you're not familiar with ajax at all it can be a bit daunting at first. Luckily there are many tutorials on the subject. Basically, add the remote: true option to your form_for statement and rails will automatically understand you want it to make a 'POST' request in JS format. It's important to realize that the incoming HTTP request is in JS format because you'll then need to specify handling that event in the controller. Such as:
def create
#Do whatever saving and processing you need here
respond_to do |format|
format.html { redirect_to some_path_here }
format.js { } #By not adding anything in the brackets here, you're telling rails to fetch a js view file that follows standard rails convention and so it should be named 'create.js.erb'
end
Then in your controller's views folder create the view file create.js.erb. In that file you'll want to refresh whatever part of the page needs updating which usually involves hiding the old div that was there and appending a partial in its place. I usually leave an empty div with an ID on the page (in this case your new_whatever_page.html.erb that I then call in the js.erb file to append a partial to:
In your create.js.erb add:
$("#the-id-of-the-div-in-your-new-view-page").html("<%= escape_javascript(render 'order_table') %> #This basically says, find the div on the current page with a matching id and then append the partial named _order_table.html.erb to it.
Now just make a partial named
_order_table.html.erb
in the same views folder and put whatever content you want to insert or update.

Understanding Rails Controller Request Format: "Processing by MyController#action as FORMAT"

In all likelihood, this question reveals my gross misunderstandings of Rails, HTTP, and the internet.
Problem
I have a request hitting my server from a "transparent redirect" via Stripe API. The request is coming in as HTML format. I want to respond to it in JS format in an AJAX-esque way. My code looks like this:
def create
.... other code ....
render "attendances/create", formats: [:js]
end
I have a view file "attendances/create.js.erb." This successfully sends a response, but rather than the response executing the JS, the JS is instead rendered as HTML. It thus looks like plaintext JS.
Thank you for taking the time to consider this!
What are the request headers, Your ajax request must have accept request headers of javascript instead of default html, for it to allow/execute the js response directly.
See datatype here , it should be script

how can i render a template as well as a JS file BOTH in a controller action

i have a scenario where in edit action ,i need to render the edit.html.erb as well as trigger the edit.js.erb file as well.right now i have
def edit
#page_id = params[:id]
respond_to do |format|
format.html
format.js
end
end
but only the view is renderring ,but my edit.js.erb is still not triggered.
With both ansers you can get it working, but you do not follow conventions. The edit.js is meant for Ajax-calls.
What you seem to be doing, is using partials to build up your page. Then you really should follow naming conventions (starting the filename with _) to be clear for other programmers.
Second, you always need to make sure your site can work without javascript, so your Edit page never should require any Javascript to work. The javascript is complementary to improve user experience (like using ajax to make edits without a page-refresh).
Summing up:
- move the 'required' javascript code to your edit.html.erb.
- only use the edit.js.coffee to handle the updates to the existing webpage if Ajax is activated, use as much of the js from the edit.html.erb.
- Put the rest of the shared code into partials, like _niceedit.js.coffee and render it using 'render :partial=>'...
Follow conventions, it will help you later on and when using test services etc.
respond with js and write code below:
edit.js.erb
$('body').html('<%=j render "edit" %>');
Your impression of what it does is wrong.
If you want javascript to run, then your edit.html.erb file needs to contain:
<%= javascript_include_tag "jsfilename" %>
and store your javascript in public/javascripts/jsfilename or similar location (public/assets/javascripts/
The respond to format.html, format.js is for requesting the view in that format.
Eg. If I browse to edit.html, it shows the html.erb view, if I browse to edit.js, it shows the js.erb view. The functionality is so that you can request the same content in different file formats, rather than to add javascript functionality to your webpage.

Check if a url parameter exists and render approprietly in Rails

I have a URL in this format http://0.0.0.0:3000/#&ui-state=dialog. I want to check for the existence of ui-state so I can render approprietly a page. I tried this
params.has_key?(:'ui-state')
But it did not work.
How can I check for the existence of ui-state?
Solution
I am using jQuery mobile. What seems like a url parameter is actually an internal attribute of jQuery mobile. That's the reason why there are no ?.
If the partial example URL you posted (http://.../&ui-state=dialog) is your actual URL, it is incorrect. Your query string must begin with a ? as in http://.../?ui-state=dialog. An & cannot start the querystring.
Update
Since this is from jQuery and not a real URL parameter, it won't appear in params in Rails. Instead you'll need to parse it out of the request.url:
ui_state = /&ui-state=([a-z]+)$/.match(request.url)
puts ui_state[1]
Update2
Since the &ui-state follows the url hash #, it will not be available in the request.url. The hash is strictly a client-side component used by the browser, and isn't sent to the server in the HTTP request.
have you tried params[:ui-state] == dialog or params[:ui-state].blank? / params[:ui-state] == ""

render :js not working

I am working on window 7 and facing issue with render
render :js => "alert('Hello')".
But it is not getting alert.
Do any one have experience with this issue.
You should make the call using AJAX so you should add the param "remote: true" to the link or form that is making the call to that action
Be sure that there is client side requested with JS format, as in that cases Rails set up content type for js, and not text/html.
It seems like you are trying to debug your code. Using a before_filter is not the best way. A request can only render once.
I suggest adding statements to your logging, and using the javascript/development console of your browser (Chrome/Firefox): this will show what goes over the wire perfectly,a dn what is executed on the client, and why it fails (if it fails).
Hope this helps.

Resources