Prototype AJAX request being sent as OPTIONS rather than GET; results in 501 error

Too many hours looking for a correct fix on prototypejs… finally, we have a non-intrusive solution on great kourge (Wilson Lee) article!. Here is an excerpt:

Most major Ajax frameworks like to set custom HTTP headers on the Ajax requests you instantiate; the most popular header is X-Requested-With: XMLHttpRequest. Consequently your request is promoted to a preflighted one and fails. The fix is to prevent your JavaScript framework from setting these custom headers if your request is a cross-domain one. jQuery already cleverly avoids unintentionally preflighting requests by not setting custom headers if your URL is considered to be remote. You’d have to manually prevent this if you’re using other frameworks.

It can be so simple as:

new Ajax.Request('http://www.external-domain.net/my_api.php?getParameterKey=getParameterValue', {
            method:'post',
            contentType:"application/x-www-form-urlencoded",
            postBody:'key=' + value,
            onSuccess: function(response) {
                // process response
            },
            onCreate: function(response) { // here comes the fix
                var t = response.transport; 
                t.setRequestHeader = t.setRequestHeader.wrap(function(original, k, v) { 
                    if (/^(accept|accept-language|content-language)$/i.test(k)) 
                        return original(k, v); 
                    if (/^content-type$/i.test(k) && 
                        /^(application\/x-www-form-urlencoded|multipart\/form-data|text\/plain)(;.+)?$/i.test(v)) 
                        return original(k, v); 
                    return; 
                }); 
            } 
        });

If you see any disadvantage/improvement to this solution, we welcome you to share 🙂

Leave a Comment