I am using Ruby on Rails 4. In my previos question I asked about how to handle JavaScript events of a link_to :remote element "a là Rails Way". However I would like to make the AJAX to do not evaluate the JavaScript response (whatever it is) so that I can implement my custom behaviors.
In my case the AJAX response that should be ignored is generated by clicking the following link:
link_to('destroy', article_path(#article), :method => :delete, :remote => true, :id => 'css_id')
On success it will return a JS redirect but I would like to simply catch the success response and do not evaluate the subsequent redirect.
$('#css_id').on('ajax:success', function(event, xhr, status) {
alert("success!");
\\ Here I would like to do not evaluate the JS response.
});
How can I make that?
You can write a javascript behavior and just call this behavior in your .js.erb file since you can avoid writing more js codes inside the template. It should be something like this.
EX: in the create.js.html:
App.createProdict() #pass the required params.
And this App.createProduct is a js behavior.
Related
I'm implementing a CSP using rails 5.2.1 content security policy DSL. I've got my policy set to something like:
Rails.application.config.content_security_policy do |policy|
policy.default_src :self, :https
policy.connect_src :self
#...
policy.script_src :self
end
# If you are using UJS then enable automatic nonce generation
Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) }
I also have <%= csp_meta_tag %> in my application.html.erb
At this point I need to add a nonce: true flag to any inline scripts for these to satisfy the policy. I've done this and it works as expected. However, I'm having trouble maintaining existing AJAX style functionality. For example, I have something like (note the remote: true):
# index.html.erb
<%= link_to create_object_path, id: "#{object.code}",method: :post, remote: true do %>
<button type="button">Create object</button>
<% end %>
In my controller
def create
#object = current_user.object.create
respond_to do |format|
if #object
format.js
else
redirect_back
format.html
end
end
end
In my *.js.erb file
$("#<%= #object.service.id %>").text("Added!");
The object is successfully created but I believe the policy is blocking the above "Added" success message that I add to the DOM. I have not seen any errors in the console so I'm not sure where to go from here.
My understanding in this scenario is script tags are temporarily inserted with the contents of the *.js.erb file and these script tags do not contain the nonce. Or, it is a mismatch.
I've been stuck on how to troubleshoot from here. Any guidance here is much appreciated even if different architectural pattern for sending data to client is the way forward. Thanks in advance.
I ran into a similar issue. In my case, it didn't refuse to run the js.erb file itself but rather scripts in templates nested within that file through the use of render. So, this answer may have limited utility to your specific case. That said, I did try to reproduce your issue using Rails version 6.1.1 and couldn't.
However, even if you get past the initial hurdle of getting just your .js.erb file to run, you can still run into the issue of nested scripts: if your .js.erb file renders a template that contains a script tag. That script won't run because the request from which it originated assigns it a new nonce, which won't match the nonce in the meta tag.
So, to those coming here from a search engine as I did, here's the general strategy I pursue to get async embedded JS working with CSP for that nested case and assuming the .js.erb file itself runs. Using your case as an example:
Send the nonce along in the AJAX request. I suppose you won't get around writing some custom JS to send the request. Something like:
document.getElementById('<%= object.code %>').addEventListener('click', e => {
e.preventDefault(); // So we don't send two requests
fetch('<%= create_object_path %>', {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify({
nonce: document.getElementsByName('csp-nonce')[0].content
})
});
});
This sends the nonce from the meta tag to the server in the form of a nonce parameter.
You may need to remove remote: true from your link for this to work. And of course, this script will itself need to be 'nonced' or else it won't run!
Assign the nonce to a #nonce instance variable in the controller:
#nonce = params[:nonce]
Wherever you render scripts, do:
<%= javascript_tag nonce: #nonce || true do %>
...
For those wondering how to get the same to work with their existing asynchronous forms:
Add this form field: <%= hidden_field_tag :nonce %>
On form submit, assign the nonce from the meta tag to the hidden field:
document.getElementById('id_of_submit_button').addEventListener('click', async e => {
document.getElementById('nonce').value = document.getElementsByName('csp-nonce')[0].content;
});
In this case, you don't want to prevent the default behavior on the event because you want the form to submit.
Then continue with step 2 above (assigning the nonce to a controller instance variable).
I hope as a general strategy this is useful to some. And I hope it can serve as inspiration for how to get the .js.erb file itself to run.
UPDATE: Of course, for your specific (but limited) use case, you could simply return the object's service id as part of some JSON object you return to the client instead of rendering a .js.erb template. I say "limited" because this won't work for people who really need to render templates.
If you did want to render your .js.erb file, I suspect something like this could work for your case as well, where instead of checking whether the HTTP_TURBOLINKS_REFERRER header is present, you check for request.xhr?. Just know that starting in newer Rails versions, remote: true doesn't set the requisite header for request.xhr? to work anymore. But since you're on 5.2.1, it may work for you.
Here's what I'm trying to do:
The user pastes a URL.
The input box that the user pastes in has an :onpaste that triggers urlPasted() function.
urlPasted() function submits the form that input box is in, which does an AJAX call to a custom function named lookup_profile.
In the controller, lookup_profile function does some web requests, and then updates some instance variables.
Once those variables are updated (takes ~5 seconds), the view has a function that waits 20 seconds and updates textboxes on the modal with the results of those instance variables.
Here's what I have thus far in the view:
<%= form_tag url_for(:controller => 'users', :action => 'lookup_profile'), id: "profileLookupForm", :method => 'post', :remote => true, :authenticity_token => true do %>
<div class="form-group row">
<div class="col-sm-12">
<%= text_field_tag "paste_data", nil, onpaste: "profileURLPasted();", class: "form-control"%>
</div>
</div>
<% end %>
<script type="text/javascript">
function profileURLPasted() {
// Once the user pastes data, this is going to submit a POST request to the controller.
setTimeout(function () {
document.getElementById("profileLookupForm").submit();
}, 100);
setTimeout(function () {
prefillForm();
}, 20000);
};
function prefillForm() {
// Replace company details.
$('#companyNameTextBox').val("<%= #company_name %>");
};
</script>
Here's what the controller looks like:
def lookup_profile
# bunch of code here
#company_name = "Random"
end
Now here's the problem I have. When the user pastes the data, it submits perfectly to the custom_action lookupProfile. However, after lookupProfile runs its code, rails doesn't know what to do afterwards. By that, I mean it gives me this error:
Users#lookup_profile is missing a template for this request format and
variant. request.formats: ["text/html"] request.variant: []
When in fact, I actually have a file at views/users/lookup_profile.js.erb. For some reason, it's trying to render the HTML version. I don't know why.
Secondly, I've tried putting this in the controller towards the end:
respond_to do |format|
format.js { render 'users/lookup_profile'}
end
but that results in this error:
ActionController::UnknownFormat
Any help would be greatly appreciated. I just want the custom function to run, update the instance variables, and let me update the current form with that data.
Here's another stackoverflow reference of something similar I'm trying to do: Rails submitting a form through ajax and updating the view but this method doesn't work (getting the actioncontroller error)
* EDIT 1 *
Ok, so I fixed the ActionController error by replacing my form_tag with:
<%= form_tag(lookup_profile_users_path(format: :js), method: :post, :authenticity_token => true, id: 'profileLookupForm', remote: true) do %>
But now it's actually rendering the actual javascript into the view, and I don't want that. I simply want to be able to access the instance variables that were updated in the lookup_profile action, not display the view.
* EDIT 2 *
So I think my problem comes down to this: Placing a button in the form and submitting from IT is different than my javascript code that submits the form. If I can figure out what's up with that, then I think I may be in good shape.
You are mixing a few things there. First of all, instead of doing document.getElementById("profileLookupForm").submit() you should do an ajax request, I guess the submit() method ignores the remote: true directive from rails.
So, change the submission to:
form = getElementById("profileLookupForm");
$.post(form.action, {paste_data: this.value}, 'script')
// form.action is the url, `this` is the input field, 'script' tells rails it should render a js script
That way the request is done async and the response does not replace the current page.
Now, what I think you are mixing is that #company_name won't change with that ajax request. When you render the form and everything else, #company_name is replaced with the actual value IN THAT MOMENT and will not change after your post request since the reference is lost. So this line:
$('#companyNameTextBox').val("<%= #company_name %>");
will be
$('#companyNameTextBox').val("");
al the time.
What you want is to respond with a script that updates the field with the value that you set to #company_name (also, waiting arbitrarilly X seconds is a really bad practice).
So, instead of responding with:
format.js { render 'users/lookup_profile'}
create a view lookup_profile.js with the code that you want to execute
$('#companyNameTextBox').val("<%= #company_name %>");
here, #company_name will actually be the value obtained with those requests you told before, the script is generated at the moment and excecuted as a response of the request.
I'm confused about remote:true in Rails forms, I thought some Javascript was required to make it asynchronous but this just seems to break my page.
Here is a really simple index.html.haml that includes a partial to show all appointments:
%h1 Calander
%h2 AppointmentsController
%h3 Make a new appointment
= form_for #appointment, remote: true do |f|
= f.text_field :title
= f.text_field :appt_time
= f.submit 'Make appointment'
#appointments
=render 'appointments'
Here is the previously mentioned partial:
-#appointments.each do |a|
%h3= a.title
%p= a.appt_time
Controller methods for index and create:
def index
#appointments = Appointment.order('appt_time ASC')
#appointment = Appointment.new
end
def create
#appointmet = Appointment.create(appointment_params)
redirect_to :root
end
Now this works fine. I can add a new appointment, hit submit and the new appointment shows up without the page refreshing, I think because I have included remote: true. So do I need to add anything else to handle the request? Am I violating best practices by not including something to handle this request and relying entirely on remote: true?
Nothing more required unless you want some callback after ajax call. You did not break any conventions. You can read this document to get ride of confusion.
Let's take a step back.
Web applications can respond to different request formats. Rails has built-in format handling.
So a request might ask for index via HTML, which response with an HTML file. It might also request index via JSON, XML, PDF or even JavaScript.
Whenever you add remote: true you are telling your form make a POST request via JS instead of HTML.
In your views you will have a bunch of HTML.ERB files. These views are request responses.
So to handle a JS request to index, you will need a app/views/appointements/index.js file.
This will be sent as the response to the request and the browser will know what to do with a JS response.
In index.js you can write JS that will be executed once the response is received.
You can also load partials into the page.
For example:
# app/views/appointements/index.js
$('#appointements').html('<%= j render "appointements" %>')
Which will render the partial content as a JavaScript string for the response.
http://guides.rubyonrails.org/working_with_javascript_in_rails.html
I have the following haml code:
%input{:value => "", :type => "button",:class => "SendBtn", :onclick => "$.get('#{send_path}',{parameter:$('#parameter').val()}); "}
This input executes an event in the controller.
// This is my controller
def send
if request.xhr?
// do stuff
end
end
But my js code in the corresponding .js.erb file is not being executed. It is returned as the response of the get request.
// send.js.erb
alert('hello');
How is the rails way to have this code executed?
Your problem is not Rails related, it's jQuery. With the get method you are just fetching more or less plain text. This will not get executed. You could do an eval on the text but there is a better way. Use the getScript method from jQuery. This will fetch and execute your code.
As a side note, there are two things that are bothering me in your code:
You are using inline JavaScript. try to remove this by using a data- attribute for your send path, like this data: { sendPath: send_path }, and retrieving it with $(yourInput).data('sendPath') in your application.js file.
From my personal view I do not like to put executing JavaScript code in ERB templates. I find that this fragments the front end logic of my app. For me it worked better to put the logic in .js files and communicate with the server over JSON.
As #topek said, you have to use $.getScript. Also in your situation better approach is to use button_to with :remote => true property instead of plain input.
<%= button_to "Do Something",
{ :controller => :somecontroller, :action=> :something },
{ :remote => true }
%>
Also you can pass attributes to button_to (but you have add parameter to your route definition).
<%= button_to "Do Something",
{ :controller => :somecontroller, :action=> :something, :param => #object.id },
{ :remote => true } %>
Here goes documentation for button_to: http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-button_to
I'm using Rails 3.1.1
I have the following in a haml view:
= form_for booking.notes.build, :remote => true do |f|
= f.text_area(:content)
= f.hidden_field(:noteable_id)
= f.hidden_field(:noteable_type)
= f.submit('Add note')
Which creates new notes on submission. Also the response from my controller is appearing correctly in a Chrome console (Network tab). But I cannot seem to grab the response.
I want to update the note list on the page after submission. I've been trying to bind to the ajax response so I can grab the response, but I am failing. For example, I think this should work but does not:
$('#new_note').bind('ajax:success', function() {
alert('Hi');
});
But no alert is triggered. Which I think explains why this also doesn't work.
$('#new_note').bind("ajax:success", function(evt, data, status, xhr){
// Insert response partial into page below the form.
$(this).parent.append(xhr.responseText);
})
Can you please point me as to what might be going wrong?
Did you try 'ajax:complete'?
Other things that can go wrong here:
Status code was not really "successful". This triggers success in jQuery
if ( status >= 200 && status < 300 || status === 304 ) {
Or the event handler was evaluated before the form was rendered. Try event delegation:
$("body").on('ajax:success', '#new_note', function(){...})
(careful, this is the new jQuery syntax. If using old jQuery, adjust accordingly)
if you want, you can put your javascript in create.js.erb (code in this file will be executed after response will come to your browser)
And in this file you can use if statement, like
<% if #ok %>
//your code
<% end %>
if in your controller's action set #ok to false the response will be empty!
This is generally done by doing a create.js.erb file in your controller's view section (if haven't done so already) in which you have access to whatever variables come out of the create action, and there you can render your html
in your create.js.erb file you could write something like
$("#new_note").html('<%= escape_javascript(render partial: "path/to/partial") %>');
read more in this post I wrote some time ago, it pretty much explains the whole flow