How to use ajax in Padrino framwork - ruby

I am a newbie of web develop, I am learning padrino framwork. But offical guide is lack of ajax content. Can any one supply me a doc or example for ajax in padrino?
eg,modifiy div .
I wrote a app,but ajax dont works fine.The refresh.js content is displayed on the #cn-status div.Followin is my ruby program
#controller
#----------------------------
get :refresh, :provides => :js do
if request.xhr?
# refresh.js.erb is js file for modify div content
render "aj/refresh", :layout => false
else
redirect url('aj/')
end
end
#link on the other erb file
<li><%= link_to 'get', url(:aj, :refresh, :format => :js), :confirm => "Are You Sure?", :remote => true %></li>
#refresh.js.erb file
$(document).ready(function(){
$("#cn-status").load("/cj/refresh_codename_get",function(responseTxt,statusTxt,xhr){
if(statusTxt=="error")
alert("Error: "+xhr.status+": "+xhr.statusText);
});
});

Related

Using Postmates API in a rails app with HTTParty

I've been working on integrating Postmates with my ecommerce rails application for on demand deliveries. I've built a controller and view for testing purposes and configured it in my routes file (built in my dev environment). For reference, here is the documentation from Postmates: docs and here is a technical blogpost: blog
Routes file:
resources :postmates do
member do
post 'get_delivery'
end
end
The controller:
require 'httparty'
require 'json'
class PostmatesController < ApplicationController
def get_delivery
api_key = **hidden**
#customer = 'cus_K8mRn4ovuNyNKV'
#urlstring_to_post = 'https://api.postmates.com/v1/customers/' + #customer + '/delivery_quotes'
#result = HTTParty.post(#urlstring_to_post.to_str,
:body => { :dropoff_address => "205 E 95th Street, New York, NY 10128",
:pickup_address => "619 W 54th St, New York, NY 10019"
}.to_json,
:basic_auth => { :username => api_key },
:headers => { 'Content-Type' => 'application/json' })
end
end
The view:
<div class="container">
<%= form_tag url_for(:controller => 'postmates', :action => 'get_delivery'), :method => 'post' do %>
<%= submit_tag "Get Delivery", :action => 'get_delivery', :controller => 'postmates'%>
<% end %>
</div>
<p>Result: <%= #result %></p>
Here is the response back from the api:
{"kind"=>"error", "code"=>"invalid_params", "params"=>{"dropoff_address"=>"This field is required.", "pickup_address"=>"This field is required."}, "message"=>"The parameters of your request were invalid."}
It seems to me that the dropoff and pickup address are not being submitted in the HTTP request. Can anyone tell me if I'm making some minor syntax error or something? The fact that I'm getting this response means that my authentication is fine and so is the url. Any ideas?
Thanks.
It looks like you're posting JSON data to the API, while the documentation (https://postmates.com/developer/docs#basics) says you should POST the data as application/x-www-form-urlencoded
I'm not really familiar with HTTParty, but you can probably just remove the .to_json and don't specify the content-type header.
Unrelated to your question, but you shouldn't publicly post your API key. ;)

jQuery Mobile breaks Rails respond_to when using UJS remote links accept headers

I'm converting our Rails 3 web app to use jQuery mobile, and I'm having problems with "remote" links.
I have the following link:
= link_to "Text", foo_url, :method => :put, :remote => true
Which, on the server, I'm handling like this:
respond_to do |format|
if foo.save
format.html { redirect_back_or_to blah_url }
format.json { render :json => {:status => "ok"} }
end
end
This used to work wonderfully. However, since I've added jQuery Mobile, the controller code goes through the "html" branch instead of the "json" one, and responds with a redirect.
I've tried adding
:data => { :ajax => "false" }
to the link, but I get the same effect.
Before jQuery Mobile, UJS was sending the request with the following accept header:
Accept:application/json, text/javascript, */*; q=0.01
while with jQuery Mobile, I'm getting this header:
Accept:*/*;q=0.5, text/javascript, application/javascript, application/ecmascript, application/x-ecmascript
I believe this change in headers is the culprit of the change in server-side behaviour. I haven't been able to debug through the client side to figure out who's doing what exactly. UJS is clearly still doing something, since I'm getting a "PUT request" of sorts, things get routed appropriately, etc, but I'm not sure what's changing the headers.
Thank you!
Daniel
By default remote: true goes to the format.js clause (and searches for some .js.erb template to send back), and defaults to format.html and sends back the html template.
You should use ”data-type” => :json in your link_to call if you want to return json, like:
<%= link_to 'Show Full Article', #article, :remote => true, "data-type" => :json %>
Source: http://tech.thereq.com/post/17243732577/rails-3-using-link-to-remote-true-with-jquery-ujs

