I'm interested in using the jQuery UI autocomplete plugin in my Rails app. The number of possible values will be small, so I wanted to store them client-side. So I have my controller set up as follows:
def index
#tags = Tag.find(:all).map { |t| t.name }
end
And in my view:
var tags = <%= #tags %>
The problem is that this renders as:
var tags = ["tag1","tag2"];
Instead of:
var tags = ["tag1","tag2"]
What do I need to do differently in order to stop escaping those quotes inside my tag array?
What about:
var tags = <%=raw #tags %>;
EDIT:
in your controller
#tags = Tag.find(:all).map(&:name).to_json
in your view:
var tags = <%= #tags %>;
It's the same as what you presented but you're sure it's valid and sure (because escaped) json (+ the query is improved).
I'm still questioning about the XSS + raw...
I was able to solve this by changing my view code to:
<%= array_or_string_for_javascript(#tags) %>
The thing missing in your controller is html_safe - here is an example:
controller
#keys = #categories.map { |x| x.name }
#autocomplete_categories = #keys.to_json.html_safe
view:
<script type="text/javascript">
$(document).ready(function() {
var data = <%= #autocomplete_categories %>;
$("#auto").autocomplete( { source: data } );
});
</script>
Related
I am trying to render a partial upon change in the drop down list.
There is the onchange javascript function which directs to a link to display the corresponding form.
But here I am getting a #<ActionController::UnknownFormat: ActionController::UnknownFormat> error inside the get_template method in controller.
I suppose it is something to do with calling the link through javascript, as the request is processed as HTML.
Processing by XYZController#get_template as HTML
How to process it as JS ?
Here's the detailed code.
dropdown.html.erb
<div id="requests_dropdown">
Choose the type of request : <%= select_tag 'drop_request_id', options_for_select(#request_types.map{|x| [x[:name], x[:id]] } ) %>
</div>
Javascript
<script>
$('#drop_request_id').on('change', function() {
var request_type_id = $('#drop_request_id').val();
var href = 'get_template/' + request_type_id ;
window.location = href;
});
</script>
controller
def get_template
#request_type = [x,y,z]
respond_to do |format|
format.js
end
end
get_template.js.erb
$("#request_form_partial").html("<%= escape_javascript(render partial: 'request_form', locals: { request_type: #request_type } ) %>");
You need to call your method via ajax.
You are getting error because you are trying to GET the html format,whereas your method renders the js format response.
Please edit your code to following:
<script> $('#drop_request_id').on('change', function() {
var request_type_id = $('#drop_request_id').val();
var href = 'get_template.js/' + request_type_id ;
$.get(href);
});
</script>
In my rails app I have a dropdown menu that a user can select an account to make a payment to:
//_payment.html.erb
<div class="field" id="payment-to-account">
<%= f.label 'Payment To:' %><br>
<%= f.collection_select :to_account_id, #liability_account_payment_list, :id, :account_details, {include_blank: 'Please Select'} %>
</div>
When the user selects a account I render a partial inside of this form based on their selection:
//_payment.html.erb
<%= form_for(#transaction,
as: :transaction,
url:
#transaction.id ? account_transaction_path(#account, #transaction) : account_transactions_path) do |f| %>
...
<% #f = f %>
<div id="to-account-form" style="display:none;"></div>
...
<script>
jQuery(function(){
$("#payment-to-account").change(function() {
var selected_item = $( "#payment-to-account option:selected" ).text();
var selected_item_index = $( "#payment-to-account option:selected" ).index();
//looks for account type in parentheses followed by space moneysign " $"
var regExp = /\(([^)]+)\)\s\$/;
var matches = regExp.exec(selected_item);
// array of account ids in order of list
var payment_account_ids = <%= raw #payment_list_ids %>;
switch (matches[1]) {
case 'Mortgage':
$('#to-account-form').html("<%= j render 'payment_to_mortgage', f: #f %>");
$('#to-account-form').slideDown(350);
break;
case 'PersonalLoan':
case 'CreditCard':
case 'StudentLoan':
case 'OtherLiability':
$('#to-account-form').html("<%= j render 'payment_to_all_other_liabilities', f: #f %>");
$('#to-account-form').slideDown(350);
break;
default:
$('#to-account-form').html("<br>" + "Contact support, an error has occurred");
$('#to-account-form').slideDown(350);
}
});
});
</script>
Right now it renders the correct partial based on the selection, but when that partial loads I need more information from the account model. I created a method called find_pay_to_account that take the input selected account id in the Accounts model that looks for the account based on the id.
When the user selects and account from the drop down, I'd like that method called on the partial that is loaded so I can show the user additional information about the account they are making a payment to before they submit the form. But I don't know how. I wanted to add something like this to my jQuery switch statement.
selected_account_id = payment_account_ids[selected_item_index-1]
#payment_to_account = Account.find_pay_to_account(selected_account_id)
Since rails preloads the partials in the background, making the following change to my partial render in the case statements still wont work:
From this
$('#to-account-form').html("<%= j render 'payment_to_mortgage', f: #f %>");
To this
$('#to-account-form').html("<%= j render 'payment_to_mortgage', f: #f, #payment_to_account: #payment_to_account %>");
I did some searching and found that with AJAX might be able to help:
Pragmatic Studio
Rails Cast
But i'm trying to access the model, not the controller and I'm trying to update a form partial. What is the correct way to do this?
Here are pics that show the user flow. An example of what I'm trying to update can be seen in the last pic. When the mortgage account is selected, it needs to show the minimum payment for the mortgage account. Right now it says zero because the partials rendering with all the information from BOA seed 0214.
If you want to access record information from your model inside of front-end javascript you will indeed want to setup a small api to query the database for that information. In ajax it would be something like this
function processDataFunction(data){
console.log(data)
}
$.ajax({
type: "GET",
dataType: "json",
url: "/some-path/:some_id",
success: processDataFunction(data){}
});
#config/routes.rb
Rails.application.routes.draw do
get "/some-path/:some_id", to: "some_controller#some_view", :defaults => { :format => :json }
end
#app/controllers/some_controller.rb
class SomeController < ApplicationController
def some_view
#some_records = SomeModel.find_by_id(params[:some_id])
respond_to do |format|
format.json { render json: #some_records }
end
end
end
To access the information in the rendered partial without making another controller action, I collected all data I might need in the original action. That way I could get the exact result I was looking for without changing my routes and doing ajax request.
To do this I added methods to the controller new action. You can see from my original question, all accounts I may need information for are in the variable that is in the dropdown menu:
#liability_account_payment_list
This is where the dropdown menu gets its information from
That variable is in the Transaction controller new action. So I created another variable storing an array on the line after the above variable:
#liability_accounts_payment_list_minimum_payments = #liability_account_payment_list.map {|account| account.minimum_payment.to_f + account.minimum_escrow_payment.to_f}
This new variable is an array of all the accounts minimum payments in the order they are listed in the dropdown menu the user will select from.
Then I changed the jQuery on the page to the following
//_payments.html.erb
<script>
jQuery(function(){
$("#payment-to-account").change(function() {
var selected_item = $( "#payment-to-account option:selected" ).text();
var selected_item_index = $( "#payment-to-account option:selected" ).index();
//looks for something in parentheses followed by space moneysign " $"
var regExp = /\(([^)]+)\)\s\$/;
var matches = regExp.exec(selected_item);
// array of minimum payments from accounts in list converted from ruby to js
var min_payments = <%= raw #liability_accounts_payment_list_minimum_payments %>;
// set the js variable to the appropriate minimum payment
var selected_account_min_payment = min_payments[selected_item_index-1];
switch (matches[1]) {
case 'Mortgage':
$('#to-account-form').html("<%= j render 'payment_to_mortgage', f: #f %>");
$("#min-payment-field-hidden").val(selected_account_min_payment);
$("#min-payment-field").html(selected_account_min_payment);
$('#to-account-form').slideDown(350);
break;
case 'PersonalLoan':
case 'CreditCard':
case 'StudentLoan':
case 'OtherLiability':
$('#to-account-form').html("<%= j render 'payment_to_all_other_liabilities', f: #f %>");
$("#min-payment-field-hidden").val(selected_account_min_payment);
$("#min-payment-field").html(selected_account_min_payment);
$('#to-account-form').slideDown(350);
break;
default:
$('#to-account-form').html("<br>" + "Contact support, an error has occurred");
$('#to-account-form').slideDown(350);
}
});
});
</script>
The lines that have min-payment-field-hidden are because setting two different divs with the same id does not work. One div is being used to set hidden_field, the other is showing the user what the value is.
//_payment.html.erb
<-- To make sure the appropriate minimum payment is submitted to controller -->
<%= f.hidden_field :amount, :id => "min-payment-field-hidden" %>
<div>
<%= f.label "Minimum Payment" %>
<div id="min-payment-field"></div>
</div>
If you look at my switch statement, you can see I set the above value with these lines:
$("#min-payment-field-hidden").val(selected_account_min_payment);
$("#min-payment-field").html(selected_account_min_payment);
Now the user can see the minimum payment for the specific account they choose from the dropdown.
I want to store mysql strings in a javascript array variable. I am using jsp for server-side.
I tried it in three ways. All the three aren't working. Need some help.
Attempt-1:
<script>
var name = [];
<%
st=con.prepareStatement("select name from company");
rs=st.executeQuery();
while(rs.next()){
String s = rs.getString(1);
%>
name.push(<%=s%>);
<%
}
%>
</script>
Attempt-2:
<script>
var name = [];
<%
st=con.prepareStatement("select name from company");
rs=st.executeQuery();
while(rs.next()){
%>
name.push(<%=rs.getString(1)%>);
<%
}
%>
</script>
Attempt-3:
<script>
var name = [];
<%
st=con.prepareStatement("select name from company");
rs=st.executeQuery();
while(rs.next()){
%>
name.push(<%out.print(rs.getString(1));%>);
<%
}
%>
</script>
All the three attempts showed the same result and error after processing.
Interpreted Code:
<script>
var name = [];
name.push(tcs);
name.push(wipro);
</script>
Error:
ReferenceError: tcs is not defined
You should add " around your string also you should javascript encode it(I think apache has a library that will do this for you):
<script>
var name = [];
<%
st=con.prepareStatement("select name from company");
rs=st.executeQuery();
while(rs.next()){
String s = StringEscapeUtils.escapeJavaScript(rs.getString(1));
%>
name.push("<%= s %>");
<%
}
%>
</script>
Try using this Apache library to escape the java string based on javascript rules: StringEscapeUtils
Javascript is trying to interpret name.push(tcs); tcs as a variable which in this case tcs has not been declared or initialized it is undefined. Instead you want javascript to interpret tcs as a string so you need quotes around it "tcs" or in your case "<%= s %>".
I want to create a javascript map from a java map to set a dropdown value depending upon the value selected in another dropdown.
Below is the code(not working):
var categoryAndReportsMap = new Object();
<%
Map<String,Set<String>> categoryAndReportsJ = (Map<String,Set<String>>) request.getAttribute("categoryAndReports");
for(Map.Entry<String,Set<String>> e : categoryAndReportsJ.entrySet()){ %>
categoryAndReportsMap[ <% e.getKey(); %> ] = <% e.getValue(); %>;
<% } %>
Please suggest how can I achieve this.
You need quotes around the keys and values :
categoryAndReportsMap["<%= e.getKey() %>"] = "<%= e.getValue() %>";
But this supposes those strings don't contain quotes themselves. The best solution would be to use a JSON serializer like the excellent gson, this would be as simple as
var categoryAndReportsMap = <%= gson.toJson(categoryAndReportsJ) %>;
I'm trying to embed data I have defined in my controller in my view.
in view.html.erb:
<script>
some_var = <%= #var_data %>
some_ints = <%= #int_data %>
</script>
in my controller:
#var_data = ['hi', 'bye']
#int_data = [1,2,3,4]
however, when I view the generated html file, it looks like
<script>
some_var = ["hi", "bye"]
some_ints = [1,2,3,4]
</script>
ie the ints are fine but all the quotes got escaped. I tried
some_var = <%= #var_data.map {|i| i.html_safe} %>
instead but it didn't do anything (and also html_safe didn't work on the whole array). How should I do this?
Thanks
have you tried this?
<%=raw #var_data %>