rails ajax request doesn't work - ajax

I have some problem with ajax
This request GET http://localhost:3000/projects/new (304 Not Modified) does work, it executes javascript from response:
$('#add-project-button').hide();
$('#project-form').append("<form accept-charset=\"UTF-8\" action=\"/projects\" class=\"new_project\" data-remote=\"true\" id=\"new_project\" method=\"post\"><div style=\"margin:0;padding:0;display:inline\"><input name=\"utf8\" type=\"hidden\" value=\"✓\" /><input name=\"authenticity_token\" type=\"hidden\" value=\"gzu9DETiVV8N+OtRnkdYpD6aa0/RbM7i2H+nkQ0yXGc=\" /><\/div>\n <div class=\"field\">\n <label for=\"project_name\">Name<\/label><br />\n <input id=\"project_name\" name=\"project[name]\" size=\"30\" type=\"text\" />\n <\/div>\n <div class=\"actions\"><input name=\"commit\" type=\"submit\" value=\"Create Project\" /><\/div>\n<\/form>");
But another request POST http://localhost:3000/projects (200 OK) seems ok but response is empty, no javascript is executing, but the server answer is ok:
Rendered tasks/_task.html.erb (0.0ms)
Rendered projects/_project.html.erb (4.5ms)
Rendered shared/_create.js.erb (5.4ms)
Rendered projects/create.js.erb (6.1ms)
Completed 200 OK in 96ms (Views: 8.6ms | ActiveRecord: 84.9ms)
So I'm guessing that the browser somehow is of not supposed to execute javascript from server in this case.
What might be a problem? How to make browser receive the javascript and execute it? Thanks.
UPDATE: The form which is making ajax request:
<%= form_for(#project, :remote => true) do |f| %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="actions"><%= f.submit %></div>
<% end %>
The controller action:
def create
#project = current_user.projects.build(params[:project])
respond_with(#project.tap(&:save))
end
Maybe the problem is causing by using partial as layout, projects/create.js.erb:
<% render :layout => '/shared/create', locals: { obj: #project } do %>
$('#project-container').append("<%= escape_javascript render(#project) %>");
$('#add-project-button').show('fast');
$('#project-form').hide('fast', function(){ $('#project-form').empty(); });
<% end %>

The problem was very simple, I forget to put <%= sign in erb, so it should be:
<%= render :layout => '/shared/create', locals: { obj: #project } do %>
$('#project-container').append("<%= escape_javascript render(#project) %>");
$('#add-project-button').show('fast');
$('#project-form').hide('fast', function(){ $('#project-form').empty(); });
<% end %>

Related

Ruby on Rails Ajax with Remote Forms

Hello when I add the comment in my application in the form that I have with ajax, I have to reload the browser to upload the comment. In the browser I get this error that I supposedly have in this file:
(function() {
$(document).on("ajax:success", "form#comments-form", function(ev, data) {
console.log(data);
$(this).find("textarea").val("");
return $("#comments-box").append("<li> " + data.body + " - </li>");
});
$(document).on("ajax:error", "form#comments-form", function(ev, data) {
return console.log(data);
});
}).call(this);
I have this file in comments.coffe like this:
$(document).on "ajax:success", "form#comments-form", (ev,data)->
console.log data
$(this).find("textarea").val("")
$("#comments-box").append("<li> #{data.body} - </li>")
$(document).on "ajax:error", "form#comments-form", (ev,data)->
console.log data
If you can help me, I thank you.
I had the same problem and, solve it by doing the following
In the folder app/asset/javascripts/application.js look for the next line
//= require rails-ujs and change for // require rails-ujs
In this way that library is not called and will not generate conflict with jquery.
I hope it helps you
<%=
form_for([#article,#comment], remote: true, html: { id: "comments-form", :"data-
type" =>
"json" }) do |f| %>
<% if #comment.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(comment.errors.count, "error") %> prohibited this comment
from
being saved:</h2>
<ul>
<% comment.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :body %>
<%= f.text_area :body %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% 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

Rails 3 Endless page, will_paginate with other AJAX on page

I am using twitter bootstrap and will_paginate. I have a laptop MVC with an index function which displays all of the laptops in the database. I also have a hidden form on the page which allows the user to input a price range and only laptops in that price range are showed, via an AJAX call. I am trying to follow the Railscast Episode #114 (revised), but the code conflicts with the price range stuff, and I'm not sure how to fix it. Code below:
index.js.erb
$("#laptops").html("<%= escape_javascript(render(#laptops)) %>");
$("#laptops").append('<%= j render(#laptops) %>');
$('.pagination').replaceWith('<%= j will_paginate(#laptops) %>');
laptops.js.coffee
jQuery ->
if $('.pagination').length
$(window).scroll ->
url = $('.pagination .next_page').attr('href')
if url && $(window).scrollTop() > $(document).height() - $(window).height() - 100
$('.pagination').text('Fetching more results...')
$.getScript(url)
$(window).scroll
index.html.erb
<div id="hidden_form">
<%= form_tag laptops_path, :method => :get, :remote => true do %>
<%= hidden_field_tag "min_price", params[:min_price] %>
<%= hidden_field_tag "max_price", params[:max_price] %>
<%= submit_tag "Get Laptops", class: "btn btn-primary", :name => nil %>
<% end %>
</div>
<div class="laptops" id="laptops">
<%= render #laptops %> <%#use :locals => ... to send other vars to partial%>
</div>
<%= will_paginate %>
Laptops Controller:
#laptops = Laptops.search(min,max).paginate(page: params[:page], per_page: 10)

Form validation after ajax request

I'm using Rails 3.2 and I'm making my first Ajax request.
This is my code:
def create
#post = Post.find(params[:post_id])
#comment = Comment.new(params[:comment])
respond_to do |format|
if #comment.save
format.html {
redirect_to #post
}
format.js
else
format.html {
render 'posts/show'
}
format.js
end
end
end
So, I understand that I return a js template.
So, question 1: Is really a good idea to use this approach instead the standard sending json / receiving json in a $.ajax call?
My create.js.erb:
$(".commentlist").append("<%= escape_javascript(render(:partial => #comment)) %>");
Working perfectly.
But... how I validate the form? (Without ajax works perfectly).
I'm seeing that the js.erb is like the html.erb but with js instead of html (I still see this weird, I think that is easier to use controller.coffee, but I will learn this way too :)).
So question 2: How I validate ? I see that what I get in the ajax call is the entire html and my two action vars (#post and #comment).
Just that, I need to learn the Rails approach to do ajax :)
P.S: My _form.html.erb:
<%= form_for comment, :url => post_comments_path(comment.post), :remote => true do |f| %>
<% if comment.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(comment.errors.count, "error") %> prohibited this comment from being added:</h2>
<ul>
<% comment.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.hidden_field :post_id %>
<p>
<%= f.label :name %>
<%= f.text_field :name %>
</p>
<p>
<%= f.label :email %>
<%= f.text_field :email %>
</p>
<p>
<%= f.label :url %>
<%= f.text_field :url %>
</p>
<p>
<%= f.label :content %>
<%= f.text_area :content %>
</p>
<p class="no-border">
<%= f.submit "Post", :class => "button" %>
</p>
<% end %>

Resources