Ajax PHP - ParserError "Unexpected token in JSON at position 0"

3

I'm trying to make a GET request with ajax and PHP, but I always get the following error:

text status=:parsererror, error thrown:=SyntaxError: Unexpected token < in JSON at position 0

My ajax request is as follows:

    $.ajax({
        url: 'private/ajax/get_personas.php',
        type:'GET',
        contentType: 'application/json; charset=utf-8',
        dataType:'JSON',
        success: function(data, textStatus, jqXHR) {
            alert(data);
        },
        error: function(data, textStatus, errorThrown) {
            console.log('message=:' + data + ', text status=:' + textStatus + ', error thrown:=' +  errorThrown); 
        }
    });

The file get_personas.php contains only the following lines of code:

include('private/connection.php');  
echo json_encode("hello");

And the connection.php file

$host = "localhost";
$user = "root";
$pass = "12345";
$db = "pruebas";
$port = 3306;

$connection = mysqli_connect($host, $user, $pass, $db, $port);

The strange thing is that if I include (I copy all the code) the lines of code in the connection.php file in the file get_personas.php everything works correctly. I have tried to solve the problem but I have not achieved it, I hope someone can help me. I do not want to have to add all the connection code in each ajax request that you make.

    
asked by alexander zevallos 29.09.2016 в 04:59
source

1 answer

3

This error is triggered by jQuery, and it happens because you are receiving an HTML instead of a JSON. That is why the < is mentioned within the description of the error.

  

Unexpected token < in JSON at position 0


First, I recommend 2 basic points to review:

  • Are there spaces before starting a script, or any line that might be printing text that is not a JSON?
    It is important that there is not even a blank line before opening the <?php tag, and that the only line printed is

    echo json_encode($texto);
    
  • Are you by chance using the <? tag instead of <?php to start the code, and are disabled in the ini? (although it is not even recommended to use them).


  • If this is not obvious, a possible way to debug it is by evaluating the HTML sent by the server. For that, you can delete the configuration that requires a response like JSON:

    $.ajax({
        url: 'private/ajax/get_personas.php',
        type: 'GET',
        success: function(data, textStatus, jqXHR) {
            console.log(textStatus, jqXHR, data);
        },
        error: function(data, textStatus, errorThrown) {
            console.log('message=:' + data + ', text status=:' + textStatus + ', error thrown:=' + errorThrown);
        }
    });
    

    Once obtained, it could be easier to distinguish why the answer is HTML.

        
    answered by 29.09.2016 / 06:47
    source