Search code examples
javascriptjqueryajaxposthttp-status-code-400

AJAX post url returning 400 (bad request)


I'm using some simple AJAX page transition on a Craft CMS site, very similar to these instructions: https://designbycosmic.com/journal/craft-cms-ajax-page-transitions-with-history-pushstate

The basic structure of my code is this:

$.ajax({
  type: 'POST',
  url: href,
  data: {},
  success: function(result){
    // hide old content, load new content, fade in new content
  },
  error: function(){
    console.log("ajax error");
  }
});

"href" is the link to new page to load.

I'm always getting a 400 (Bad Request) error.

I'm using this exact same method for a similar site on the exact same hosting environment and it works fine, so I'm banging my head as to why this would be acting differently.

All of the other answers on this subject seem to be for when "data" is not formatted correctly, but none address the issue when you're simply loading a URL, with no other data.

In this case, what would cause a 400 error?


UPDATE

OK here's the live site for anyone who is kind enough to help further investigate: http://mearch.nz/

Still very incomplete and under development. You should be able to navigate between Home, Projects, and and then any project detail page linked from the Projects index. You'll see that the loading indicator just gets stuck there and the new page never arrives because the AJAX fails.

If you reload any of those pages they work fine. Nothing wrong with the URL. For some reason it's just not accepted as proper data for the AJAX POST.

Now for comparison, here's another website on the same web host, using the same AJAX functions, and same CMS, and it works fine: http://benek.nz/


Solution

  • http:// mearch.nz/projects/ does not reference http:// mearch.nz/js/init.js. But init.js needs to be loaded since it contains your javascript-code! In contrast http://benek.nz does reference init.js and therefore it works.

    Looks like you use minmee on http:// mearch.nz and therefore it is a bit difficult to debug your issue.

    It seems that your request has an CSRF-issue. This normally happens if javascript sends a request to a web-server, which is different to where the javascript comes from.

    This is what I did to reproduce your issue:

    • navigated to http://mearch.nz/projects/
    • clicked on link "projects"
    • In Google Chrome: the console window writes "... 400 (Bad Request)"
    • In Google Chrome in the network tab under response I see the server also sent HTML containin text "Bad Request" and "The CSRF token could not be verified."