Simulating Rails form submit in JavaScript - javascript

I have a pretty standard Rails HAML new object form that does the usual stuff and ends with:
= f.submit "Add scenario"
This works perfectly, and the scenarios_controller.rb is also a straightforward:
def create
...create scenario...
redirect_to scenarios_path
end
However, I have also developed a wizard-type form that needs to do some JavaScript on pressing my button:
= f.submit "Add scenario", :onclick => "return validateForm()"
In my CoffeeScript, I collect up all the information and finish up with:
$.post(
url
data
(data, textStatus, jqXHR) ->
# How do I follow the redirect?
return false
My url and data are correct as the above controller works correctly and creates my object, but my page doesn't redirect to scenarios_path. I think I should be doing something with the post result, but searching around the web I cannot find out what, and examining the returned fields in Chrome's debugger doesn't suggest anything. The only suggestion I saw was to use data.redirect, but such a field doesn't exist, although jqXHR.responseText seems to contain the page I want to redirect to.

I'd treat the HTML call to Scenario#create and the JS call to Scenario#create differently, using a respond_to block.
In your scenarios_controller.rb file:
def create
# create your object
respond_to do |format|
format.html do
redirect_to scenarios_path
end
format.js
end
end
In views/layouts/scenarios/create.js.erb, then put something like:
window.location.replace("<%= scenarios_path %>");
When you call Scenario#create with JS, the create.js.erb file gets rendered and forces the redirect. When you call Scenario#create with HTML, the redirect_to call happens as usual.

Related

Rails Controller - refresh page same as if I hit the refresh on my browser

I have inherited a Rails code base that I do not fully understand. We have a requirement to, when the user hits Submit, render ON THAT PAGE the set of validation failures the user put into the form. I cannot redirect to any other page - we must remain on the page which contains the form upon which they put the invalid input.
Here is my method
def tpr_bulk_update
updated, date_died = update_tprs #it returns 0,0 when there are validation fails
if updated == 0 && date_died == 0
flash.now[:notice] = 'A bunch of errors occurred'
#Here I need to refresh the page. I do not especially want to redirect.
#I want this to perform exactly the same as me hitting the refresh button on my browser.
#The initial form loaded via a very complicated codebase that I do not understand exactly.
#I do have available to me the params from the initial call - but it seems to me hitting refresh on
#the browser implicitly handles repassing to this method with the SAME PARAMS I CAME IN WITH....
#AND it shows my flash.now. So then, I want to refresh the page the same mechanism the browser uses,
#because this is what demonstrably meets my requirement
elsif !date_died
redirect_to tprs_index_vod_assets_path
else
flash[:notice] = "One or more TPR assets were not given valid future dates, so those invalid dates did not save".html_safe
redirect_to tprs_index_vod_assets_path
end
end
The issue is I see no way to do this. Perhaps the browser invoking refresh uses javascript that is impossible to inline in my rails controller?
redirect_to :back
fails on account that the set of params I came in with are not populated - it explodes.
respond_to do |format|
format.js {render inline: "location.reload();" }
end
My method does not output javascript, and neither will it ever output javascript - that is a requirement for the system.
I need whatever is equivalent to the refresh operation my browser (Chrome) performs when I press "Refresh". I want that to happen right after I set my flash.now message. How can I capture what Chrome/what hitting refresh actually does? And how can I perform it within my controller?
This is exactly what AJAX was designed for. By sending an asyncronous request you can send data to the server without reloading the page and update the page with the response. In Rails you can use Server Side Concerns to simply replace a chunk of contents with a rendered view.
Since you don't actually have an example of the form or controller this is a simplefied example that demonstrates the concept:
class ThingsController < ApplicationController
def new
#thing = Thing.new
end
def create
#thing = Thing.new(thing_params)
respond_to do |format|
if #thing.save
format.js
else
format.js { render :new }
end
end
end
end
end
# things/_form.html.erb
# remote: true is the default - its just added for extra clarity here
<%= form_with(model: #thing, remote: true, id: 'my-special-form') do |form| %>
<% if #thing.errors %>
# .. display the errors
<% end %>
# ...
<% end %>
# things/new.html.erb
<%= render partial: 'form' %>
// things/new.js.erb
// Since we want to extract the children of the form element
// we use DOMParser to create a fragment
const node = new DOMParser().parseFromString(
"<%= j render(partial: 'form') %>", // rails renders the template
"text/html"
);
// Find form on page and replace its contents
document.getElementById('my-special-form').innerHTML = node.querySelector('form').innerHTML;
// #todo set flash message
// things/create.js.erb
window.location = "<%= thing_path(#thing) %>";
The way that this works is that Rails UJS listens for submit events on any element with the data-remote attribute. Instead of the normal submit it will send an XHR request with the Content-Type: application/javascript header.
After rails is finished rendering and reponding with your js.erb view it is sent back to the client and Rails UJS takes the response and evals it by popping it into a script tag.

Rails 5.2. Rendering a js.erb partial from a helper method

I have a model called Question, and it has action create;
My goal is to display a flash message instantly, using a helper method (show_alert for example) when the instance is not valid.
question_controller.rb
def create
question = Question.new(question_params)
if question.save then
redirect_to show_question_path(question.id)
else
show_alert(:warning, question.errors)
end
end
application_controller.rb
helper_method :show_alert
def show_alert(type, message)
#type = type; #msg = message
respond_to do |format|
format.js { render :template => 'alert.js.erb'}
end
end
alert.js.erb
var div = $('<div></div>').addClass(`alert alert-${#type}`)
$('<ul></ul>').append( $('<li></li>').html(#msg)
div.append(ul)
$('#alerts').html(div)
But instead of displaying the flash, I get only the partial's code on the white screen.
see the screenshot
Since I've used respond_to I got another error: ActionController::UnknownFormat
I need the snippet of code in alert.js.erb to be executed, in order to render the flash, I think the trick is somewhere in the render function, but two hours of googling were just a waste of time.
Please help! Thank you in advance
ActionController::UnknownFormat error is showing up because the browser is sending HTML request to Rails server, but the respond_to block has only specified what to do in case of a javascript request from web server.
You will need to add a little bit of Ajax to achieve what you want. See this tutorial on Ajax. https://www.tutorialspoint.com/ruby-on-rails/rails-and-ajax.htm
Ajax will send a js request to browser in the background (i.e the browser will not refresh or show any signs of loading). This js request will be sent to Rails server and it will return the .js.erb file containing the script back to the browser. Now since this script was returned as a response to Ajax request by browser, the browser will already know that it is javascript that needs to be executed.
If you do not wish to implement Ajax, you have the alternate of doing something like this in your create controller:-
def create
question = Question.new(question_params)
if question.save then
redirect_to show_question_path(question.id)
else
redirect_to new_question_path(error: question.errors) #new_question_path is the action that displays the question form to the user
end
end
and then you can initialize an error variable in the action that displays the question form. e.g.
def new
#error=params[:error]
#rest of the code...
end
And then in somewhere in your new.html.erb (or whatever the html.erb file name is)
<script>
<% if #error %>
var div = $('<div></div>').addClass(`alert alert-<%= #type %>`)
$('<ul></ul>').append( $('<li></li>').html(<%= #msg %>)
div.append(ul)
$('#alerts').html(div)
<% end %>
// you might need to tweak the variable names in controller or the above code
</script>
(This code above may not be perfect. its just to give u an idea)
However this approach will not be as quick and beautiful as ajax because when the user will submit their question, the entire page will load again to display the error warning.
By default, all output from helpers is escaped. To show the HTMl as-is, you need to use the html_safe method (https://apidock.com/rails/v4.2.1/String/html_safe). See Using helpers in a view escapes the html?
I cannot be sure this without seeing your alert.js.erb but it could be that you need to use escape_javascript in your alert.js.erb
Something like (and I haven't tested this out) in your alert.js.erb
$('<%= escape_javascript("#{type} - #{msg}") %>').appendTo("#alert")
You can read more about it on Rails Guides - Working With Javascript in Rails
Hope this helps!

Problems submitting AJAX request in Rails 4

I've been following http://blog.markhorgan.com/?p=522 as a guide to update an image in a form with an ajax callback. Image saves fine but I want to do some clever ajax so the page doesn't refresh.
Here's my code:
edit.html.haml:
#promo-image
= render partial: 'promo_image'
_promo_image.html.haml:
= form_for( #property, remote: true) do |f|
= f.file_field :promo_image, :pattern => "^.+?\.(jpg|JPG|jpeg|JPEG|png|PNG|gif|GIF)$", :id => 'promo-image-upload'
= f.submit 'Update'
= image_tag #property.promo_image.url(:medium)
properties_controller.rb
def update
#property = Property.find(params[:id])
if #property.update(property_params)
format.js
else
render 'edit'
end
end
update.js.haml:
$("#promo-image").html("#{escape_javascript(render partial: 'promo_image',)}");
With the code outlined above I get error pointing to the format.js line:
ArgumentError in PropertiesController#update too few arguments
Can anyone see where I'm going wrong or perhaps point me in the right direction?
Many thanks!
Steve
UPDATE
Just to be clear, I want to be able to update JUST the Div stated here:
update.js.haml:
$("#promo-image").html("#{escape_javascript(render partial: 'promo_image',)}");
This code works, but refreshes the whole page:
respond_to do |format|
format.html { redirect_to edit_property_path(#property) }
format.js
end
FURTHER UPDATE
Just to be clear on my motives, I want to be able to update an element on the edit page, and not be redirected to a different one, e.g. show or index. This is for UI reasons. The guide above talks about the exact same thing.
FINAL UPDATE
The issue is because I'm using a file upload, this can't be achieved via ajax. For those in a similar situation see here: Rails form_for with file_field and remote => true and format => :js
A solution could lay here, and I will investigate this: https://github.com/JangoSteve/remotipart
Thanks to everyone for helping me work out the error of my ways!
Regarding your first update, you said that this code works, but refreshes the page:
respond_to do |format|
format.html { redirect_to edit_property_path(#property) }
format.js
end
If that is the case, that means the incoming request is an html request, rather than an AJAX request. So the format.html block runs and redirects the browser to the same page, which now has the updated image.
What you need to do is figure out why the page is not sending the request as AJAX. You can see the request format if you look at the terminal output (if running locally). It will say something like:
Processing by ControllerName#action as [format]
Format needs to be JS in order for the format.js to render update.js.haml.
UPDATE:
Now that you mention it, the issue is indeed the file_upload field. Uploading files with AJAX is actually not possible with the Forms Helper. See the docs:
Unlike other forms making an asynchronous file upload form is not as simple as providing form_for with remote: true. With an Ajax form the serialization is done by JavaScript running inside the browser and since JavaScript cannot read files from your hard drive the file cannot be uploaded. The most common workaround is to use an invisible iframe that serves as the target for the form submission.
I did a quick search on Google and found the remotipart gem, which seems to specialize in doing this. I don't have any experience with it though, so you're on your own from here on. :)
Try changing your update action to
def update
#property = Property.find(params[:id])
if #property.update(property_params)
respond_to do |format|
format.html { redirect_to properties_path }
format.js
end
else
render 'edit'
end
end
Source

Input form where user could enter regular expression

I have a rails application in which I need to create some input form where user could enter regular expression. This regex needed to be passed to my method check_site(url, regex) that will return true or false depends on regex found on the page.
I've tried to create a 'link_to':
link_to 'Search', check(item.name, #pattern)
In this case method "check" is called not with button pressed but with page loading.
Do I need to use JS+AJAX? How to?
Crash course on getting AJAX/JS set up with your Rails form:
Ensure correct javascript is called in your page <head>: JQuery + application.js (Jquery-compatible version, of course!)
Change your link to:
link_to 'Search', check_item_path(:name=>item.name, :id=>#pattern, :var=>var, etc.), :remote => true
In items_controller:
def check
...your regex...
respond_to do |format|
format.html { redirect_to ...(wherever you'd like if no .js) }
format.js
end
end
Create a file called check.js.erb in the corresponding views folder and enter the javascript you'd like to update the page / confirm the form's successful submission / return results from your search, etc.
$(document).ready( function() {
$("#result").html(" <%= #item.result == true ? "true" : "false" %> ");
});
No method error: check_item_path
This means Rails is not recognizing the route to that controller action. Run rake routes in console and see if anything corresponds to the items controller, check_item action. If not, add:
match 'items/check_item'
to your routes file. Then run rake routes again and you should see check_item appear somewhere - if it does, you can use check_item_path again.

How does js.erb work

Lately i have run into a few applications that are using js.erb and i am not really sure how to use it ...here is the code below. Can someone help me understand how this works?
in the routes.rb file
map.resources :player_emails
my controller player_emails_controller.rb in the create action
def create
#player_email = PlayerEmail.create(params[:player_email])
if #player_email.save
#response_txt = "The player has been emailed."
PlayerEmailsMailer.deliver_pattern_email(#something, #player_email, request.host_with_port)
#error = false
else
#error = true
#response_txt = "Please make sure you entered your name and a valid email address."
end
end
then i have the file player_emails/create.js.erb
$('#player_email_ind').hide();
$('#player_email_submit').show();
$('#player_response_msg').html("<%= escape_javascript #response_txt %>").fadeIn();
<% unless #error %>
$('#player_email_form')[0].reset();
<% end %>
i know what the jquery is going but i dont know how this is doing the ajax call. Does it just automatically do an ajax call when there is a js.erb...can someone explain the way this works and why i dont need a respond_to in the controller action telling it this is format.js
If a js (ajax) request is made it will respond by rendering the js.erb file and viceversa.
This is the default behaviour that is being performed:
respond_to do |format|
format.js{
render :template => 'create.js.erb'
}
format.html{
render :template => 'create.html.erb'
}
end
When the form is submitted, it does a POST to /player_emails. The resource declaration in routes.rb ensures the request is handled by PlayerEmailsController#create.
The controller is responsible for handling each format it receives. In the case of an AJAX call, the format is 'js', and is set by explicitly adding the format string to the end of the URL (/player_emails.js) or (more likely) by deducing the format from the request header.
In your case, the create action does not expect anything other than AJAX, so it takes a shortcut and omits the respond_to and format blocks. The controller has already figured out that the format is 'js', so when create is complete it takes the default action of rendering the appropriate template for the format (create.js.erb).
Does your form submit button have a :remote => true on it? If so, there might be some JavaScript in rails.js or application.js that automatically submits via AJAX. Bottom line is, there has to be some JavaScript somewhere that is making an AJAX call and asking for a js or JSON response, otherwise it would be an html request.
As for why you don't need a respond_to block, I'm not entirely sure. Maybe since the call is always being made by AJAX and there is a js.erb template available, it just does its thing without complaining. Is there an html.erb template at all? If not, try doing a regular form submit and see if it complains.

Categories