A ‘Heads’-up about access control orgins and setting content-type

I’m not really sure if this happens on every server, but I recently came across a little annoyance that had me locked up for the greater part of 3 hours trying to figure out what was wrong. I had a javascript application doing an ajax call over to a different server. I wasn’t doing anything fancy, just using jQuery, etc, and using JSON to send data to the remote server.

The first thing to know about trying to do ajax calls to another server is that you need to set your header orgin access control allowances. The easiest way to do this is to edit your .htaccess and drop these lines in somehere at the bottom:

Header add Access-Control-Allow-Origin “*”
Header add Access-Control-Allow-Headers “origin, x-requested-with, content-type”
Header add Access-Control-Allow-Methods “PUT, GET, POST, DELETE, OPTIONS”

After doing this the remote calls started going through for me, but then they started getting duplicated as well. The strange thing is that the chrome developer console didn’t show duplicate ajax calls being sent out!

The problem ended up being that my server didn’t like that I was trying to set the content-type property from my java-script AJAX request so for some reason it was failing in its response back to the client and attempting to redo the server call as a POST request… It is a very weird reaction from the server and caused duplicate actions on the server-side per each single AJAX call on the server side. It was near impossible to prevent with a hack-fix because the issue is controlled neither by the client javascript code, nor the server application code.

The solution? Make sure you don’t try to set the content-type in your ajax call to the server. That means if you’re using the jQuery ajax function then don’t set the contentType attribute. Removing the contentType from my ajax calls solved this crazy problem for me. I hope my solution helps someone else! 



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s