How to pass the params from JS to rails3 controller - javascript

Here is my JS.coffee codes:
fetchselect =(val) ->
$.ajax(url: '/firstpages/page', dataType: 'json', par_id: val )
$('.homeNav').find('.unactive').click ->
id = $(this).attr('id')
fetchselect(id)
and Here is my controller codes:
def page
#select = Firstpage.where(:pid=>params[:par_id])
respond_to do |format|
format.html # page.html.erb
format.js { render :layout => false }
format.json { render :json => #select }
end
end
It can't pass the params to #select ,when I click $('.homeNav') ,the log tell me:
Started GET "/firstpages/page" for 127.0.0.1 at 2012-09-07 05:27:07 +0800
Processing by FirstpagesController#page as JSON
Firstpage Load (0.2ms) SELECT "firstpages".* FROM "firstpages" WHERE "firstpages"."pid" IS NULL
Completed 200 OK in 2ms (Views: 0.1ms | ActiveRecord: 0.2ms)

Looks like the problem is in the actual ajax request. Try:
$.ajax({
type: "POST",
url: '/firstpages/page',
dataType: 'json',
data: {par_id : val})
})
For more examples, check out the jQuery $.ajax documentation.

Related

Rails: Using Ajax to fill Jquery Autocomplete

I've been all over the place plugging different things into this process and I still get no results.
Sometimes I get the infamous extra "<" error, sometimes absolutely nothing happens, and I'm not sure if this is the problem but I think Google developer is showing that the current page is being sent as the json file I'm asking for and not the json I'm sending (see later). This is what I see in google developer:
Which is definitly NOT my json file:
In any case, this is my javascript:
$('#q_name_cont').autocomplete({
url: "autocomplete/items",
dataType: 'json'
});
This is my route:
get 'autocomplete/items' => 'home#autocomplete_items', :defaults=>{:format=>'json'}
Controller Action (commented out part is another method I was trying for a while):
def autocomplete_items
# respond_to do |format|
# format.js {render 'autocomplete_items'}
#products = Item.all.order(:name)
respond_to do |format|
format.html
format.json {
render json: #products.map {|item| item.name}
}
end
end
Before I was using mapping, I was using this view for the render:
{
"items": [
<%Item.all.each do |i|%>
{ "<%=i.name%>","<%=i.name%>" },
<%#end%>
{ "value": "", "data": "" }
]
}
I've really been all over the place, trying for a very long time to get this to work. What am I missing?
IIRC, Your url and dataType options just do not exist in autocomplete's documentation. You could try source option instead:
$('#q_name_cont').autocomplete({
source: function (request, response) {
$.ajax({
url: "/autocomplete/items", // should be with '/'
dataType: 'json',
data: { query: request.term },
success: function(data) {
// call response to return the result to autocomplete box
response(data);
}
});
}
});
Of course, this is just for showing up all items, if you want to filter like real autocomplete box, you should modify controller to filter the result base on query:
def autocomplete_items
#products = Item.all.order(:name)
respond_to do |format|
format.html
format.json {
render json: #products
.where('name ILIKE ?', "%#{params[:query]}%")
.pluck(:name)
}
end
end

Triggering callback after rendering login form from rails

