handle Status Code:200 OK on ajax save form - javascript

I have the following HAML form:
.row
.col-lg-6
.panel.panel-default
.panel-heading
%h1.box-title
%i.fa.fa-calendar.fa-fw
Availability
.panel-body
= form_tag dashboard_kid_availabilities_url(current_kid), :method => 'post', id: "save-availability", remote: true do
.form-group
= _("Date")
= select_date(Time.now + 1.day, order: [:day, :month, :year])
%br
= _("Hour")
= select_hour(Time.now )
.form-group
= submit_tag _('Save'), class: 'btn btn-blabloo btn-xs'
With the following ajax request:
:javascript
$("#save-availability").submit(function () {
var availability_day = $("#date_day").val();
var availability_month = $("#date_month").val();
var availability_year = $("#date_year").val();
var availability_hour = $("#date_hour").val();
var calendar = $("#calendar").fullCalendar();
$.ajax({
url: $(this).attr('action'),
type: "POST",
data: {"date_day" : availability_day, "date_month" : availability_month, "date_year" : availability_year, "date_hour" : availability_hour},
success: function(result){
alert("salvada disponibilidad");
},
error: function(xhr, textStatus, error) {
console.log("Impossible to connect");
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
});
And this is the code of my controller:
def create
#availability = Availability.new()
#availability.availability_date = (params[:date][:day] + "/" + params[:date][:month] + "/" + params[:date][:year] + " "+ params[:date][:hour]).to_str
#availability.end_availability_date = (params[:date][:day] + "/" + params[:date][:month] + "/" + params[:date][:year] + " "+ (params[:date][:hour].to_i + 1).to_s).to_str
#availability.kid = current_kid
if #availability.save
flash[:notice] = 'Availability created successfully'
respond_to do |format|
format.json { render json: #availability.to_json, success: :ok, error: false }
end
else
flash[:error] = 'Availability not created'
end
end
Everything work great (the record is saved), but the success code on my javascript code it's never execute, instead the error code it's executed.
I'm getting this error on my console:
POST http:// localhost:3000/dashboard/kids/jean_oso/availabilities 500
(Internal Server Error) application.js?body=1:8707send
application.js?body=1:8707jQuery.extend.ajax
application.js?body=1:8137(anonymous function)
edit:1808jQuery.event.dispatch
application.js?body=1:5096elemData.handle application.js?body=1:4767
Impossible to connect edit:1816 Internal Server Error edit:1817 error
edit:1818 Internal Server Error
What I'm doing wrong.
Thanks in advance

Related

How to work with rails render with ajax javascript request

I have action in controller
def login
#message = params[:mess]
#user = 1
render :rend_log_form
end
the view - rend_log_form.js.erb
l = $("#log_form");
console.log(<%= #message %>);
l.html("<%= j(render(partial: 'login/log_form', locals: {user: #user})) %>");
and some javascript code
$.ajax({
type: "POST",
url: "/login",
data: {mess:"eee"},
success:function(data) {
console.log("SUCCESS POST");
console.log(data);
},
error:function(data) {
console.log("ERROR POST:");
console.log(data);
}
});
action and controller works ok if use link_to with remote: true, but with my javascript code I have in browser console:
ERROR POST:
Object
the Object.responseText - the code of rend_log_form.js.erb
How to render the form with javascript?
Thanks to Hary Bomrah, adding dataType:"html" to ajax call in js code has helped.

Defining routes in AJAX and Rails

Error I get: undefined variable article_id.
What I am trying to achieve : Define the correct route in AJAX and Rails.
What I need: The structure articles/1/comments/2.
Goal: Note that my goal is to only load comment using AJAX, not article.
In the AJAX script below what I currently have undefined is article_id, for which I wrote the following:
var getArticle = function () {
return $('.article-title').each(function() {
var article_id = $(this).data('article-id');
});
};
$(document).ready(getArticle);
AJAX:
var loadComment = function() {
return $('.comment-content').each(function() {
var comment_id = $(this).data('comment-id');
return $.ajax({
url: "/articles/" + article_id + "/comments/" + comment_id,
type: 'GET',
dataType: 'script',
error: function(jqXHR, textStatus, errorThrown) {
return console.log("AJAX Error: " + textStatus);
},
success: function(data, textStatus, jqXHR) {
return console.log("Worked OK!");
}
});
});
};
$(document).ready(loadComment);
$(document).on('page:change', loadComment);
Index:
- #articles.each do |article|
%article-title{ :class => "article-title", "data-article-id" => article.id }= article.title
- article.comments.each do |comment|
%comment-content{ :id => "comment-#{comment.id}" }
Add this to your routes.rb
resources :articles do
resources :comments
end
And add the following controller:
class CommentsController < ApplicationController
def show
#article = Article.find(params[:article_id])
#comment = #article.comments.find(params[:id])
render json: #comment
end
end
Running something like:
curl http://localhost:3000/articles/123/comments/456.json
will set the params[:article_id] to 123 and the params[:id] to 456, the id is intended to be used as a comment id.

ActionController::UnknownFormat in CareersController#create for rails 4

i am trying to intigrate js file for "success message" as pop up when I submit my form.
its says, ActionController::UnknownFormat in CareersController#create
In my controller:
def create
#career = Career.new(career_params)
respond_to do |format|
if #career.save
format.js {render :template => 'careers/create', :locals => { :career => #career} }
else
format.html { render :new, :locals => { :career => #career} }
end
end
end
and my create.js.erb file:
$(document).ready(function(){
$("#new_career").submit(function(e){
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
format: 'js',
success:function(data, textStatus, jqXHR)
{
alert("Form has been submitted");
},
error: function(jqXHR, textStatus, errorThrown){
alert("Network connection problem");
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
})
Here is my server Error log :
Started POST "/careers" for ::1 at 2015-06-15 21:54:32 +0600
Processing by CareersController#create as HTML
Parameters: {"utf8"=>"√", "authenticity_token"=>"3NOJnGQZsFuYtd4JdNGl4wVmIh7at3laQDfjYyp1iPxt/xUdokGqSaAQiWOb+zEh2yvrW6IE3CrnPXQhwBADTg==", "career"=>{"full_name"=>"mezbah", "email
"=>"mezbahalam26#gmail.com", "phone_number"=>"01742626262"}, "commit"=>"SUBMIT APPLICATION"}
(0.0ms) begin transaction
SQL (1.0ms) INSERT INTO "careers" ("full_name", "email", "phone_number", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?) [["full_name", "mezbah"], ["email", "mezbahalam26#gmai
l.com"], ["phone_number", "01742626262"], ["created_at", "2015-06-15 15:54:32.107023"], ["updated_at", "2015-06-15 15:54:32.107023"]]
(172.2ms) commit transaction
Completed 406 Not Acceptable in 178ms (ActiveRecord: 173.2ms)
ActionController::UnknownFormat (ActionController::UnknownFormat):
app/controllers/careers_controller.rb:21:in `create'
Rendered C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/actionpack-4.2.1/lib/action_dispatch/middleware/templates/rescues/_source.erb (1.0ms)
Rendered C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/actionpack-4.2.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (3.0ms)
Rendered C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/actionpack-4.2.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.0ms)
Rendered C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/actionpack-4.2.1/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (48.0ms)
Cannot render console with content type multipart/form-dataAllowed content types: [#<Mime::Type:0x42c5208 #synonyms=["application/xhtml+xml"], #symbol=:html, #string="text/html">, #<
Mime::Type:0x42c4458 #synonyms=[], #symbol=:text, #string="text/plain">, #<Mime::Type:0x4267e48 #synonyms=[], #symbol=:url_encoded_form, #string="application/x-www-form-urlencoded">]
what am i doing wrong ? please help
ActionController::UnknownFormat in CareersController#create
You have defined format as json instead js. Change it to like this
def create
#career = Career.new(career_params)
respond_to do |format|
if #career.save
format.js {render :template => 'careers/create', :locals => { :career => #career} }
else
format.html { render :new, :locals => { :career => #career} }
end
end
end
Update
You should also have to define format as js in your ajax
#create.js.erb
$(document).ready(function(){
$("#new_career").submit(function(e){
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
format: 'js', #here
success:function(data, textStatus, jqXHR)
{
alert("Form has been submitted");
},
error: function(jqXHR, textStatus, errorThrown){
alert("Network connection problem");
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
})

Use ajax to post back to same page

I would like to post the result of an ajax request back to the same page that it was requested from. Here are the interacting parts:
AJAX in Jquery
var ids = 1
$(document).ready(function(){
$('#showbtn').on('click', function() {
$.ajax({
url: "http://localhost:3000/teamplayers.json",
data: {'resolution':ids},
type:"post",
dataType: "json",
cache: true,
success:function(){
$('#test3').val(1);
alert("test 3");
},
error: function(error) {
alert("Failed " + console.log(error) + " " + error)
}
});
});
});
This is supposed to set a variable here:
Teamplayer Controller
# GET /teamplayers
# GET /teamplayers.json
def index
#teamplayers = Teamplayer.all
#fteams = Fteam.all
#teamplayer2 = 1
tid = params[:resolution] <-It should set here per the data section above
#ids = tid
end
unfortunately it calls this section of the same controller
# POST /teamplayers
# POST /teamplayers.json
def create
#teamplayer = Teamplayer.new(teamplayer_params)
respond_to do |format|
if #teamplayer.save
format.html { redirect_to #teamplayer, notice: 'Teamplayer was successfully created.' }
format.json { render action: 'show', status: :created, location: #teamplayer }
else
format.html { render action: 'new' }
format.json { render json: #teamplayer.errors, status: :unprocessable_entity }
end
end
end
So what do I do to make it post to the same page.
You are POSTing the ajax, which means the create action will be hit, not the index action. You should be able to see this in your server log output when you hit the page.
If you want to hit the index action, you need to do an GET ajax request with the resolution data set so you can get the data you want.
Additionally, you probably maybe don't want to cache this ajax request if it is actually dynamic data, but it is up to you.
Edit from comments:
You need to add your parameter as a query string for a GET, not as generic "data".
Try something like this:
$.ajax({
url: "http://localhost:3000/teamplayers.json?resolution="+ids,
type:"GET",
dataType: "json",
success:function(){
$('#test3').val(1);
alert("test 3");
},
error: function(error) {
alert("Failed " + console.log(error) + " " + error)
}
});
});
Another edit from comments:
# GET /teamplayers
# GET /teamplayers.json
def index
#teamplayers = Teamplayer.all
#fteams = Fteam.all
#teamplayer2 = 1
tid = params.fetch(:resolution) { 0 } # make sure we got something
#ids = tid.to_i # coerce string param to integer
end

Show Rails error message in Ajax alert

Using Rails 3.2. I wonder how can we push the error from Rails to show in the Ajax alert. Here is my code:
# posts_controller.rb
def update
#post = Post.find(params[:id])
if #post.update_attributes(params[:name] => params[:value])
render :nothing => true
else
render :text => #post.errors.full_messages[0], :status => :unprocessable_entity
end
end
# _form.html.erb
$("#status_buttons button").click(function() {
$.ajax({
type: 'POST',
url: "<%= post_path(#trip) %>",
data: { _method: 'PUT', name: this.name, value: this.value },
error: function() {
alert(" *****************Rails error message here**********************");
}
});
});
The conventional validation error message should appear in the alert(). Any idea?
Thanks.
one way to determine is to pass at least 3 arguments to the callback function and checking the console (or an alert) for whatever argument passes the error.
error: function(a,b,c) {
alert('a contains ' + a);
alert('b contains ' + b);
alert('c contains ' + c);
}
one of them should contain the error message :) Good luck!
error: function( jqXHR, textStatus, errorThrown ) { ...

Categories