dynamically set value of textfield rjs rails - rjs

I am trying to set the value of the hidden text field through rjs. I have a form.
<% form_tag :action => "upload" do %>
<%= file_field_tag :zipfile %>
<%= submit_tag "Upload" %>
<%= hidden_field_tag "progress" %>
<% end %>
I want to set the value of the hidden text field according to the id of the progress that will be created when the browse button is clicked.
<script>
$(document).ready(function() {
$("input#zipfile").change(function() {
$.ajax({
url: "/progress_create",
type: "GET"
})
});
})
</script>
progress_create is as follows:
def progress_create
#progress = Progress.create(:value => 0)
respond_to do |format|
format.js {}
end
end
I think I am doing something in progress_create.js.rjs file which is as follows:
page<< %{
$('#progress').val("<%= #progress.id %>");
}
I want to set the value of the hidden field as id of the #progress. But, when I do the above, the value of the hidden field is "<%= #progress.id %>" string, not the exact id. Can anyone please correct me!

page << "$('#progress').val(#{#progress.id});"
This should work. cheers

Related

Using wicked_pdf, save as pdf including user supplied data

I have a template to be filled out by a user. My goal is to convert the template into a pdf (containing information supplied by the user) using wicked_pdf.
Also, none of the user input is hitting the model/database. I simply need to convert the template to a pdf containing the user's data, nothing more.
So far, I can convert the template to a pdf, save it and redirect back to my index view. However, none of the fields filled in by the user are saved; all fields that were containing input or values typed by the user are blank. It's simply saving a blank template. How can I convert a pdf and user supplied data to a pdf using wicked_pdf?
# controller save method --->
def save_grade_sheet
#result = Result.find(params[:id])
if current_user.admin?
filename = "#{#result.user.last_name}_grades.pdf"
save_path = "#{Rails.root}/public/uploads/#{#result.user.last_name}/#{filename}"
respond_to do |format|
pdf = render_to_string pdf: filename,
template: "/results/grade_sheet.html.erb",
encoding: "UTF-8",
disposition: "attachment",
save_to_file: save_path,
save_only: true
File.open(save_path, "wb") do |file|
file << pdf
end
flash[:notice] = "#{filename} successfully saved"
format.html { redirect_to results_path }
end
else
head :unauthorized
end
end
# sample template code
<div>
<div>
<h2>PERSONNEL INFORMATION</h2>
<p>Examinee's Name: <%= #result.user.first_name %> <%= #result.user.last_name %></p>
<p>Examiner's Name: <input class="inline" type="text"></p>
</div>
<div>
<p>Exam Type: <%= #result.test.upcase %></p>
<p>Exam Version: <input class="inline" type="text"></p>
<p>Exam Date: <%= #result.created_at.strftime("%m-%d-%y") %></p>
</div>
<%= button_to "Create Grade Sheet", save_grade_sheet_result_path(#result), data: { method: :post }, class: "btn btn-primary btn-lg"%>
</div>
I was sending everything to the correct route, but none of the data was actually being passed. Instead, I needed to wrap everything in a form_tag and use a submit_tag.
<%= form_tag(save_grade_sheet_result_path(#result), method: :post) %>
<div>
<h2>PERSONNEL INFORMATION</h2>
<p>Examiner's Name: <%= text_field_tag :examiner_name, #examiner_name, class: "inline" %></p>
<p>Exam Version:<%= text_field_tag :exam_version, #exam_version, class: "inline" %></p>
</div>
<%= submit_tag "Create Grade Sheet", class: "btn btn-primary btn-lg" %>
<% end %>
And in my controller, I needed to grab the params passed in:
def save_grade_sheet
#result = Result.find(params[:id])
#examiner_name = params[:examiner_name]
#exam_version = params[:exam_version]
if current_user.admin?
# existing code
end
end

Else part is not working in Rails ajax form

I have a Rails ajax form to submit.When user will give the correct data it will search the database and do the operation accordingly.If user is giving the Wrong data it should display user to alert message.But it is not happening like that.
I am explaining my codes below.
home.html.erb
<% if current_admin %>
<p class="flash-message"><%=flash[:notice]%></p>
<div class="col-md-6" style="float:none; margin:auto;">
<%= form_for :sdf ,:url => {:action => "scan_report" },remote: true do |f| %>
<% if params[:receipt_no] %>
<div class="input-group bmargindiv1 col-md-12"> <span class="input-group-addon text-left">Receipt No. Scan :</span>
<%= f.text_field :Receipt_No,:class => "form-control", :value => params[:receipt_no] %><%= f.submit "Scan Report" %>
</div>
<% else %>
<div class="input-group bmargindiv1 col-md-12"> <span class="input-group-addon text-left">Receipt No. Scan :</span>
<%= f.text_field :Receipt_No,:class => "form-control",placeholder:"Receipt No. scan" %><%= f.submit "Scan Report" %>
</div>
<% end %>
<% end %>
<% end %>
controller/homes_contorller.rb
class HomesController < ApplicationController
def home
#sdf=TSdf.new
respond_to do |format|
format.html
format.js
end
end
def scan_report
if #sdf=TSdf.find_by_Receipt_No(params[:sdf][:Receipt_No])
if #sdf && #sdf.HCSY_Status=='YES'
#hcsy=THcsy.find_by_Sdp_Id(#sdf.Sdp_Id)
#hcsy_deatils=THcsyDetails.find_by_HCSY_ID(#hcsy.id)
#woods=THcsyFundTypeMaster.find_by_Fund_Type_Code(1)
#burn=THcsyFundTypeMaster.find_by_Fund_Type_Code(2)
#good=THcsyFundTypeMaster.find_by_Fund_Type_Code(3)
#swd=THcsyFundTypeMaster.find_by_Fund_Type_Code(5)
#photo=THcsyFundTypeMaster.find_by_Fund_Type_Code(6)
end
else
flash[:notice]="Not Found"
end
end
end
In this form its only taking the correct input but if user is trying to give the wrong input the else part is not executing.Please help me to resolve this error and let me to know how can i make this ajax call in below format.
$('form').submit(function() {
var valuesToSubmit = $(this).serialize();
$.ajax({
type: "POST",
url: $(this).attr('action'), //sumbits it to the given url of the form
data: valuesToSubmit,
dataType: "JSON" // you want a difference between normal and ajax-calls, and json is standard
}).success(function(json){
console.log("success", json);
});
return false; // prevents normal behaviour
});
Please help me.I am using Rails version 3.2.19.
Here you send AJAX POST request to scan_report, and if it is successful it should render template scan_report.js.erb, and rendered template will appear in json variable in success callback.
But if params are not valid, the same template is rendered, but all instance variables are missing. And probably empty json is returned or an error appears in log.
Anyway, if you'd like to change flash in remote form, you should put custom code in fail callback. Something like
$("#flash").html('<%= j render flash[:notice] %>');

Value is not submitting in using Rails ajax form

I want to store value in db using Rails ajax form but it is not storing anything.Please let me to know where i did the mistake and help me to resolve this issue.
I am explaining my code below.
users/index.html.ebr:
<script type="text/javascript">
$('form').submit(function() {
var valuesToSubmit = $(this).serialize();
console.log('hello')
$.ajax({
type: "POST",
url: $(this).attr('create'), //sumbits it to the given url of the form
data: valuesToSubmit,
dataType: "JSON" // you want a difference between normal and ajax-calls, and json is standard
}).success(function(json){
console.log("success", json);
});
return false; // prevents normal behaviour
});
</script>
<p><%= flash[:notice] %></p>
<%= form_for :user do |f| %>
<p>
Name : <%= f.text_field :name,placeholder:"Enter your name" %>
</p>
<p>
Email : <%= f.email_field :email,placeholder:"Enter your email" %>
</p>
<p>
Content : <%= f.text_field :content,placeholder:"Enter your content" %>
</p>
<p>
<%= f.text_field :submit,:onchange => "this.form.submit();" %>
</p>
<% end %>
<div id="sdf-puri" style="display:none" >
</div>
controller/users_controller.rb
class UsersController < ApplicationController
def index
#user=User.new
respond_to do |format|
format.html
format.js
end
end
def create
#user=User.new(params[:user])
if #user.save
flash[:notice]="user created"
end
end
end
create.js.erb
$("#sdf-puri").css("display", "block");
$("#sdf-puri").html("<%= escape_javascript (render 'table' ) %>");
$("#sdf-puri").slideDown(350);
create.html.erb
<%= render 'table' %>
_table.html.erb
<table>
<tr>
<th>Name :</th>
<th>Email :</th>
<th>Content :</th>
</tr>
<% #user.each do |user| %>
<tr>
<td><%= user.name %></td>
<td><%= user.email %></td>
<td><%= user.content %></td>
</tr>
<% end %>
</table>
After submit value should display in same index page.Please help me.
Rails has a built in Ajax system, on your form you need to add remote: true
form_for(#user, remote: true) do |f|
This tells rails to submit the form using Ajax under the hood... You don't need all of the script above the form
Your controller already correctly has the line:
responds_to js
So all you would do is have a create.js file in your views/user folder that handled your return Ajax stuff such as appending or fading etc
you need to add remote: true in form tag

How to use properly use a search function and json parser?

In my view I have
<%= form_tag searches_path, method: 'get', do %>
<p>
<%= text_field_tag :search %>
<%= submit_tag "Search", name: nil %>
</p>
<% end %>
and in my controller I have
class SearchesController < ApplicationController
def index
raw_result = params[:search]
result = raw_result.gsub(/\s+/, "+")
movie_details = HTTParty.get("http://imdbapi.org/?title="+result+"&type=json")
#searches = ActiveSupport::JSON.decode(movie_details)
end
end
When I visit the view I get a undefined method `gsub' for nil:NilClass. I'm guessing because the form hasn't been submitted. Am I implementing the json parser correctly?
raw_result = params[:search] || "default value"

Rails 3 & Ajax date_select onchange => submit

I'd like my date to get saved anytime I change my date via ajax, is this possible? I tried
<%= form_for #dates,:remote => true do |f| %>
<%= f.date_select :booking_date,:onchange => "this.form.submit();" %>
<% end %>
but it does nothing, any good work arounds?
From the rails documentation:
date_select(object_name, method, options = {}, html_options = {})
Because onchange is an html option you need to provide an empty set of options to date_select, otherwise it assumes onchange is a date_select option.
You should change your call to date_select to look like this:
f.date_select :booking_date, {}, :onchange => "this.form.submit();"
Are you including this in your layout:
<%= javascript_include_tag :defaults %>
<%= csrf_meta_tag %>

Resources