Rails 3 Image upload form submitting with http instead of AJAX

I am working on a form to submit it by AJAX instead of http.
This is the form :
<%= form_for(:image, :remote => true, :url => {:controller=> 'questions',:action => 'upload'},:multipart => true) do |f| %>
<%= f.file_field :image, :onchange => "$(this).parents('form').submit();" %>
<% end %>
I have set the :remote => true option above and submitting the form with an onchange event . I have the following code in controller :
def upload
if request.xhr?
#image = Image.new(params[:image])
#image.save
respond_to do |format|
format.js { render :layout=>false }
end
else
render :text => 'Request Wasnt AJAX'
end
end
My action renders the text everytime , the request does not seem to be AJAX style despite the remote tag being set (it appears correctly even in the final HTML). I can't figure out where I am going wrong with this . I have tested it in the latest browser version of FF and Chrome , so I don't think it's a browser issue. Any ideas ?
Update : I did some more debugging attempts . The issue is with the file field , if I replace the file field with text field , the request is AJAX (everything else remaining same) . But with a file field it always sends a non AJAX request.
Note : Overall objective is to upload an image via AJAX request, with the response rendering nothing, no HTML, no redirection, no reload of the page.
Got it to work by installing the Remotipart gem . To upload image files using ajax form submission , this is the only way . Find the git here :https://github.com/JangoSteve/remotipart
JQuery form.sumbit() submits a form the normal way (Not Ajax). You have to do it differently:
$('#submitButton').click( function() {
$.ajax({
url: 'some-url',
type: 'post',
dataType: 'json',
data: $('#myForm').serialize(),
success: function(data) {
// ... do something with the data...
}
});
});

Ruby rails - ajax form_tag isn't making ajax call

I have a form that works on html, I am trying to convert that to ajax. Here is my code, I think the issue is that my form doesn't submit an ajax request, it is still sending normal html request. I get rendered a new page (item/create) with the partial. How do fix this?
<%= form_tag ( :action => :create, :remote => true, :method => :post ) do %>
... #stuff
<% end %>
Controller -
def create
...
respond_to do |format|
format.html { render :partial => 'view_item', :item_num => #t[:item_num], :flag => "new" }
format.js
end
end
JS -
# cat view.js.erb
$('#item').html(<%= (render :partial => 'view_item').to_json.html_safe %>); #I have "item" div in my view
Log -
Started POST "/item/create" for 10.10.23.12 at 2012-04-18 06:41:23 -0400
Processing by ItemController#create as HTML
Parameters: {"utf8"=>"â", "authenticity_token"=>"GRNJAx2ePzRIOaJjr2w4F6WwueRq7FL9tIDaKtIPZSQ=",
.......#long log here
"
(0.1ms) COMMIT
Rendered item/_view_item.html.erb (1.6ms)
Completed 200 OK in 3261ms (Views: 2.4ms | ActiveRecord: 4.1ms)

Rails 3.1 Ajax 500 Error

I'm getting a 500 error when I try to use ajax to delete a post. It works just fine without using ajax.
In the view I have this to delete a post
<%= link_to 'Destroy', post, confirm: 'Are you sure?', method: :delete,:remote => true, :class => 'delete_post' %>
In the controller I have this for the Destroy method.
def destroy
#post = Post.find(params[:id])
#post.destroy
respond_to do |format|
format.html { redirect_to posts_url }
format.js
end
end
In the browser I get a 500 error.
Run Rails 3.1 Ruby 1.9.2-p290 and brand new 3.1 app
What am I doing wrong
It's probably a missing template error. If you don't specify any parameters in a format statement, Rails looks for and loads a file named action . format . template language (destroy.js.erb).
Try something like this:
format.js { render text: "Object successfully destroyed", status: :destroyed }

Resources