-1

Hi I'm trying to make an html file (no PHP allowed) that will send an ajax request to a server and then alert the response :

$(document).ready(function(){
$("#connect").click(function(){
$.ajax({
url: "http://213.74.86.200:8080/pwr/relays?ac=123456",
type: "GET",
crossDomain: true,
contentType: 'text/plain',
xhrFields: {
withCredentials: false
},
headers: {
    'Access-Control-Allow-Origin': '*'
},
success:function(data,status){
    if(status=="success"){
    alert(data);
    }else{
        alert("Connection Error");
    }
}   
});
});

});

The thing is that when I open the link with my browser

http://213.74.86.200:8080/pwr/relays?ac=123456

everything works just fine and I can see the response as a text but when I open my html file and click the connect button I get this in the console log :

OPTIONS http://213.74.86.200:8080/pwr/relays?ac=123456

XMLHttpRequest cannot load http://213.74.86.200:8080/pwr/relays?ac=123456.
Response to preflight request doesn't pass access control check: 
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'null' is therefore not allowed access. The response had
HTTP status code 405.

Any help please ?

1 Answers1

0

As the error says, you need to set Access-Control-Allow-Origin on your relays page.

L Ja
  • 1,384
  • 1
  • 11
  • 22
  • then why I don't need it when I open the link from my browser ? i thought that ajax are identical to normal browser requests! – Fareed Nema Nov 26 '15 at 15:31
  • 1
    @FareedNema — Because, as the duplicate question says, when you open it directly, that is just between you and site A. It isn't between you, site A, and some untrusted third party JavaScript on site B. – Quentin Nov 26 '15 at 15:33