-2

i'm trying to do a request to a php file. I catch the longitude and latitude from a function in Maps API, and use AJAX to save this points in a MySQL database.

AJAX

 function salvaPonto(latitude, longitude){
            $.ajax({
              type: "GET",
              data: {latitude: latitude,longitude: longitude},
              url: "http://localhost/dados/salvaPonto.php",
              datatype: 'JSONp',
              success: function(data) {
                alert("ok");
              },
              error: function(data){
                alert("erro");
              }
          });
        }

PHP File

<?php

    header("Access-Control-Allow-Origin", "*");
    error_reporting(0);
    $latitude = $_GET['latitude'];
    $longitude = $_GET['longitude'];

   $conn = mysql_connect('localhost', 'root', '') or die ('Erro de conexão com o banco de dados');
    mysql_select_db('app') or die ('Erro ao selecionar banco de dados');

    $myquery = "INSERT INTO pontos(latitude, longitude) VALUES ('".$latitude."', '".$longitude."');";

    $result = mysql_query($myquery) or die("Query error:".mysql_error());
    mysql_close($conn);

    echo 1;   


?>

Error:

XMLHttpRequest cannot load http://localhost/dados/salvaPonto.php?latitude=-22&longitude=-43. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

Lucas Torres
  • 222
  • 1
  • 2
  • 12
  • 2
    possible duplicate of [“No 'Access-Control-Allow-Origin' header is present on the requested resource”](http://stackoverflow.com/questions/20035101/no-access-control-allow-origin-header-is-present-on-the-requested-resource) – geocodezip Jul 31 '16 at 21:58
  • possibly related question: [XMLHttpRequest cannot load. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin is therefore not allowed access](http://stackoverflow.com/questions/25445027/xmlhttprequest-cannot-load-no-access-control-allow-origin-header-is-present-o) – geocodezip Jul 31 '16 at 22:00
  • See [Cross-Domain requests in Javascript](https://jvaneyck.wordpress.com/2014/01/07/cross-domain-requests-in-javascript/) – geocodezip Jul 31 '16 at 22:01

1 Answers1

2

Lucas you're misusing the header function, so your Access-Control-Allow-Origin is not set properly. header() accepts the header name and value as one string, not two. Change:

header("Access-Control-Allow-Origin", "*");

To:

header('Access-Control-Allow-Origin: *');

See docs

BeetleJuice
  • 39,516
  • 19
  • 105
  • 165