Rails Select2 Gem using Ajax not displaying data - ruby-on-rails

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 ...

Related

Rails Ajax not displaying the result

I have created a new controller, that in future will be responsible only for translating strings for different objects.
Here is the code of the controller:
# frozen_string_literal: true
class Api::TranslationsController < AuthenticatedController
def translate_string
#translated_string = GoogleTranslator.translate('hello', 'de')
render json: {translated_string: #translated_string.to_json}
end
helper_method :translate_string
private
def translations_params
params.permit(
:id,
:translated_string
)
end
end
It is placed in directory controllers/api/translations_controller. Here is the part of routes:
namespace :api do
resource :translations do
member do
get 'translate_string'
end
end
end
And here is part of my html.erb to call JS function:
<%= image_tag "google-icon.png", id: "google_icon", onclick: "test_transl()",
remote: true%>
And here is my JS code, currently only with Ajax:
<script>
function test_transl(){
$.ajax({
type: "GET",
url: "/api/translations/translate_string",
dataType: "json",
success:function (result){
console.log(result)
}
})
}
</script>
I expect this ajax code to translate the world 'hello' on German and get value #translated_string - 'hallo' in console but nothing happens except the fact, that the error I got is 'statusText: "parsererror"'. What may be wrong?
I finally found what was wrong with my code. The problem was with fact that I didn't pass sessions token in ajax. So now my ajax code will look like this:
$.ajax({
type: "GET",
headers: {
"Authorization": "Bearer " + window.sessionToken
},
url: "/api/translations/translate_string",
dataType: "json",
success: function(result){
console.log(result);
},
error: function (result){
console.log(result, this.error)
}
})
And def from controller like this:
def translate_string
#translated_string = GoogleTranslator.translate('hello', 'de')
render json: #translated_string.to_json
end
The output in console is: "hallo".

Passing in rails routes to AJAX url value

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

use select2 Auto Tokenization in rails

I use auto tokenization in my rails project.
I want read the tags from database and show to user. I use below code in controller and html file, but don't work for auto tokenization.(this code is ok for other select2, like ajax.)
problems_controller.rb
respond_to :html, :json
def index
#problem = Problem.order('status asc').all
respond_with #problem
end
index.html.erb
<script type="text/javascript">
$(document).ready(function(){
$("#e20").select2({
tags: {
url: "/problems.json",
dataType: "json",
results: function(data, page) {
return {
results: $.map( data, function(problem, i) {
return { id: problem.id, text: problem.status }
} )
}
}
},
tokenSeparators: [",", " "]
});
});
</script>
Where is the problem of my code? Why this code cannot read database information?

Rails Select2 initselection load data from database

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

Rendering JSON from AJAX call in Rails

I have an ajax call to fetch information from Flickr API which returns JSON data. I want to display values from JSON data in my view. I do this by editing some innerHTML with jQuery. The problem I am having is that the data is undefined, so it looks like a scoping problem.
photo.js
jQuery(function() {
$('#<%=p[:id]%>').click(function (e) {
//ajax call to fetch photo info
var fetch_id = '<%=p[:id]%>';
var fetch_secret = '<%=p[:secret]%>';
$.ajax({
type: 'GET',
url: '/photos/fetch_info',
dataType: 'json',
data: { 'id' : fetch_id, 'secret' : fetch_secret },
success: function(data){
console.log(data) //returns Object
console.log(data.title) //returns appropriate title
//edit innerHTML of basic_modal
$('.basic_modal').html(
"<div id='modal_image'><%= escape_javascript(image_tag p[:url]) %></div><div id='photo_title'><%=data.title %></div>"
);
//load modal
$('.basic_modal').modal({
overlayClose:true
});
} //end success: function(result)
});
When I print data.title to console, I get the appropriate title. However, when I try to edit HTML and render <%=data.title %>, I get an undefined variable/method error.
Any tip on how I can display the data in my modal in the view?
Here is my controller:
def fetch_info
#info = flickr.photos.getInfo(:photo_id => params[:id], :secret=> params[:secret])
respond_to do |format|
format.json { render :json => #info }
end
end
var result = jQuery.parseJSON(data);
You donot need to do this, Because datatype:JSON already parse the data
$('.basic_modal').html(
"<div id='modal_image'><%= escape_javascript(image_tag p[:url]) %>
</div><div id='photo_title'><%="+data.title+" %></div>"
);
this might help you

Resources