jQuery cross domain POST shenanigans

21,201

Solution 1

You should follow a different pattern. Your local JS will do an ajax post to a local URL which will accept the POST method with your json data.

At this point your server code will do an HTTP POST with proper data to the remote server, get the response, and send it back to the calling js.

Solution 2

The problem is that the domain you are trying to POST to doesn't respond to the OPTIONS request that is sent before each cross-domain request. With the OPTIONS request, the browser receives information about cross domain rules etc. To enable the cross domain request, the server has to set Access-Control-Allow-Origin:* (or the domain of the script, actually, but * covers everything) and maybe Access-Control-Allow-Methods: GET, POST, OPTIONS headers.

Solution 3

I have a shared hosting on GoDaddy. I needed an answer to this question, too, and after searching around I found that it is possible.

I wrote an .htaccess file, put it in the same folder as my action page. Here are the contents of the .htaccess file:

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"

Here is my ajax call:

    $.ajax({
        url: 'http://www.mydomain.com/myactionpagefolder/gbactionpage.php',  //server script to process data
        type: 'POST',
        xhr: function() {  // custom xhr
            myXhr = $.ajaxSettings.xhr();
            if(myXhr.upload){ // check if upload property exists
                myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // for handling the progress of the upload
            }
            return myXhr;
        },
        //Ajax events
        beforeSend: beforeSendHandler,
        success: completeHandler,
        error: errorHandler,
        // Form data
        data: formData,
        //Options to tell JQuery not to process data or worry about content-type
        cache: false,
        contentType: false,
        processData: false
    });

See this article for reference:

Header set Access-Control-Allow-Origin in .htaccess doesn't work

Share:
21,201
FLX
Author by

FLX

Updated on May 03, 2020

Comments

  • FLX
    FLX about 4 years

    I'm trying to authenticate to an API, which only allows you to authenticate using a POST with JSON as form data, in the format of {"username":"myusername","password":"mypassword"}.

    I've been trying for two days to get this working with jQuery but I'm running into problems because it's cross domain. How can I accomplish this?

    Error message:

    Request Method:OPTIONS
    Status Code:405 METHOD NOT ALLOWED
    

    Code up till now:

    var username = "myusername";
    var password = "mypass"
    var authurl = "https://myurl";
    
    $.ajax
    ({
        type: "POST",
        url: authurl,
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        async: false,
        data: {'json':'{"username":"' + username + '", "password":"' + password + '"}'},
        success: function (result) {
            $('#json').html(result);
        }
    })
    

    To summarize:

    • API only accepts POST for auth
    • API requires json as form data, example: {"username":"myusername","password":"mypassword"}
    • The js is ran from a different domain, causing cross domain errors

    Your help is much appreciated :)

  • FLX
    FLX almost 13 years
    Thanks Matteo, I fixed this by mod rewriting a path towards a different server, which worked :)
  • Mohsen Afshin
    Mohsen Afshin almost 12 years
    Worked Flawlessly, this solution is the best in comparison to the YQL and JSONP... Since your server is under your control you easily can add Access-Control-Allow-Origin to your server. Thanks Matteo
  • IdeoREX
    IdeoREX almost 11 years
    @MatteoMosca I'm not sure if this post is dead, but I'd really appreciate more explanation on your answer. How do I make my server do a HTTP POST to a remote server?
  • Matteo Mosca
    Matteo Mosca almost 11 years
    That depends on what server side technology you're using. In .Net C#, for instance, you can use the WebRequest or the WebClient classes. You can find plenty of documentation about this, just google for it.
  • Straw Hat
    Straw Hat about 10 years
    what if that jquery request is sent from some app like android app with webview executing that jquery. you add .htaccess at client(sender) or at server side(receiver)?
  • pim
    pim almost 8 years
    You would add the .htaccess server-side