Problem "CORS" using AJAX and PHP

3

I have this code from JQUERY:

$(document).ready(function() {
listarDetalle();

});
function listarDetalle(){
     var accion="listar";
       var URLprotocol = window.location.protocol;
    $.ajax({
     
            type: "POST",
            url: URLprotocol+"//gestionweb/includes/php/procesoDetalle.php",
            data: { "accion":accion}, 
            dataType:'json',
        
            error: function(){
                alert("error petición ajax");
               
            },
            
            success: function(data){
                console.log(data);
             
                                   
               for (var i = 0; i < data.length; i++) {
        
                var newRow =
                    "<tr>" +
                    "<td>" + data[i].idp + "</td>" +
                    "<td>" + data[i].nombre + "</td>" 
                    "<td>" + data[i].marca + "</td>" +
                    "<td>" + data[i].cantidad + "</td>" +
                    "<td><input type='radio' id='"+data[i].idproducto+"' name='seleccion'/></td>"+
                    "</tr>";
                $(newRow).appendTo("#ticket tbody");                 
       
    
               
            
        
  

        } }
        
}).fail( function( jqXHR, textStatus, errorThrown ) {

  if (jqXHR.status === 0) {

    alert('Not connect: Verify Network.');

  } else if (jqXHR.status == 404) {

    alert('Requested page not found [404]');
  

  } else if (jqXHR.status == 500) {

    alert('Internal Server Error [500].');

  } else if (textStatus === 'parsererror') {

    alert('Requested JSON parse failed.');

  } else if (textStatus === 'timeout') {

    alert('Time out error.');

  } else if (textStatus === 'abort') {

    alert('Ajax request aborted.');

  } else {

    alert('Uncaught Error: ' + jqXHR.responseText);

  }

});;

};

And I get this error:

Blocked Crossed Origin Request: The Same Source Policy does not allow you to read the remote resource in link . (Reason: the CORS request was rejected).

Try with:

dataType:'jsonp',

What I found on a website, but if I do that, it tells me that the script failed to load. I really do not know what to do. I attach google chrome images of the headings ... the address appears well let's say:

link

as you will see error 302 in processDetail.php as the resource was moved but I do not understand.

I'm calling from another script and everything is fine

    
asked by Caruso 16.08.2018 в 13:16
source

1 answer

2

To start I have to tell you that this line is unnecessary:

 url: window.location.protocol + "//gestionweb/includes/php/procesoDetalle.php"

If you want to keep the scheme ( http: or https: ) just do not indicate it:

 url: "//gestionweb/includes/php/procesoDetalle.php"

On the other hand, the rules of CORS (or also known as exchange of resources of crossed origin ) prevent you from accessing the resources of an external page if it does not authorize your site web to do it.

By default, all queries within the same origin (same URL or Same Origin Policy ) are assumed to be secure and do not use CORS for validation, only queries to origins (or URLs) external.

To do this, the browser performs a preflight request using HTTP method OPTIONS .

It is precisely this prior consultation that has failed you and, therefore, it is assumed that access to this external API is prohibited.

One way to implement the response to that previous query could be by adding the following code to the beginning of your PHP script:

<?php
/* Permitimos a cualquier origen acceder a este API de manera remota */
header('Access-Control-Allow-Origin: *');
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  /* No debe ejecutarse el resto del script mediante la consulta OPTIONS previa */
  die();
}

EYE : This code allows access to your API from any URL .

If you want to restrict access to the API to a small number of URLs then you should do something like the following:

<?php
/* Listado de URLs (orígenes) que tienen acceso al API (sin / al final) */
$autorizados = [
  'http://www.origen1.com',
  'https://www.origen2.es',
];
/* Comprobamos que el origen esté en el listado de orígenes permitidos */
if (
  isset($_SERVER['HTTP_ORIGIN'])
  && in_array($_SERVER['HTTP_ORIGIN'], $autorizados) === true
) {
  /* Sólo autorizamos el origen validado */
  header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
}
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  /* No debe ejecutarse el resto del script mediante la consulta OPTIONS previa */
  die();
}
    
answered by 16.08.2018 / 13:51
source