I am building a single-page-app with rails and client-side javascript. To dynamically manage the interface, I need to trigger a callback after the login form view (loginForm.html.erb) is returned (for user authentication via Bcrypt). I've tried jquery $.ajax requests, and can get the form OR the json responses but not both.
Here's the request to get the login form:
loginMenuEl.on("click", function(event){
event.preventDefault();
$.ajax({
url: "http://localhost:3000/login",
type: "GET",
dataType: "json"
}).done(function(jsonData) {
self.initLoginButton();
self.processContent(jsonData);
}).fail(function(){
console.log("*** ajax fail L1 ***");
});
});
Here are the relavent routes:
get "/login" => "sessions#login"
get "/loginForm" => "sessions#loginForm"
get "/login_attempt" => "sessions#login_attempt"
post "/login_attempt" => "sessions#login_attempt"
Here is the Sessions controller that processes the form and json:
def login
#contentInfo = Content.find_by_id(1)
respond_to do |format|
format.html { render :loginForm }
format.json { render json: #contentInfo }
end
end
I've tried other versions of the respond_to block but the form never returns:
format.html { redirect_to (:action => 'loginForm') }
format.html { redirect_to (action: 'loginForm') }
format.html { redirect_to action: 'loginForm' }
format.json { render json: #contentInfo }
Am I correct to believe that rails can return both json and a view file (loginForm.html.erb)

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 }

What am I doing wrong with this AJAX request using a form_for in Rails 4?

I'm trying to do a form submission through AJAX in Rails and I am not too sure what is wrong here. I got everything to work using "remote: true" but I want to gain a better understanding of how the AJAX works with jQuery. This is my javascript code:
$(document).ready(function(){
$("#new_user_friendship").on("submit", function(event){
event.preventDefault();
var friendId = $("#user_friendship_friend_id").val();
var _this = $(this);
$.ajax({
url: "/user_friendships",
data: _this.serialize(),
method: "POST",
dataType: "json",
success: function(data){
console.log(data);
friendButton.hide();
$(".friend-request-form").html("<p>Friend request sent</p>");
}
});
});
});
I am suspecting this line url: "/user_friendships/new?friend_id="+friendId containing the url is the culprit of my errors. I wrote this because a hidden field is being passed as a person's friend id but it throws a "404 error", I've also tried url: "/user_friendships" which doesn't return any errors but it also doesn't properly execute the Javascript as I expected.
This is the corresponding form_for that the AJAX request is sent to:
<div class="friend-request-form">
<%= form_for current_user.user_friendships.build(friend_id: #user), id: "new_user_friendship", method: :post do |f| %>
<%= f.hidden_field :friend_id, value: #user.id %>
<%= submit_tag "Send friend request", class: "button radius tiny", id: "friend-request-button" %>
<% end %>
</div>
What this form does is it sends a friend request to another user using a hidden field.
And in my user_friendships_controller.rb I have this code:
def create
if params[:user_friendship] && params[:user_friendship].has_key?(:friend_id)
#friend = User.find(params[:user_friendship][:friend_id])
#user_friendship = UserFriendship.request(current_user, #friend)
respond_to do |format|
if #user_friendship.new_record?
format.html do
flash[:error] = "There was a problem creating that friend request."
redirect_to user_path(#friend)
end
format.json {render json: #user_friendship.to_json, status: :precondition_failed}
else
format.html do
flash[:success] = "Friend request sent"
redirect_to user_path(#friend)
end
format.json {render json: #user_friendship.to_json, status: :precondition_failed}
end
end
else
flash[:error] = "Friend required"
redirect_to root_path
end
end
If anyone can provide any suggestions or feedback that'd be great!
UPDATE:
Now that I added in data: _this.serialize() and changed the url to: url: "/user_friendships" I'm now getting a 412 (Precondition Failed) error. Despite this error the data is actually being saved into the database. Does anyone know why I'm getting this 412 (Precondition Failed) error?
There is something I do not understand, with the dataType json, you said that you had a precondition failed status right ?
But you wrote
format.json {render json: #user_friendship.to_json, status: :precondition_failed}
So I don't think there is any problem, indeed, it seems to work fine, as you explicitly passed the status in your render command, try removing it and I think you will have a 200 (success) status instead.
Of course, you can keep the previous post ajax request, or use this short version
$.post(
/user_friendships',
{ user_friendship: { friend_id: friendId } },
function(){
console.log(data);
friendButton.hide();
$(".friend-request-form").html("<p>Friend request sent</p>");
},
'json')
Add a data attribute to the post params instead of passing it in the url:
$.ajax({
url: "/user_friendships",
data: { user_friendship: { friend_id: friendId } }, // <<< Updated
method: "POST",
dataType: "json",
success: function(data){
console.log(data);
friendButton.hide();
$(".friend-request-form").html("<p>Friend request sent</p>");
}
});
Update
The url should be /user_friendships, assuming that you're using RESTful actions. Have a look to this article about REST in Rails.
Also, when you do an AJAX request like this, your are not sending the rails authenticity tokens that are crated by the form helper. This may be the cause of your 412 (Precondition Failed) error.
See: Understanding the Rails Authenticity Token

Ruby on rails - PUT method on update ajax

Could someone tell me why this PUT method doesn't work please.
$.ajax({
type: "PUT",
dataType: "script",
url: '/resources/35',
data:
{
resource : { pos_y: 45, pos_x: 50 }
}
}).done(function( msg )
{
alert( "Data Saved: " + msg );
});
Server says that I have used the GET method but in my ajax request I have type: "PUT"
Started GET "/resources/35?resource%5Bpos_y%5D=45&resource%5Bpos_x%5D=50&_=1344001820350" for 192.168.1.89 at 2012-08-03 15:50:20 +0200
Processing by ResourcesController#show as */*
Parameters: {"resource"=>{"pos_y"=>"45", "pos_x"=>"50"}, "_"=>"1344001820350", "id"=>"35"}
User Load (0.3ms) SELECT "users".* FROM "users"
Resource Load (0.1ms) SELECT "resources".* FROM "resources" WHERE "resources"."id" = ? LIMIT 1 [["id", "35"]]
Rendered resources/show.html.erb within layouts/login (2.3ms)
Completed 200 OK in 238ms (Views: 235.9ms | ActiveRecord: 0.4ms)
resources_controller.rb
# PUT /resources/1
# PUT /resources/1.json
def update
#resource = Resource.find(params[:id])
respond_to do |format|
if #resource.update_attributes(params[:resource])
format.html { redirect_to #resource, notice: 'successfully updated.' }
format.js
else
format.html { render action: "edit" }
format.js
end
end
end
I have tried adding _method: 'put' But it's still the same
$.ajax({
type: "PUT",
dataType: "script",
url: '/resources/35',
data:
{
resource : { pos_y: 45, pos_x: 50 },
_method: 'put'
}
}).done(function( msg )
{
alert( "Data Saved: " + msg );
});
Server:
"resource%5Bpos_y%5D=45&resource%5Bpos_x%5D=50&method=put&=1344004390840"
Started GET "/resources/35?resource%5Bpos_y%5D=45&resource%5Bpos_x%5D=50&_method=put&_=1344004390840" for 192.168.1.89 at 2012-08-03 16:33:10 +0200
Processing by ResourcesController#show as */*
Parameters: {"resource"=>{"pos_y"=>"45", "pos_x"=>"50"}, "_"=>"1344004390840", "id"=>"35"}
User Load (0.3ms) SELECT "users".* FROM "users"
Resource Load (0.1ms) SELECT "resources".* FROM "resources" WHERE "resources"."id" = ? LIMIT 1 [["id", "35"]]
Rendered resources/show.html.erb within layouts/login (0.8ms)
Completed 200 OK in 93ms (Views: 90.5ms | ActiveRecord: 0.4ms)
I'd appreciate any help.
Rails determines the put request via the parameter _method with the value 'put'.
As not all the browsers support the put method, rails cheats in the form_tag. its putting this output in a PUT form:
<input type='hidden' name='_method' value='put'>
So what you have to do is this:
$.ajax({
type: "POST",
dataType: "script",
url: '/resources/35',
contentType: 'application/json',
data: JSON.stringify({ resource:{pos_y:45,pos_x:50}, _method:'put' })
}).done(function( msg )
{
alert( "Data Saved: " + msg );
});

Categories