No Access-Control-Allow-Origin header is present on the requested resource. Origin 'null' is therefore not allowed access. - Phonegap [duplicate]

3

I have read about this method json and I just do not understand and do not know what to fix, I'm using another domain to get json.

Here is my code:

$(function(){
    var url = "http://website.com/json.php";
    $.getJSON(url, function(result) {
        console.log(result);
        $.each(result, function(i, field) {
            var id = field.id;
            var title = field.title;
            $(".class").append("<a href='page.html?id=" + id + "&title=" + title +");
        });
    });
});

Error:

  

XMLHttpRequest can not load link . In 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

How can I pass this to another code, like this:

 $.ajax({
        url: url,
        crossDomain: true,
        data: form,
        dataType: 'json',
        success: function(data) {
            console.log(data);
        },
        type: 'POST'
    });

Json.php:

<?php
    header("Access-Control-Allow-Origin: *");
    include "db.php";
    $data=array();
    $q=mysqli_query($con,"select * from 'course_details'");
    while ($row=mysqli_fetch_object($q)){
        $data[]=$row;
    }
echo json_encode($data);
?>

Db.php

<?php
    header("Access-Control-Allow-Origin: *");
    $con = mysqli_connect("localhost","user","pass","db") or die ("could not connect database");
?>

I'm opening the index.html by the same chrome, not by localhost, and I'm making the call in another domain (website.com/json.php), and have this problem.

Some people put it as a duplicate, but it is not duplicated, I would like a solution that the other does not have, I need a clear answer.

    
asked by anonymous 11.09.2017 / 17:02

2 answers

1

If you do not have access to the server to add the headers:

You can use one of the extensions for chrome (for development) :

Allow-Control-Allow-Origin: *

CORS Toggle

These extensions disable chrome security with respect to communication from different hosts and without the authorization definition in the header (as done by the header () function).

Summarizing This error is corrected by adding: (PHP)

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
echo json_encode($data);

Or your API consuming front-end must be on the same host (IP + port) as your API.

    
11.09.2017 / 23:56
0

This indicates a problem communicating with your site's server. This occurs when you try to make a call to a server that is in a different domain than the source of your request. I do not know what technology you are using on your site, but you can enable this communication.

Search how to enable CORS in the technology you are using on the web site.

    
11.09.2017 / 17:14