Thịnh Kều
Thịnh Kều

Reputation: 163

Can't not get JSON file cross domain

I generate a list of objects in a json file using PHP and then i used jQuery to get data from it

    $.ajax({
        url: url,
        method: "get",
        dataType: "json"
        }).done(function (data) {
                for(var i=0; i < data.length; i++){
                document.getElementById("id01").innerHTML = data[i].Kategorianimi;

    }
    }).fail(function () {
        document.getElementById("id01").innerHTML = "cant get json";
    })

});

It worked ok in localhost but when i give a external host link to the url, it not work. Is there anyone has same issue with me and could you guy show me how to fix it? thanks.

When i add a header like this, then my JSON data was error

<?php
require_once "../pdo/kategoriaPDO.php";
header('Access-Control-Allow-Origin: *’);

/**
 * Created by PhpStorm.
 * User: dinhthinh
 * Date: 27/11/16
 * Time: 14:07
 */
$katepdo = new KatePDO();
$json = str_replace("\u0000","",json_encode($katepdo->listaKaikkiKategoriat(), true));
echo stripcslashes($json);

Upvotes: 0

Views: 855

Answers (2)

Shubham Khatri
Shubham Khatri

Reputation: 281854

The error You might be getting is that

No Access-Control-Allow-Origin header is present on the requeswted resource. localhost:8080 is thus not allowed Access.

This happens because browsers send a preflight OPTIONS requested to the server to see if it has access before sending the actual request

For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts. For example, XMLHttpRequest and Fetch follow the same-origin policy. So, a web application using XMLHttpRequest or Fetch could only make HTTP requests to its own domain. To improve web applications, developers asked browser vendors to allow cross-domain requests.

You server must then allow this by specifying the Access-Control-Allow-Orgin for localhost

Or for testing purpose you can use the CORS plugin for Chrome extension and test you code. But anyways later you need to enable CORS from the server.

Read more about cors here

Upvotes: 2

ixpl0
ixpl0

Reputation: 756

You must add your host to server's Access-Control-Allow-Origin header, or just send Access-Control-Allow-Origin: * header from server

Upvotes: 2

Related Questions