-1

I am using XMLHttpRequest to run a ajax with javascript.I am getting error

"Reason: CORS header 'Access-Control-Allow-Origin' missing".

I am hitting other domain url in Ajax.This is my code

if (mypostrequest.readyState==4){
                console.log(mypostrequest.status);
              if (mypostrequest.status==200 || window.location.href.indexOf('http')==-1){
               console.log('got it');
               console.log(mypostrequest.responseText);
               redirect_url = mypostrequest.responseText;
               //BTHit();
              }
              else{
               console.log('cant get data');
              }
}
var parameters='campaign_id='+campaign_id;
        mypostrequest.open('POST', 'http://mydserverip/get_campaign.php', true)
        mypostrequest.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        //mypostrequest.setRequestHeader('Access-Control-Allow-Origin', '*');
        mypostrequest.send(parameters);

and on my server I am simply printing data like

<?php male('myemail','test','testm');  echo "hello"; ?>

I am getting email but when I look on my console I got above error and nothing comes in response.

and output of console.log(mypostrequest.status); is 0 and console shows cant get data.

I have tried so many solutions of google but not able to solve my problem.

I have tried .htaccess as well no good luck.

Please help me guys.

user3110655
  • 121
  • 3
  • 20

1 Answers1

0

I had the same problem with my API. In your PHP application you need to add header to allow CORS. use the header function.

header('Access-Control-Allow-Origin: *')

The previous line allows your php app to be access from any domains. You can restrict your domains access by adding origin.

header('Access-Control-Allow-Origin: http://exemple.com/myapp http://foobar.com/api')

If you want only some method to access your server (ex GET OR POST only ) add those line also

header('Access-Control-Allow-Methods:' . $YourMethods)
Nicolas
  • 8,077
  • 4
  • 21
  • 51