JqueryUI autocomplete in Rails3 - ruby-on-rails

$(document).ready ->
$('#auto').autocomplete( source: "main/search" )
the code beyond set up the autocomplete env,'#auto' is an input filed.
In my main controller I got the search action
def search
#user = User.find_by_name 'castiel'
respond_to do |format|
format.json { render :json => #user.to_json(:only => :name) }
end
end
everything seems working perfectly fine.When I type in a char,let's say a "c",so the ajax request was sent and received the json data.
In firebug, it shows the ajax request successfully get the json data below
{"name":"castiel"}
so far so good,but the json data's type is not the kind that autocomplete demanded.It demands that json data is like below.
{"id":"castiel", "label":"castiel", "value":"castiel"}
So here is problem,how to modify the josn data to the kind that I wanted.

In the success function, you need to return something like
.autocomplete({
source: function(request, response){
$.ajax({
url: "main/search",
dataType: "json",
data: {
style: "full",
maxRows: 12,
term: request.term
},success: function( data ) {
response( $.map( data, function( user ) {
return {
label: user.name,
value: user.id
}
}));

Rails allows you to serve JSON in any structure from your controller. When using the jQuery autocomplete helper, you serve JSON back in the format needed by using the autocomplete library method json_for_autocomplete as follows:
# app/controllers/example_controller.rb
def autocomplete_example
items = Example.where(...)
respond_to do |format|
format.json do
render :json => json_for_autocomplete(items, 'name', [])
end
end
end
The first argument to json_for_autocomplete is your collection of objects to return. The second is the method to call on those objects to define the values in the JSON hash. The final argument is for any extra options, which can be found at:
https://github.com/crowdint/rails3-jquery-autocomplete/blob/master/lib/rails3-jquery-autocomplete/autocomplete.rb

Related

How do I tell my Rails controller to use the format.json part of my method instead of the format.html branch?

I'm running Rails and trying to set up an autocomplete on my text field. I want to submit to a controller method. If I'm submitting from my form (using the "Submit" button), I'd like to use the "format.html" branch. If I'm submitting using the autocomplete Ajax call, I'd like to use the "format.json" branch ...
def search
if params.has_key?("s")
search = params[:s].strip
#people = Person.where("name ilike ?", "%#{search.upcase}%")
respond_to do |format|
format.html {
if #people.size == 1
redirect_to controller: 'votes', action: 'show', id: #people.first.id
end
}
format.json { #people.map(&:name) }
end
end
end
I set up the autocomplete on my text field like so
$(function() {
return $('#s').autocomplete({
source: function(request, response) {
$.get('/people/search', { s: request.term }, function(data) {
alert(data)
response(data.split('\n'));
});
}
});
});
but what's happening is the value of "data" is an HTML page, as if I were submitting via the format.html method. How do I configure things so that my autocomplete call forces me to render the JSON response from my controller?
Specify .json format in the url like this -
$.get('/people/search.json', { s: request.term }, function(data) {
alert(data)
response(data.split('\n'));
});
To send raw json data In Controller change. Otherwise it will look for template to build json (by default rails will look for search.json.jbuilder)
format.json { render json: {people: #people.pluck(:name)} }

Rails ajax request response

I am using Rails CoffeeScript to call an action in my controller, which is fine, but I can not get the response to work.
I have a form with a list of budget lines. I want to allow the use to add a new line using CoffeeScript so I don't need to reload the question.
I have got the following in CoffeeScript:
$("button[id^='new_budget_line']").on 'click', (event) ->
category_id = $(this).attr('name')
child_economy_id = $('#child_economy_id').val()
$('#form_id').submit ->
valuesToSubmit = $(this).serialize()
$.ajax
type: 'POST'
url: $(this).attr('action')
data: valuesToSubmit
dataType: 'JSON'
$.ajax({
type: 'GET'
url: '../child_economy_lines/create_line'
data:
child_economy_id: child_economy_id
category_id: category_id
cost_type: 'direct'
dataType: JSON
}).done (response) ->
alert "Hey"
$('#test_append').html("Hey you now!!")
And the following in my controller
def create_line
logger.debug "Hejsa fra create line - category id #{params[:category_id]}"
#child_economy_line = #child_economy.child_economy_lines.build(:child_economy_category_id => params[:category_id], :cost_type => params[:cost_type])
if #child_economy_line.save
respond_to do |format|
format.js {render nothing: true}
format.json {render :json => "test"}
end
end
end
The action in the controller i called fine, and the new line is created, but I can not the actions after the ajax call to work. The part from .done ...
Can anybody help me identify where it is going wrong?

how to set session variable with ajax request on rails?

I need to set session variable on ajax call on rails. I have following ajax code:
$.ajax({
url: '/dashboard/set_session',
type: 'GET',
data: {
site_id: site_id
},
dataType : 'json'
}).done(function(data){
console.log(data);
});
And on rails end:
def set_session
puts params[:site_id]
session[:site_id] = params[:site_id]
puts session[:site_id]
respond_to do |format|
format.json { render json: 'success'}
end
end
The first and second puts print same value. That means the session is set. But when I navigate to other pages or reload the page, the session value of site_id is cleared.
How to fix this issue?

Rails ajax update

I would like to change a Workorder.wostatus_id based on data in html.
In my index html, I have the wostatus.id stored like this:
<span id="woid">4</span>
I would like to update the workorder.wostatus_id = 4
This is in the workorders.js.coffee - but, it's not working:
$.ajax
type: 'POST'
url: 'http://localhost:5000/workorders'
data:
workorder:
wostatus_id: $("#woid").val()
Maybe I'm not getting to the right workorder record?
Even doing this didn't update the workorder.wostatus_id
$.ajax
type: 'POST'
url: "http://localhost:5000/workorders"
data:
workorder:
wostatus_id: '3'
This didn't work either:
$.ajax
type: 'POST'
url: "http://localhost:5000/workorder/17"
data:
wostatus_id: '7'
I'm missing something big time.
Does the ajax POST execute this code in the workorder controller????
# PUT /workorders/1
# PUT /workorders/1.json
def update
#workorder = Workorder.find(params[:id])
respond_to do |format|
if #workorder.update_attributes(params[:workorder])
format.html { redirect_to #workorder, notice: 'Workorder was successfully updated.' }
format.json { head :ok }
else
format.html { render action: "edit" }
format.json { render json: #workorder.errors, status: :unprocessable_entity }
end
end
UPDATE:
I added this to the workorder controller:
def changestatus
#workorder = Workorder.find(params[:id])
#workorder.update_attribute :wostatus_id, '4'
render nothing: true
end
I added this to the routes:
resources :workorders do
member { put :changestatus }
end
This is currently in the js.coffee:
$.ajax
type: 'PUT'
url: "http://localhost:5000/workorders/11/changestatus"
data:
wostatus_id: 4
(I'm hard coding things until I get the next step working.)
SO - this works, workorder 11 gets wostatus_id changed to 4.
But, now I'm having trouble getting the right information from the html.
The html contains 2 data fields I need - one for which workorder and the other is what the wostatus_id is.
Here is the html for the update url:
<div class="false" data-change-url="http://localhost:5000/workorders/16/changestatus">
I thought this would get that url - but, it doesn't work:
$(this).data('change-url')
If I understand correctly, then I think your sending a single value while your controller expects an array, and you're using different param names (wostatus_id on client, workorder on server).
Perhaps what you want is this:
$.ajax
type: 'POST'
url: $('#sort2').data('update-url')
data:
workorder: $('#sort2 span').map((i, el) ->
el.text()
) // Change the selector to the elements that holds the ID
Found out I didn't need any new controller code - I could just use update.
This is for jquery-ui sortable.
receive: (event, ui) ->
str_id = $(ui.item).attr('id')
woid = str_id.split('_')[1]
$.update "/workorders/" + woid,
workorder:
wostatus_id: $(this).data('wostatus-id')
Thanks for the help - you got me going in the right direction.

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