Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send data in params to rails back end using jQuery ajax get

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.

like image 514
natecraft1 Avatar asked Oct 31 '13 05:10

natecraft1


1 Answers

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
like image 97
Mike Lyons Avatar answered Nov 14 '22 21:11

Mike Lyons