Jeremy Thomas Jeremy Thomas - 1 year ago 175
Javascript Question

Rails 4 + jQuery: PUT ajax request

Ajax requests are still pretty new to me, but I have a recipe index with a button that allows you to favorite recipes.

<i class="favorite" data-recipe="<%= %>">

... I am trying to use a PUT request to the route:

favorite_recipe PUT /recipes/:id/favorite(.:format) recipes#favorite

... using the following jQuery function:

var recipe_id = $(this).data("recipe");

// displays properly when I console.log() it
var url_path = '/recipes/' + recipe_id + '/favorite'

url: url_path,
type: 'PUT'

but in my developer console, I get a 404 error and the url shown is
Request URL:http://localhost:3000/recipes
rather than

What am I doing wrong? Do I need to use the data parameter to supply the id?

Answer Source

Ok, I'm changing my answer because I noticed you DO have a route for that request.

I believe you're getting this error because you're not handling the request properly in your controller. Try to add the following to your controller, to make it handle JSON requests.

respond_to do |format|
      format.json do
        render :json => {success: 'yes'}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download