ERROR Uncaught Syntaxerror: Unexpected token < in JSON at position 0

Asked

Viewed 3,164 times

1

I have the following JS script:

   jQuery(document).ready(function($) {
    $("#idSelect").change(function(event) {
  var valor = $(this).val();
    //alert(valor);
      $.post( "ajaxSerie.php", { valorInput: valor }, function( data ) {
        var retorno = JSON.parse(data);
        console.log(retorno);
        $("#pertence").val(retorno['pertence'])// aqui estou atribuindo um input qualquer o valor retornado do php, o input tera o valor de sala206
        $.each(retorno, function() {
          $('<option>').val(retorno['pertence']).text(retorno['pertence']).appendTo('#teste');
        });
    }); 
}); 

});

in AJAX is like this:

  $idValor = $_POST['valorInput']; 
  $result = [
  "pertence" => $idValor
  ];
  echo json_encode($result);

when I do site it works perfectly, now when I step to the site on the server of your error: Uncaught Syntaxerror: Unexpected token < in JSON at position 0, how to solve this?

  • Ever tried to give a console.log(data) before the JSON.parse() to see if the return of AJAX is a valid JSON?

  • I just did, it returned a gigantic HTML code, how can I solve this?

  • It’s probably a server error screen explaining what went wrong. You will need to read this screen and update the question with the new information

1 answer

1

Actually it is not php error this, but rather CORS which in general means that you are making a call from one server to another, without owning the other (being in the same domain).

If you have access to the other server (the one you are calling), add this directive to . htaccess

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.