Send data in params to rails back end using jQuery ajax get
You can send information to a page with get
via the query-string, then this can be used to populate fields in the new
view which is where the form is that eventually submits to the create action.
However, this will also return the body of the new action view in the response, which you may want if you're using this to asynchronously pull that page in for a dialog or something.
It might be better, if you're using this ajax call to create a post, to post
to a /create
action on the posts controller.
Then you can send the data in JSON as a post
and the object will translate into the params
hash when your controller goes to parse it and create the post.
js in the view:
var url = '/users/' + userId + '/posts/create';
var myLoc = { 'lat': 35, 'lon': -110 };
$.ajax({
type: "POST",
url: url,
data: myLoc
});
in routes.rb:
match 'users/:user_id/posts/create' => 'posts#create', :via => :post
in posts_controller.rb:
def create
post = Post.new(params[:myLoc])
if post.save!
render :status => 200
else
# exception handling
end
end
Comments
-
natecraft1 almost 2 years
This has confused me on several different occasions and each time I struggle to find a good answer on the Internet or the World Wide Web. Let's say that in my javascript file I have a variable
var myLoc = { lat: 35, lon: -110 }
that I got from using geolocation whatnot. I want to send this information to the backend in order to associate it with a specific post I'm going to create.
Assume my routes are just this:
resources :users do resources :posts end
I don't know if this is the correct way, but what comes to mind is something like this:
$.get('/users/' + JSON.stringify(myLoc) + '/posts/new', function() {console.log("please work")});
My questions are:
A. Should this work?
B. Is it the right way to do this?
C. Can you send front-end stuff like this to any route in the backend?Much appreciated.
-
Matthew Blancarte over 10 years
A.
You kind of have the right idea.B.
No, you should specify an API namespace and routes within your rails app. Ideally, your API would respond back to jQuery AJAX requests with JSON. You are also using$.get
incorrectly. You should go read the documentation on that jQuery method.C.
Yes, but the route may not like it. See answerB
. -
natecraft1 over 10 yearsHow does the API namespace work? do u have a good link to info on that
-
-
prasad.surase over 10 yearsu dont need to specify the 'create' in the url explicitly and dont implement the match. A POST request to /users/user_id/posts will map to 'create' method in posts_controller.rb
-
Mike Lyons over 10 yearsAh you are correct! It is a feature of resource routing as seen here: guides.rubyonrails.org/routing.html#crud-verbs-and-actions
-
natecraft1 over 10 yearsi dont get what this means "However, this will also return the body of the new action view in the response, which you may want if you're using this to asynchronously pull that page in for a dialog or something." and can i send information like this using any route? even without a parameter, for instance get '/show_posts'?
-
Mike Lyons over 10 years
Get
is the same type of request a web browser makes when you visit a URL in the address bar, so you'll get the HTML of the page you request in the response, if you are trying to then inject that into the page you're making the ajax request from, it can be useful, but otherwise it's not a good way to send data via ajax andpost
would be better. Making a request to a route, without parameters, is not sending any information to that action. I'm not sure what you're asking. -
natecraft1 over 10 yearsso you can send it to any 'get' route with parameters and even if the param is something like :user_id you can send any piece of data and just access it as :user_id?
-
Mike Lyons over 10 years
Get
typically requires the query-string, so if youget /users?userId=1
you can then haveparams[:userId] == 1
available to you in the controller on that action. But with resourceful routes, you'll only be able toget
certain routes and be required topost
put
ordelete
to others. In the case ofput
ordelete
you'd use$.ajax
instead of$.post
parameters built into the route like/users/:user_id/posts
are different because they don't use the query-string to assign the parameter, but can still be handled inget
requests. See the link in my comment above. -
Sean Magyar over 8 yearsMike Lyons, could you please take a look at this issue: stackoverflow.com/questions/34323316/…? It is the extension of this question with nested resources + passing vars from rails to browser. An answer would save my life. Thanks in advance!