How to send a cross domain ajax request

 

I want to send a cross domain ajax request but I am getting below error.

I need to allow others send ajax requests to my script . So external requests may come from other websites and domains.

Code which I have tried for request.

$(document).ready(function () {
    $.ajax({
        type: 'POST',
        url: "http://otherdomain.com/mypage.php",
        data: 'ss=' + 1,
        success: function (msg) {
            alert(msg);
        }
    });
});

 

Error on console log:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://otherdoamin/mypage.php. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)

If you control the server being POST ed, simply leverage the “Cross-Origin Resource Sharing standard” by setting response headers on the server.

In short here is how you accomplish the cross domain POST from from-myend.com/post.html to to-target.com/post.php (using PHP as an example).

Note: set Access-Control-Allow-Origin for NON OPTIONS .

 

SETUP:-TARGET DOMAIN::   

In the posted domain server or the target domain server setup the following:

switch ($_SERVER['HTTP_ORIGIN']) {
    case 'http://from.com': 
    case 'https://from.com':
         header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
         header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
         header('Access-Control-Max-Age: 1000');
         header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

    break;
}

This allows your script to make cross domain POST, GET and OPTIONS.

SETUP:-FROM REQUEST SENDING DOMAIN::  

Setup your cross domain POST from JS (jQuery example):

$.ajax({
    type: 'POST',
    url: 'https://to-target.com/post.php',
    crossDomain: true,
    data: '{"some":"json"}',
    dataType: 'json',
    success: function(responseData, textStatus, jqXHR) {
        var value = responseData.someKey;
    },
    error: function (responseData, textStatus, errorThrown) {
       alert('failed.');
    }
});

 

Note:

  1. For the security implications. Be careful before doing something like ‘Access-Control-Allow-Origin: *’
    header('Access-Control-Allow-Origin: *');