PHP Solution to http to https ajax call: No ‘Access-Control-Allow-Origin’ header is present on the requested resource

PHP Solution to http to https ajax call: No ‘Access-Control-Allow-Origin’ header is present on the requested resource

When submitting a form from an http:// site to an https:// via ajax,   you will run into the following error in the Chrome console

XMLHttpRequest cannot load https://www.example.com. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.example.com' is therefore not allowed access

This problem can come about if your current url is http://www.example.com/  and you are using an ajax POST or GET request to the https://www.example.com site.

For example on http://example.com/login.php you might have some JQuery such as

$('div#login').load('https://example.com/loginform.php')

Or

$.post({url:'https://example.com/loginform.php'
     ,data: 'username=bob&password=pass123'
     ,success: function(data){ $('div#login').html('You are logged in') }
})

To correct this, add the following PHP to the top of the loginform.php page.  Note the HTTP_HOST variable which should make it so that if you are simply trying to access the https:// site using the exact same domain name you will not have to change the code

 

<?php
    header("Access-Control-Allow-Origin: http://$_SERVER[HTTP_HOST]"); 
?>

 

Leave a Reply

Your email address will not be published. Required fields are marked *