I have data coming from sunspot to select2(shown list_styles method of controller). I can search and save multiple categories with select2 on new provider form without any problems however when I try to load the data from database on edit provider form it doesn't show up. Tried the initselection method and checked the documentation/stackoverflow for initselection method that fits to my application but could not sort it out. Created a new controller method called list_categories without success. Can anyone comment me on the correct way to do it?
Thank you.
Jquery
$('#provider_category').select2({
minimumInputLength: 3,
multiple: true,
ajax: {
url: "/categories/list_styles",
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return {
q: term,
page_limit: 10,
page: page,
};
},
results: function (data) {
var hashtable={};
var results = \[\];
$.each(data, function(index, item){
if (hashtable\[item.parent\]===undefined) {
hashtable\[item.parent\]={text:item.parent, children:\[\]};
results.push(hashtable\[item.parent\]);
}
hashtable\[item.parent\].children.push({id:item._id,text:item.title});
});
return {
results: results
};
},
initSelection: function(element, callback) {
return $.ajax({
type: "get",
url: "/categories/list_categories",
dataType: 'json',
data: function (term, page) {
return {
q: term,
page_limit: 10,
page: page,
};
},
success: function(data){
}
}).done(function(data) {
//console.log(data);
return callback(data);
});
}
}
});
Controller
class CategoriesController < ApplicationController
respond_to :html, :json
def list_styles
search = Category.search do
fulltext params[:q]
end
search = Category.search { keywords params[:q]; paginate :page => params[:page], :per_page => params[:page_limit] }
#categories = search.results
respond_with #categories
end
def list_categories
search = Provider.find "5299b5dcdd506322c4000091"
#category = search.category
x = Category.find #category
search = Category.search { keywords x.title; paginate :page => params[:page], :per_page => params[:page_limit] }
#categories = search.results
respond_with #categories
end
end
Thats the way it is baby!
jquery
},
initSelection : function (element, callback) {
var data1 = [];
jQuery(element.val().split(",")).each(function () {
$.ajax({
type: "get",
url: "/providers/list_categories",
async: false,
dataType: 'json',
data: { id: $("#provider_id").val()},
success: function(category){
$.each(category, function(i, obj) {
data1.push({id: this._id, text: this.title});
});
}
});
});
callback(data1);
}
});
contoller
def list_categories
#provider = Provider.find params[:id]
arr = #provider.category.split(",")
#category = Category.where(:_id.in => arr)
respond_to do |format|
format.json { render :json => #category}
end
end
Related
I need help in select2 gem ajax request, where i can't display any data.
I can't get also any response from the console and server.
I was using this as a reference or guide jQuery Select2 not displaying Data and Select2-rails 4.0.3 cannot trigger ajax. Thank you for any help.
routes.rb
namespace :advertiser do
resources :service_providers do
collection do
get :cities # return /advertiser/service_providers/cities
end
end
end
controller
def cities
cities = Model.where("name ILIKE ?", "%#{params[:q]}%").map{ |rec| { :id => rec.id, :text => rec.name }}
render json: cities
end
result from controller
[{"id":1,"text":"Result 1"},{"id":2,"text":"Result 2"},{"id":3,"text":"Result 3"}]
js
$(document).ready(function() {
$("#service_provider_city_name").select2({
ajax: {
url: "/advertiser/service_providers/cities",
dataType: "json",
type: 'GET',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
};
},
processResults: function (data) {
return {
results: data
};
},
cache: true
}
});
});
please help me ...
I have an app where a user has a portfolio that has many positions and each position has many movements. So the url for an associated movement index page for a particular position looks like: portfolio_position_movements. I have an index page with and the controller action looks like
def index
#movements = #position.movements.all
respond_to do |format|
format.html
format.json { render json: #movements}
end
end
My ajax call in my movements.js file is this:
var loadData = function(){
$.ajax({
type: 'GET',
contentType: 'application/json; charset=utf-8',
url: ?,
dataType: 'json',
success: function(data){
drawBarPlot(data);
},
failure: function(result){
error();
}
});
};
How can I pass in a dynamic route path so this will work with the movement index on any position object?
You can use erb tags in js files, for me i did it as the following:
#edit.js.erb
$modal = $('.modal'),
$modalBody = $('.modal .modal-body'),
$modalHeading = $('.modal .modal-heading');
$modalHeading.html("Edit <%= #student.full_name.titleize %>'s information");
$modalBody.html("<%= escape_javascript(render 'edit_student') %>");
$modal.modal();
Note: the file extension is .js.erb so rails can process it. I was calling a modal form and the edit method in students_controller.rb was:
def edit
#student = Student.find(params[:id])
respond_to do |format|
format.html # edit.html.erb
format.js # edit.js.erb
format.json { render json: #student }
end
end
Edit:
You can embed the JS code inside html.erb and use rails routes like:
<script>
var loadData = function(){
$.ajax({
type: 'GET',
contentType: 'application/json; charset=utf-8',
url: <%= my_ajax_path %>,
dataType: 'json',
success: function(data){
drawBarPlot(data);
},
failure: function(result){
error();
}
});
};
</script>
What is my_ajax_path?
Is a rails route defined in routes.rb for example i need a list of all available sections that students can apply to using ajax so i did the following:
1- defined a method in students_controllers.rb like this one:
def available_sections
batch_id = (params[:batch_id].nil? || params[:batch_id].empty?) ? 0 : params[:batch_id].to_i
if batch_id == 0
#sections = [].insert(0, "Select Section")
else
batch = Batch.find(params[:batch_id])
# map to name and id for use in our options_for_select
#sections = batch.sections.map{|a| [a.section_name, a.id]}
end
end
2- added a route to it in routes.rb
resources :students do
collection do
get :available_sections
post :create_multiple
end
end
3- Inside new.html.erb:
<script type="text/javascript">
$(document).ready(function() {
$('.student_section_id').hide();
$('#student_batch').change(function() {
$.ajax({
url: "/students/available_sections",
data: {
batch_id : $('#student_batch').val()
},
dataType: "script",
success: function () {
if (+$('#student_batch').val() > 0)
{
$('.student_section_id').fadeIn();
}
else
{
$('.student_section_id').fadeOut();
}
}
});
});
});
</script>
Forget about that messy code :D as it was my first steps but you get the point, and for this line url: "/students/available_sections" it should be using rails routes you can get it by calling rails routes from the command line to get a list of all your application routes
I want send selected drop down menu value to controller by ajax
panel_controller.rb
class PanelController < ApplicationController
def insert
#city_ids = params[:city]
end
end
panel.js.erb
$(document).ready(function() {
$('#f_city_id').change(function() {
var city_js_id = this.value
$.ajax({
url: '/panel/insert',
type: 'GET',
data: {"city": city_js_id},
success: function (data,status)
{
alert(this.url);
}
});
return false;
});
});
routes.rb
get '/panel/insert' => 'panel#insert'
views/panel/insert.html.erb
<%= #city_ids %>
but #city_ids dont respond value after chenge drop down menu
You need to respond back from your insert method.
Try doing this
class PanelController < ApplicationController
def insert
#city_ids = params[:city]
respond_to do |format|
format.html { render partial: 'insert.html.erb' }
end
end
end
Create a partial file with the new content _insert.html.erb
<%= #city_ids %>
In you panel.js.erb try catching the response and append it in your DOM wherever necessary. Your updated value will be on the page.
$(document).ready(function() {
$('#f_city_id').change(function() {
var city_js_id = this.value
$.ajax({
url: '/panel/insert',
type: 'GET',
data: {"city": city_js_id},
success: function (res){
$("#somediv").html(res);
//You will get the partial's content with the new data and you'll only need to append it to your page.
}
});
return false;
});
});
So I have been playing around with acts_as_taggable_on in active admin, and for the most part everything is working as expected.
However, whenever I search for tags, and add an existing tag to a model, it seems to save it as the ID, rather than as the name. Creation of new tags returns the name fine, and when I go to edit the object again the tags remain tagged by the name. But when I try and add another tag, one that already exists in the database, it returns the name in the form, and seems to save OK, but when I go back to edit the onject again the tag shows up as an ID, rather than the name.
In admin/gift.rb:
controller do
def autocomplete_gift_tags
#tags = ActsAsTaggableOn::Tag
.where("name LIKE ?", "#{params[:q]}%")
.order(:name)
respond_to do |format|
format.json { render json: #tags , only: [:id, :name], root: false }
end
end
end
In tag-autocomlete.js:
$(document).ready(function() {
$('.tagselect').each(function() {
var placeholder = $(this).data('placeholder');
var url = $(this).data('url');
var saved = $(this).data('saved');
$(this).select2({
tags: true,
placeholder: placeholder,
minimumInputLength: 1,
initSelection: function(element, callback) {
saved && callback(saved);
},
ajax: {
url: url,
dataType: 'json',
data: function(term) {
return {
q: term
};
},
results: function(data) {
return {
results: data
};
}
},
createSearchChoice: function(term, data) {
if ($(data).filter(function() {
return this.name.localeCompare(term) === 0;
}).length === 0) {
return {
id: term,
name: term
};
}
},
formatResult: function(item, page) {
return item.name;
},
formatSelection: function(item, page) {
return item.name;
}
});
});
});
And in my _gift_form.html.erb:
<%= f.input :tag_list, label: "Tags", input_html: { data: { placeholder: "Enter tags", saved: f.object.tags.map{|t| {id: t.name, name: t.name}}.to_json, url: autocomplete_gift_tags_path }, class: 'tagselect' } %>
Can't work out why the new ones are working, but the existing tags are not.
change this:
respond_to do |format|
format.json { render json: #tags , only: [:id, :name], root: false }
end
to this:
respond_to do |format|
format.json { render :json => #tags.collect{|t| {:id => t.name, :name => t.name }}}
end
I was wondering how you can get 2 variables to update a div tag using an ajax call instead of just 1. My current .js file:
$(document).ready(function() {
$("select").change(function() {
var selected_product_id;
selected_product_id = $(this).val();
$.ajax({
url: "/products/" + selected_product_id,
type: "GET",
success: function(data) {
$("#description").empty().append(data);
}
});
});
});
show.html.erb where i get the data:
<%= #product.item %>
I would like something like this
$.ajax({
url: "/products/" + selected_product_id,
type: "GET",
success: function(data) {
$("#description").empty().append(data[1]);
$("#price").empty().append(data[2]);
}
});
with
<%= #product.item %>
<%= #product.price %>
where my description div gets updated with #product.item and my price div gets updated with #product.price. How could I achieve this?
EDIT
updated .js file
$(document).ready(function() {
$("select").change(function() {
var selected_product_id;
selected_product_id = $(this).val();
$.ajax({
url: "/products/" + selected_product_id,
type: "json",
success: function(data) {
$("#description").empty().append(product.item);
$("#price").empty().append(product.price)
}
});
});
});
show.html.erb:
<%= #product.item %>
<%= #product.price %>
controller:
class ProductsController < ApplicationController
respond_to do |format|
format.html # show.html.erb
format.json { render :json => #product.to_json }
end
def index
end
def show
#product = Product.find(params[:id])
end
end
I'm pretty sure that controller isn't correct. I placed #product before respond_to and it didn't work so I just put respond_to without really knowing where it goes. Sorry for being such a noob. Thanks for all your help.
FINAL EDIT:
working javascript file:
$(document).ready(function() {
$("select").change(function() {
var selected_product_id;
selected_product_id = $(this).val();
$.getJSON("/products/"+selected_product_id,function(data){
$("#description").empty().append(data.item);
$("#price").empty().append(data.price);
});
});
});
Ah, This remembers me a piece of code I wrote for you a week ago!
You can use JSON to render your Product:
#controller
def show
#product = Product.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render :json => #product.to_json }
end
end
And handle the response from the server like this:
$.ajax({
url: "/products/" + selected_product_id,
dataType: 'JSON',
success: function(data) {
var product = JSON.parse(data);
$("#description").empty().append(product.item);
$("#price").empty().append(product.price);
}
});
Edit #1: I found this method: jQuery.getJSON : http://api.jquery.com/jQuery.getJSON/
You could use JSON, return
{"item": "<%=j #product.item %>", "price": <%= #produce.price %>}
then type: 'json' in the ajax call