In AJAX I write:
$.ajax({
URL: '/new_avatar',
type: 'POST',
data: { username: 'alizade' },
success: function(response){
alert(response);
},
})
Route.rb:
post '/new_avatar' => 'avatars#new_avatar'
Avatar.rb model:
self.new_avatar(username)
Avatar.where(username: username).select('avatar').last
end
Avatars_Controller:
def new_avatar
#username = params[:username]
#result = Avatar.new_avatar(#username)
end
So, how can send #result to AJAX response function and alert the database selection result?
Assuming you need only response from this service, you can use following way to get the result.
def new_avatar
#username = params[:username]
render :json => Avatar.new_avatar(#username)
end
you need to use render :text in your controller method
def new_avatar
#username = params[:username]
#result = Avatar.new_avatar(#username)
render :text => "#{#username} has this result:- #{#result.inspect}"
end
Related
please help me i newbie on rails and jquery i try get all values from array #mychannels id element on html in my view.
JS AJAX
$(document).ready(function() {
$('#mychannels').change(function () {
$.ajax({
type: "GET",
contentType: "dados/json",
url: "/suporte/chamados?empresa_id=91194",
success: function(data){
alert(data);
}
});
});
});
Controller
def get_data
#company = Company.find(params[:company_id])
#servers = Server.find(:all, :conditions => ["company_id = ? AND action != 3", #company.id])
#channels_list = Channels.where("channel = 't' and company_id = 91194")
My View
<%= select_tag "mychannels",options_for_select(#channels_list.map { |e|
[e.name+" - "+e.server.name, e.id]}) %>
I am trying to read the data that comes from the controller throw to an array and display it in the select_tag of the view.
could you help me with the code
You need to update your controller action adding the render method and adding the values you want to get in your jQuery success callback.
Controller
def get_data
#company = Company.find(params[:company_id])
#servers = Server.find(:all, :conditions => ["company_id = ? AND action != 3", #company.id])
#channels_list = Channels.where("channel = 't' and company_id = 91194")
render json: { company: #company.to_json, servers: #servers.to_json, channels_list: #channels_list.to_json }
end
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.
Stackoverflow community
I have a select in my view. Onchange of which my ajax request is sent.
<%= f.select :id, options_from_collection_for_select(#rtypes, "id", "typeName"),
{include_blank: true },
{'data-rtypes': #rtypes.to_json } %>
.I am using Jquery ajax. My ajax works. It send an id of rtype to the show_sub_types method.
$(function () {
// specify id or class for your select tag
$('select').on('change', function () {
var rtype = $(this).val();
$.ajax({
url: "/RequestTypes/show_sub_types/"+rtype,
type: "GET",
})
});
});
In my show_sub_types method I want to grab all subTypes (stypes) from RequestSubType model.
def show_sub_types
#rtype = params[:id];
#stypes = RequestSubType.where("RequestType_id"==#rtype).all
respond_to do |format|
... some code here
end
end
I do not know how to deal with ajax request, i dont know how to send my stypes array to the page, and how to deal with that response. I have read some tutorials, but still can not understand that respond_to part. Probably i would understand on my own example.
In my view i have div where i want to put data send by ajax (inserted into html).
Specify the id of select and read for data attribute.
Get that array in data variable, and pass it to post ajax request
var data = $(this).data('rtypes');
or
$(this).find(':selected').data('rtypes')
$.ajax({
type : "POST",
url : "/RequestTypes/show_sub_types/"+rtype,
dataType: 'json',
data: JSON.stringify(data),
dataType: "json",
contentType: 'application/json'
});
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
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