1

I'm working with this webservice it return an XML document.

When i call this webservice with Ajax i get:

XMLHttpRequest cannot load http://services.gisgraphy.com/geoloc/search?lat=36.81881&lng=10.16596&from=1&to=1. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.1.4:50000' is therefore not allowed access. 

When do the same thing with PHP:

<?php
    $xml = simplexml_load_file('http://services.gisgraphy.com/geoloc/search?lat=50.209298&lng=10.245&from=1&to=1');
    print_r($xml);
?>

Print it without getting restricted.

I just wonder the difference between those cases, and why it work for php file only ?

Cheers.

Community
  • 1
  • 1
Marwen Trabelsi
  • 4,167
  • 8
  • 39
  • 80

2 Answers2

2
  • When you run PHP code, you do it on your own server. Nothing should restrict you from accessing other website because it's your server.

  • When you run Javascript Code, you usually run it on a client web browser. You don't own the client machine. And the client machine want to protect itself from connecting to malicious website.

Imagine there's no same-origin policy :

$.ajax({
  url: "http://somedrugdealingwebsite.com"
})

Client's IP will be registered as visitor of drug dealing website.

Perfect28
  • 11,089
  • 3
  • 25
  • 45
  • 3
    This is actually not accurate and can be easily disproven if you run a web debugger. Your request goes through just fine - the browser blocks the response, not the request. In fact, the browser has no idea whether or not the server implements CORS until the server responds. – Mike Bell Jul 25 '14 at 17:03
1

In short, because the same-origin policy is enforced by the browser, not the server. If you have Fiddler or somesuch running when you make the Ajax request, you'll see that the response actually comes back fine. It's the browser that rejects it.

In the case of your PHP request, you are requesting from the server, not from the script (browser). To be clear, PHP always runs from the server, not the client (this seems to be a somewhat common misconception).

Mike Bell
  • 1,356
  • 11
  • 9