I'm having a hard time trying to make jquery.form with a cross-domain request. I'm having issues with Firefox and Chrome (didn't even try IE yet).
Explanation: my whole site is located inside http://www.mysite.com. However, my contact form is on another server, referenced by http://contact.mysite.com . I thought that putting it on a subdomain would sidestep the issues regarding cross-domain requests, but apparently it didn't. http://contact.mysite.com is implemented in Sinatra.
My javascript setup is nothing fancy. The form's action points to http://contact.mysite.com and the method is POST:
<form id="contact" action="http://contact.mysite.com/" method="post">
jquery.form is configured with an ajaxForm call:
$(document).ready(function() {
$('#contact').ajaxForm({
success: function() { $('#success').fadeIn("slow"); },
error: function() { $('#error').fadeIn("slow"); }
});
});
The first problem I encountered was with Firefox 3.5 - apparently it sends an OPTIONS request expecting an specific answer from the server. I used this question to configure my Sinatra app so it did what was expected (it seems that more recent versions of sinatra include an options verb):
require 'rubygems'
require 'sinatra'
require 'pony'
# patch sinatra so it handles options requests - see https://stackoverflow.com/questions/4351904/sinatra-options-http-verb
configure do
class << Sinatra::Base
def options(path, opts={}, &block)
route 'OPTIONS', path, opts, &block
end
end
Sinatra::Delegator.delegate :options
end
# respond to options requests so that firefox can do cross-domain ajax requests
options '/' do
response['Access-Control-Allow-Origin'] = '*'
response['Access-Control-Allow-Methods'] = 'POST'
response['Access-Control-Max-Age'] = '2592000'
end
post '/' do
# use Pony to send an email
Pony.mail(...)
end
With jquery 1.4.3, I saw on firebug an OPTIONS request followed by a POST request (status 200. The email was sent). With jquery 1.3.2 or 1.5, only the OPTIONS request was shown (the email was not sent).
Nevertheless, the error
callback is always fired with all versions of jquery I tried. I traced that down to the $.ajax(...)
call, so I'm not sure of whether this problem comes from jquery.form or jquery itself.
I tried logging out the information coming from the error:
$('#contact').ajaxForm({
success: function() { $('#success').fadeIn("slow"); },
error: function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR.status);
console.log(jqXHR.statusText);
}
});
Output on jquery 1.4.3 (after the OPTIONS & POST requests are sent, both with status 200):
0
(empty string)
Output on jquery 1.5 (after OPTIONS returns with a 200 status; POST is never sent)
302
error
I'm really lost here.
- Is there a plugin that handles this?
- Am I missing something somewhere?
Any help will be greatly appreciated.
See Question&Answers more detail:
os