Thursday, 23 August 2018

HTTPS to HTTP Ajax Request, Same Origin Policy.

Often there are times where we need to make a request that might not obey the Same Origin Policy . So here I am going to address Different Protocal issue in Same Origin Policy. Suppose we are making a http request from a server with https protocal like following,

$.ajax({
        url: 'http://MyAjaxHTTP Path',
        type: 'POST',
        data: 'param1=value1&param2=value',
        header: "application/x-www-form-urlencoded",

The above request cannot be made because it violates same origin policy. So we have to write a layer code between Javascript and the HTTP server that directly interacts with HTTP. So first we have to choose a server side language for this. I am choosing PHP.

In PHP (phplayer.php):


$param1 = $_POST["param1"];
$param2 = $_POST["param2"];
$data = array(“param1”=>$param1, "$param2"=>$param2);

$data = http_build_query($data);
header('content-type: application/json');
$context_options =  array(
        'http' => array(
                'method' => 'POST',
                'header' => 'Content-type: application/x-www-form-urlencoded',
                'content' => $data
        ));
$context  = stream_context_create($context_options);

//notice that our actual HTTP URL is called here
$result = file_get_contents("http://MyAjaxHTTPPath", false, $context);
echo $result;

In Javascript everything remains same except that we have to make a call to our layer php code that will actually make a http request and get back the response.


$.ajax({
        url: 'phplayer.php',
        type: 'POST',
        data: "param1=value1&param2=value",
        header: "application/x-www-form-urlencoded",

No comments:

Post a Comment