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
Related
I am trying to submit localstorage data via a POST request using the below jquery ajax method. How should I write my view so I can Parse my JSON object and get a hold of "product_id" to execute the below command in my Django view. Please see a copy of my view below.
Trying since one week, but I failed to fix the issue
Is there any better way of achieving this ?
My Ajax:
$(document).ready(function() {
var compare = localStorage.getItem("comparisionItems");
var compareObj = JSON.parse(compare);
var data_url = window.location.href;
console.log(compare)
console.log(compareObj)
$.ajax({
url: data_url,
type: "POST",
data: {'compare_id': compareObj },
headers: { "X-CSRFToken": $.cookie("csrftoken") },
success: function (result) {
console.log("Success")
},
});
});
and My Views:
def compare(request):
is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
if is_ajax and request.method == "POST":
compare_id= request.POST.getlist('compare_id[itemIds]')
product = get_object_or_404(Products, id=compare_id)
context={ 'product':product}
return render (request, './compare.html', context)
Actually my localStorage is on following format:
("comparisionItems"({ images: products, itemIds: itemIds }));
Can you please help me how can I pass itemIds to views and return item from views for the itemsIds?
Console log for console.log(compareObj)
https://imgur.com/MxdZrgy
since .is_ajax() is deprecated you cant use that, but you can check if the request is an XMLHttpRequest like below.
from django.shortcuts import get_object_or_404
def compare(request):
is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
if is_ajax and request.method == "POST":
compare_id = request.POST.get('compare_id')
product = get_object_or_404(Products, product_id=id)
context={ 'product':product,}
return render (request, './ecommerce/compare.html', context)
note; the get_object_or_404 is just a shortcut for:
try:
product = Products.objects.get(product_id=id)
except:
raise Http404
I am trying to pass an array of objects from my JS to my Rails controller so that I can loop through the array and check to see if each object exists, and if not, create it. I'm having a difficult time getting my strong params setup properly. Seems like no matter what I do, I'm getting some kind of an error about unpermitted params.
My JS that is creating and sending the data:
function addGame(gameData) {
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(gameData,"text/xml");
// Check categories and create any new categories that need created
var gameCategories = [];
// for each category in the JSON push into gameCategories
var x = xmlDoc.getElementsByTagName("link").length;
var i = 0
for (i = 0; i < x ; i++) {
var type = xmlDoc.getElementsByTagName("link")[i].getAttribute("type");
if (type == "boardgamecategory") {
var categoryData = {
name: xmlDoc.getElementsByTagName("link")[i].getAttribute("value"),
bgg_id: xmlDoc.getElementsByTagName("link")[i].getAttribute("id")
};
gameCategories.push(categoryData);
}
}
console.log(gameCategories);
// Try sending all of the categories at once
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});
$.ajax({
url: '/categories',
type: 'POST',
dataType: 'json',
data: { categories: JSON.stringify(gameCategories)},
success: function (response) {
console.log(response);
}
});
My rails controller
class CategoriesController < ApplicationController
def create
logger.debug category_params
# #category = Category.find_or_initialize_by(category_params)
# if #category.save
# logger.debug "Category Saved"
# else
# flash[:danger] = "There was a problem creating one of the game categories ¯\_(ツ)_/¯"
# redirect_to root_url
# end
end
private
def category_params
params.permit(categories: [])
end
end
Right now if I run this the server log shows
Started POST "/categories" for ::1 at 2019-09-19 21:45:33 -0400
Processing by CategoriesController#create as JSON
Parameters: {"categories"=>"[{\"name\":\"Adventure\",\"bgg_id\":\"1022\"},{\"name\":\"Exploration\",\"bgg_id\":\"1020\"},{\"name\":\"Fantasy\",\"bgg_id\":\"1010\"},{\"name\":\"Fighting\",\"bgg_id\":\"1046\"},{\"name\":\"Miniatures\",\"bgg_id\":\"1047\"}]"}
User Load (0.5ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
↳ app/helpers/sessions_helper.rb:18
Unpermitted parameter: :categories
{}
No template found for CategoriesController#create, rendering head :no_content
Completed 204 No Content in 95ms (ActiveRecord: 22.8ms)
Thanks in advance for any advice!
Try this
$.ajax({
url: '/categories',
type: 'POST',
dataType: 'json',
data: { categories: gameCategories},
success: function (response) {
console.log(response);
}
});
def category_params
params.permit(categories: [:name, :bgg_id])
end
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.
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'
});
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