4

I'm trying to build an ajax request that will eventually allow users to sort a list by clicking buttons next to each item. Here's what I have so far:

upLinks.on('click', function(e) {
  var link;
  e.preventDefault();
  link = $(this)[0];
  console.log(link.pathname);
  $.ajax({
    type: 'PUT',
    url: link.pathname
  });
  return false;
});

console.log(link.pathname) logs out /projects/11/project_items/104/sort to the console, as expected. However, the ajax request returns an error:

PUT http://localhost:3000/projects/11 400 (Bad Request)

Looking at the server logs, it is in fact going to /projects/11, not /projects/11/project_items/104/sort for some reason. According to the jQuery docs, /projects/11 would be the default parameter for ajax in this case, because that's the route of the current page. Which leads me to believe it's ignoring the url parameter altogether.

If I change HTTP method type to GET, the ajax runs as expected. Is there some reason /projects/11/project_items/104/sort is not an acceptable url for a PUT request? I thought that because I'm updating data (with the new position) a PUT request would be the most logical option.

Shaun
  • 2,012
  • 20
  • 44
  • 1
    Try doing a network trace (press F12 in Chrome|Firefox and go to Network) to see what's actually being sent. – amphetamachine Jan 13 '15 at 15:19
  • 2
    Depends if the server can accept PUT requests – pee2pee Jan 13 '15 at 15:20
  • @amphetamachine Thanks for the tip. Through the network tab I was able to see that the PUT request was actually being sent successfully, but then the server was attempting a redirect that triggered the error. So this was a server-side issue. – Shaun Jan 13 '15 at 17:57

1 Answers1

3

Just a note, if you're using an IIS webserver and the jquery PUT or DELETE requests are returning 404 errors, you will need to enable these verbs in IIS. I've found this to be a good resource: http://geekswithblogs.net/michelotti/archive/2011/05/28/resolve-404-in-iis-express-for-put-and-delete-verbs.aspx

"The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers." from: http://api.jquery.com/jQuery.ajax/#options

Reference stack question: How to send a PUT/DELETE request in jQuery?

Community
  • 1
  • 1
indubitablee
  • 8,136
  • 2
  • 25
  • 49
  • 1
    The question is showing that the URLs are going to the wrong place though – Quentin Jan 13 '15 at 15:28
  • @Quentin but OP said that when the request is changed to "GET", it works as expected, so its not the url, but the "PUT" request, which this answer addresses – indubitablee Jan 13 '15 at 15:30
  • 1
    @indubitablee Assuming it's a problem on the server rather than the client. If it's the client mangling the URL in the PUT request, changing stuff on the server won't help. – James Thorpe Jan 13 '15 at 15:37