0

I have a problem with an AJAX request to other website. When I call Http to Http there is no problem. But When I call from HTTP to HTTPS then I have error message as below:

Access to XMLHttpRequest at 'https://www.mywebsideserver.pl/test.php' from origin 'http://mywebsideclient.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. klientcors.php:77 jquery.min.js:2 POST https://www.mywebsideserver.pl/test.php net::ERR_FAILED

These are the client-side headers.

enter image description here

And this is my client-side code:

<script type="text/javascript">

testCORS();
    function testCORS() {
        $.ajax({
          url: 'https://www.mywebsideserver.pl/test.php',
          type: 'POST',
          //dataType: 'html',
          data:{},
         
          crossDomain: true,
          success: function (data, textStatus, xhr) {
            alert(data);
          },
          error: function (xhr, textStatus, errorThrown) {
            console.log(errorThrown);
          }
        });
    }   
</script>

And Server-side easy code:

<?php
header('Access-Control-Allow-Origin: *');
$myArr = array("xx1", "xx2", "xx3", "xx4");

$myJSON = json_encode($myArr);


echo $myJSON;
?>

Something needs to be added to htaccess , client-side code or server-side code ?

ArashShiri
  • 55
  • 7
Niffe33
  • 43
  • 5
  • Does this answer your question? [JavaScript cross-domain call: call from HTTP to HTTPS](https://stackoverflow.com/questions/8414786/javascript-cross-domain-call-call-from-http-to-https) – Umair Khan Aug 12 '20 at 11:14

2 Answers2

0

One way to work this out is to decide what protocol to use (depending on the current protocol) before making the Ajax request. For example, if an user will access https://www.mywebsideserver.pl then your ajax url should be

https://www.mywebsideserver.pl/test.php

If the user acces http://www.mywebsideserver.pl then the ajax url should be

http://www.mywebsideserver.pl/test.php

You can change your code like this:

$is_https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443;

$protocol = $is_https ? 'https' : 'http';

Now you can use the $protocol variable to build your url like this:

<script type="text/javascript">

testCORS();
    function testCORS() {
        $.ajax({
          url: '<?php echo $protocol ?>://www.mywebsideserver.pl/test.php',
-1

Yeah, that is the reason for using CORS, an API request to a secured website can only be done by another secured website. Hence an HTTP using the website cannot send a request to an HTTPS website. You can read more about it here. The HTTPS website can make an exception to this, by adding a "Access-Control-Allow-Origin" header to their website saying that
"Hey, this HTTP website can access my HTTPS website since I am his friend, I will make this exception". Read more about it here

keidakida
  • 713
  • 4
  • 12