Why does Ajax give me a cross-origin error when I can make a request with PHP?

I can make a GET request with PHP and get the correct answer. This is the function I use:

Php

function httpGet($url)
{
    $ch = curl_init();

    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_HEADER, false);

    $output=curl_exec($ch);
    curl_close($ch);
    return $output;
}

A simple example:

$fakevalue='iamfake';
$url="http://fakeurl.com?fakeparameter=".$fakevalue;
$jsondata= httpGet($url);
$fake_array = json_decode($jsondata, true);
$weed_var=$fake_array['weeds']; // successfully obtained weed.

This function returns a response from the server.

Now I am trying to execute the same HTTP GET request in AJAX, but I cannot get a response.

Initially, I thought the problem was with the JavaScript function being used. Google provided me with many JavaScript functions to execute an HTTP GET request, but they all had the same problem. The request returns an error instead of the data that I received when I used PHP.

JAVASCRIPT

var fakevalue = "iamfake";

var fake_data = {
    fakeparameter: fakevalue
};

$.ajax({
    url: "http://fakeurl.com",
    data: fake_data,
    type: "GET",
    crossDomain: true,
    dataType: "json",
    success: function(a) {
        $("#getcentre").html(a);
    },
    error: function() {
        alert("Failed!");
    }
});

JavaScript error

XMLHttpRequest cannot load http://fakeurl.com?fakeparameter=fakevalue. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.`

I know that you will tell me to use CORS, but if it was due to the lack of the Access-Control-Allow-Origin header, then how did I get the answer to the same service in PHP?

+4
3

PHP ( - , ( , )) ( cookie, IP-, ).

Ajax , , JavaScript ( , ).

, . : Alice eBanking .

, , , ( CORS), JavaScript .

CORS, , (JSONP) ( ), , URL- ( - , YQL) ( , , , , ).

+15

: PHP CORS. , URL- .

+1

CORS, XMLHttpRequest , . , . - , - . : http://www.html5rocks.com/en/tutorials/cors/

GET-, JSONP datatype="jsonp". : http://www.sitepoint.com/jsonp-examples/

0

All Articles