Rails - AJAX PUT or PATCH fire several times

I am trying to update a resource attribute via AJAX (using a PUT or PATCH request) and the request is run multiple times.

I am using Angular JS and jQuery.

HTML template

This is what my HTML template looks like -

 <span id="test" ng-click="setValue('test')"></span> 

Javascript Code

This is what my Angular JS code looks like -

 $scope.setValue = function(value){ $.ajax({ method: 'PATCH' // or PUT, url: 'resources/' + $scope.resourceId, data: { test: value } }).success(function(response){ console.log(response); }); }; 

Rails Code

Here's what my controller update method looks like -

 def update @resource.update(resource_params) respond_with(@resource) end 

Screenshots

An AJAX request is run several times (about 15 times). See screenshot below -

enter image description here

By simply changing the PATCH (or PUT ) request to POST , only one will be triggered. See screenshot below -

enter image description here

Is there a reason why PUT requests are run multiple times and a POST request is run only once?

Even if the PUT request updates the value correctly. I would like to prevent his dismissal several times. Is there any way to do this? (Without changing routes or controller methods)

+5
source share
1 answer

The first thing to note: your screenshot from your POST request returns 404, most likely because you are not updating the action of your controller as create instead of updating. (Make sure your routes are configured so that they match.) Since there is no action, Rails returns 404 and it will stop processing.

This is important because your PATCH screenshot looks like it probably redirects itself endlessly. Each PATCH request receives an HTTP 302 Redirect response in response, and since you receive many of them, I assume that it redirects to itself (either the same URL or a URL that redirects to the same controller method ... or other middleware that causes a redirect for any URL).

So, if you changed the action of the controller and the route to allow POST, I bet you will get the same multiple requests and redirects that you get with PATCH.

It solves one secret. The next is to ask why you get endless redirects. I cannot answer this from the information available, but it can make you start a solution.

0
source

Source: https://habr.com/ru/post/1241968/


All Articles