Jeremy Thomas Jeremy Thomas - 1 month ago 16
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="<%= recipe.id %>">


... 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:

$(".favorite").click(function(){
$(this).toggleClass("favorited");
var recipe_id = $(this).data("recipe");

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


$.ajax({
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
http://localhost:3000/recipes/:recipe_id/favorite
.

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

Answer

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'}
      end
end
Comments