ActionController::UnknownFormat in CareersController#create for rails 4 - javascript

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.
});
})

Related

Dynamic select boxes with Rails 4

I tried to make dynamic select boxes(One boxes choosing info in another), but have some troubles.
routes.rb
get "students/new/update_tutors" => 'students#update_tutors', as: 'update_tutors'
students_controller.rb
def update_tutors
admin = Administrators.find(params[:administrator_id])
##tutors = admin.tutors.map{|t| [t.info.name, t.id]}
debugger
#tutors = Tutor.where(administrator_id: params[:administrator_id])
respond_to do |format|
format.js
end
end
def new
#user = Student.new
#is_super_adm = is_super?
if #is_super_adm
#tutors = Tutor.all.map { |t| [t.info.name, t.id] }
#admins = Administrator.where(is_super: false).map { |adm| [adm.info.name, adm.id] }
else
#tutors = Tutor.where(administrator_id: session[:type_id]).map { |t| [t.info.name, t.id] }
end
end
new.html.erb
<%= form_for #user, remote: true do |student_form| %>
<!--....-->
<%= label_tag :administrator_id, "Choose local administrator" %><br/>
<%= select_tag :administrator_id, options_for_select(#admins), {id: 'administrator_selection'} %><br/>
<!--....-->
<%= student_form.label :tutor_id, "Choose Tutor" %><br/>
<%= student_form.select :tutor_id, options_for_select(#tutors), {} , {id: 'tutor_selection'}%>
students.coffee
$ ->
$(document).on 'change', '#administrator_selection', (evt) ->
$.ajax 'update_tutors',
type: 'GET'
dataType: 'script'
data: {
administrator_id: $("#administrator_selection option:selected").val()
}
error: (jqXHR, textStatus, errorThrown) ->
console.log("AJAX Error: #{textStatus}")
success: (data, textStatus, jqXHR) ->
console.log("Dynamic country select OK!")
update_tutors.coffee
$("#tutor_selection").empty()
.append("<%= escape_javascript(render(:partial => #tutors)) %>")
I tried to insert alert('msg') into students.js.coffee, and event worked, so I am sure that the problem is in $.ajax but this is first time I am working with ajax and I can't find the bug.
Update
I guess problem is in routing, but i didn't understand why it calls students/update_tutor instead students/new/update_tutor
Log
Started GET "/students/update_tutors?administrator_id=3&_=1459590346845" for 127.0.0.1 at 2016-04-02 11:47:01 +0200
Processing by StudentsController#show as JS
Parameters: {"administrator_id"=>"3", "_"=>"1459590346845", "id"=>"update_tutors"}
Fixed
I changed update_tutors in $.ajax to 'new/update_tutors' and fixed error in update_tutors method in Administrators.find(...) to Administrator.find(...).
Change your Ajax request as per given below,
$ ->
$(document).on 'change', '#administrator_selection', (evt) ->
$.ajax '<%= update_tutors_path %>',
type: 'GET'
dataType: 'script'
data: {
administrator_id: $("#administrator_selection option:selected").val()
}
error: (jqXHR, textStatus, errorThrown) ->
console.log("AJAX Error: #{textStatus}")
success: (data, textStatus, jqXHR) ->
console.log("Dynamic country select OK!")

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.

Sending back an ajax error response in rails contoller

I am attempting to send back an error response to an ajax call in a rails controller.
Below is my create action in my controller the javascript function with the ajax call. I need to send back a error response so the error portion of the ajax request is called. I can not figure out how to get this to work.
def create
#company = Company.find(params["company_id"])
#campaign = #company.campaigns.build(campaign_params)
if #campaign.save
redirect_to campaign_get_campaigns_path(#company)
else
respond_to do |format|
format.json {render :json => {:error_message => #campaign.errors.full_messages, :success => false } }
end
end
end
$(document).on('click', '#submitCampaign', function (e) {
$form = $('.new_campaign');
$.ajax({
type: "POST",
url: $form.attr('action'),
data: $form.serialize(),
dataType: "json"
});
error: function(data) {
newfunction(data);
}
});
The response I am getting in the terminal is:
Completed 200 OK in 269ms (Views: 0.2ms | ActiveRecord: 9.9ms)
You have to define response :status. In this case is the best choice 422 Unprocessable entity.
format.json { render :json => { :error_message => #campaign.errors.full_messages }, :status => :unprocessable_entity }

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

Json sending multiple results

I send data in json format for counting visits. Problem is when i use back arrow in browser - results are send second, third ... and more times and there is one em tag for every click in back arrow on browser. What i can do to overwrite results but not sending second in new place.
My controller:
visits_count = current_user.visits.where(:read => false).count.to_i
respond_to do |format|
format.json { render :json => visits_count }
And my js:
function unread(){
$('#visits p').each( function() {
$.ajax({
url: '/visits/unread_count',
dataType: 'json',
success: function(data) {
if (data > 0) {
$('#visits p').append('<em>' + data +'</em>');
}
}
});
});
};
and my view:
<%= link_to 'visits', visits_path, :id => "visits" %><p></p></li>

Categories