My goal is to render html from an AJAX call. Changing the dataType to 'html' in my AJAX call seemed to work in that on my console it happily claims that the render was successful:
Rendered admin/articles/show.html.erb within layouts/application (108.1ms)
Completed 200 OK in 185ms (Views: 112.6ms | ActiveRecord: 2.8ms)
but the page does not change.
Here's some code:
View:
<span id='show' class="ui-icon ui-icon-extlink" article_id=<%=article.ID %> onmouseover="this.style.cursor='pointer'"></span>
jquery:
$('#show').live("click",function(evt){
evt.preventDefault();
var article_id=$(this).attr("article_id");
$.ajax({
success : null,
type : 'GET',
url : '/admin/articles/show',
dataType : 'html',
data: {
id: article_id
},
});
});
and my controller:
def show
#article = Article.find(params[:id])
respond_to do |format|
format.html
format.xml { render :xml => #article }
end
end
routes.rb
match 'articles/show' => 'articles#show', :via => :get
I know it's an odd request to want to render html from AJAX but it's the easiest way that I can think to have a clickable link contained in a span tag.
Using Rails 3.0.1, Ruby 1.9.2 and JQuery
usually ajax request ha js type,if you can change type to js these changes will works
controller
def show
#article = Article.find(params[:id])
respond_to do |format|
format.html
format.js
format.xml { render :xml => #article }
end
end
then in app/views/articles/show.js.erb write javascript code to update page content like
$("#yourDiv1").html("blah blah");
$("#yourDiv2").html("whatever");
and following approach will work for both html and JS
$.ajax({
success : null,
type : 'GET',
url : '/admin/articles/show',
dataType : 'html',
data: {
id: article_id
},
}).done(function( html ) {
$("#yourDIv").html(html);
});
Related
Load table with Kaminari pagination using AJAX.
The pagination itself is using AJAX as well.
In my controller:
def update_user_list
modal = render_to_string('tables/_user_table', :layout => false, :formats=>[:html]).html_safe
data = {
:table => modal
}
respond_to do |format|
format.json { render :json => data }
end
end
In tables/_user_table
# Table part and content notrelated
<%= paginate #users, :params => {:controller => 'product', :action => 'more_users'}, :remote => true, :theme => 'twitter-bootstrap-3' %>
The response JSON of update_user_list looks like:
{
table=" // the table part
// the pagination part shows as follows
<li class="page">3</li>
<li class="page">4
"
}
What I want is to remove ".json" in the url.
If I just render tables/_user_table without AJAX, not in a JSON object, it doesn't have ".json" in the url.
version:
rails: 3.2.17
kaminari: 0.13.0
bootstrap-kaminari-views: 0.0.3
Find the problem. It's actually not included in the question.
$.ajax({
url: '<%= user_product_index_url %>.json',
success: function(data) {
// not important......
});
remove ".json" here solve the problem...
I'm getting an error: No route matches {:action=>"sort", :controller=>"links"}
I'm adapting from a non-nested example and am having trouble figuring out the nested routing.
Right now, my route looks like this:
resources :groups do
resources :navbars do
resources :links do
collection { post :sort }
end
end
post :add_user, on: :member
end
I am rendering a collection of links from navbar>show:
= render partial: 'links/link', collection: #navbar.links
and here's the collection, links>_link.html.haml:
%ul#links{"data-update-url" => sort_group_navbar_links_url}
- #links.each do |faq|
= content_tag_for :li, link do
%span.handle [drag]
= link.method_name
= link.code
= link.button
= link.text
= link_to 'Edit Link', edit_group_navbar_link_path(#group, #navbar, link), class: 'btn btn-mini'
= link_to 'Delete', group_navbar_link_path(#group, #navbar, link), data: { confirm: 'Are you sure?' }, method: :delete, class: 'btn btn-mini'
My links_controller has the sort action:
def sort
params[:link].each_with_index do |id, index|
Link.update_all({display_order: index+1}, {id: id})
end
render nothing: true
end
Because my link collection is being rendered from the navbar>show page, it's not clear to me where my sort action should be located (in links_controller or in navbars_controller).
And my navbars_controller defines #links:
def show
#links = #navbar.links.order("display_order")
respond_to do |format|
format.html # show.html.erb
format.json { render :json => #navbar }
end
end
Also here's the js for good measure (links.js.coffee):
jQuery ->
$('#links').sortable
axis: 'y'
handle: '.handle'
update: ->
$.post($(this).data('update-url'), $(this).sortable('serialize'))
Maybe this last line also needs work to include the route?
I'm using rails 3.2.
How do I execute a jquery js after rendering a json page?
respond_to do |format|
format.html
format.json { render :partial => "tables" }
format.js
end
The tables.json.erb gets rendered but the js.erb file does not.
The code in js.erb won't be executed, it's for js response.
You should write the code in the ajax success callback function.
For example:
$.getJSON('your_request_uri', function(data){
// write your code here.
});
I'm trying to upload a video using uploadify and paperclip on rail 3.1
When i upload a video with uploadify, the server returns an 500 error.
The development.log says:
Started POST "/videos" for 127.0.0.1 at Tue Oct 04 14:46:05 +0200 2011
Processing by VideosController#create as HTML
Parameters: {"Filename"=>"prova.mov", "folder"=>"/public",...}
WARNING: Can't verify CSRF token authenticity
#<Video id: nil, source_content_type: nil, source_file_name: nil, source_file_size:nil, state: nil, created_at: nil, updated_at: nil>
[paperclip] Saving attachments.
Completed 500 Internal Server Error in 29ms
ActionView::MissingTemplate (Missing template videos/create, application/create with {:locale=>[:en, :en], :handlers=>[:builder, :coffee, :erb], :formats=>[:html]}. Searched in:
* "($mypath)/workspace/Video_Api/app/views"):app/controllers/videos_controller.rb:48:in `create'.
This is my controller:
def create
logger.info(params.inspect)
#video = Video.new(params[:video])
logger.info(#video.inspect)
respond_to do |format|
if #video.save
format.html
format.json { render :json => #video, :status => :created, :location => #video }
else
format.html { render :action => "new" }
format.json { render :json => #video.errors, :status => :unprocessable_entity }
end
end
end
And this is my uploader:
<input id="upload" type="file" name="upload" />
<!--div class="button" id="send_button">SEND FILE</div -->
</div>
<script>
<%- session_key = Rails.application.config.session_options[:key] -%>
$('#upload').uploadify({
'uploader' : 'uploadify.swf',
'script' : '/videos',
'cancelImg' : 'images/cancel.png',
'folder' : '/public',
'buttonText' : 'Add video!',
'multi' : true,
'auto' : true,
'scriptData' : {"<%= key = Rails.application.config.session_options[:key] %>" :"<%= cookies[key] %>",
"<%= request_forgery_protection_token %>" : "<%= form_authenticity_token %>",
},
onError : function (event, id, fileObj, errorObj) {
alert("error: " + errorObj.info);
}
});
Any ideas?
The error is pretty straightforward -- it is saying that you are missing a template to render videos/create -- if you're trying to render HTML here, you'll need to create this template. If you're expecting your JSON response instead, you need to figure out why that isn't being triggered. Changing the 'script' parameter to be '/videos.json' should take care of that, although it might be smarter to use the Rails helper url_for.
I am trying to upload an image from iPhone to my working rails application that uses Carrierwave for processing. Do I need to account for the CSRF authenticity token that rails requires?
I have the following in my Titanium app.js file, taken pretty much from their Snapost example code:
xhr.open('POST','http://myapp.com/foos/1/bars');
xhr.send({media:originalImage});
My rails action is very simple:
def create
#bar = #foo.bars.build(params[:bar])
#bar.image = params[:file]
respond_to do |format|
if #bar.save
format.html { redirect_to(#foo, :notice => 'Bar was successfully created.') }
format.json { render :json => #bar, :status => :created }
fotmat.xml { render :xml => #bar, :status => :created }
else
format.html { render :action => "new" }
format.json { render :json => #bar.errors, :status => :unprocessable_entity }
format.xml { render :xml => #bar.errors, :status => :unprocessable_entity }
end
end
end
From my device, I get the 'xhr.onerror' alert describing a timeout when I attempt an upload. My server log is as follows:
Started POST "/foos/1/bars" for ###.###.#.### at 2011-05-01 17:01:33 -0500
Processing by BarsController#create as MULTIPART_FORM
Parameters: {"media"=#<ActionDispatch::Http::UploadedFile:0xabdd968 #original_filename="285050.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"media\"; filename=\"2
85050.jpg\"\r\nContent-Type: image/jpeg\r\n", #tempfile=#<File:/tmp/RackMultipart20110501-32635-olgooh>>, "foo_id"=>"1"}
^[[1m^[[36mSQL (1.9ms)^[[0m ^[[1mSHOW TABLES^[[0m
^[[1m^[[35mFoo Load (0.1ms)^[[0m SELECT foos.* FROM foos WHERE foos.id = 1 LIMIT 1
^[[1m^[[36mSQL (2.6ms)^[[0m ^[[1mBEGIN^[[0m
^[[1m^[[35mSQL (5.9ms)^[[0m ROLLBACK
Completed 406 Not Acceptable in 468ms
You are correct, it is the authenticity token (or lack there of) that is causing the problem. How do I ignore the authenticity token for specific actions in Rails? has more details on how to have it ignored. More details at http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection.html