jquery.form and cross-domain requests

12,466

Solution 1

AJAX requests cannot be executed cross-domain (UPD: not true anymore, all modern browsers support CORS), but you can use JSONP instead. Although JSONP works cross-domain, it can't be used for POST requests, and you'll need to change you form's method to get and use this:

$('#contact').ajaxForm({
  success: function() { $('#success').fadeIn("slow"); },
  error: function() {  $('#error').fadeIn("slow"); },
  dataType: 'jsonp'
});

The solution above relies on your server responding with a valid jsonp response, otherwise success handler won't be executed. e.g: response.write(request.callback + '(' + result.to_json + ')')


Latest versions of jQuery can serialize forms without the ajaxForm plugin. If you don't need file uploads you can use this:

$('form').submit(function() {
  var url = $(this).attr('action')
  var params = $(this).serialize()
  $.getJSON(url + '?' + params + "&callback=?", function(data) {
    // success
  })
  return false
});

Solution 2

You can also use a local proxy URL to perform the request as servers can generally make cross-domain calls using something like HttpRequest or cURL. So basically you make a call using ajax to a URL on the local domain and then forward the request to the cross-domain URL and pass the response from the HttpRequest/cURL back to the browser in the response from the local domain.

Solution 3

I think JSONP the only AJAX request which can cross domain.

http://en.wikipedia.org/wiki/JSON#JSONP

Solution 4

After lots of fighting, I finally ended up conquering this, with the help of Alexey. Here's my solution, for now:

Javascript (using jquery directly, without jquery.form):

$(document).ready(function() {
  $('#contact').submit(function() {
    $('#success').fadeOut("slow");
    $('#bademail').fadeOut("slow");

    var url = $(this).attr('action')
    var params = $(this).serialize()
    $.getJSON(url + '?' + params + "&callback=?", function(data) {
      if(data == true) { // success
        $('#success').fadeIn("slow");
        $('#contact')[0].reset();
      } else { // error
        $('#bademail').fadeIn("slow");
      }
    });

    return false;
  });
});

With Sinatra, I used the sinatra-jsonp gem. I make the get action return "true" or "false" depending on whether the emails can be sent or not (for example, for an invalid email address).

require 'rubygems'
require 'sinatra'
require 'sinatra/jsonp'
require 'pony'


get '/' do

  # check for blanks, etc
  return jsonp false unless fields_valid(params)

  Pony.mail(
    ...
  )

  return jsonp true

end
Share:
12,466
kikito
Author by

kikito

scripted: ruby on rails, javascript, lua compiled: C++, Java Opensource when possible, thanks.

Updated on June 04, 2022

Comments

  • kikito
    kikito almost 2 years

    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.