Error returning data from PHP to Javascript: "Unexpected token in JSON at position 0"

0

I am making a form and I am using fetch to send and receive data with PHP:

  

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 at fetch.then.res ( app.js:15 )

Here is my% code of%:

File app.js (where I send the string I want to capture in inserta.php ):

The following is the function I am calling to get the string:

    
asked by Marco Pascual 27.06.2018 в 07:44
source

1 answer

0

The error you are suffering is due to the fact that when you do not check the check box whose name="chk" the value $_POST['chk'] is not defined, so it will send you an index warning not defined in the following line:

if ($_POST["chk"] == "")
{
  $chk = 0;
}
else
{
  $chk = 1;
}

I recommend changing it for:

if (empty($_POST["chk"])) {
  $chk = 0;
} else {
  $chk = 1;
}

That way you will not mix HTML code of the error with the JSON that must be delivered.

Also, as a protection system against mixing warning or error messages during the development phase , I recommend you do the following:

  • Make use of ob_start() at the beginning of the PHP script to store this type of messages in a temporary warehouse and not sent to the client until we decide.
  • Use ob_end_clean() just before the echo json_encode() to discard the temporary store exit and send the customer only the echo .

Example:

<?php
/* Comenzamos a guardar todo en un almacén temporal */
ob_start();
/* Hacemos nuestro trabajo */
/* ... */
/* Descartamos los mensajes de advertencia previos */
ob_end_clean();
/* Configuramos las cabeceras para los datos enviados */
header('Content-type: application/json; charset=utf-8');
/* Enviamos el JSON al cliente */
echo json_encode($ofi);

In production you should not have any kind of warning, you should debug any case that could occur or instead of using ob_end_clean() use a ob_get_clean() and save the messages obtained to a log file using file_put_contents(..., FILE_APPEND) or error_log() .

<?php
/* Comenzamos a guardar todo en un almacén temporal */
ob_start();
/* Hacemos nuestro trabajo */
/* ... */
/* Enviamos al log los mensajes de advertencia */
error_log(ob_get_clean());
/* Configuramos las cabeceras para los datos enviados */
header('Content-type: application/json; charset=utf-8');
/* Enviamos el JSON al cliente */
echo json_encode($ofi);

PD: Using "$ofi" instead of $ofi is redundant (although equivalent). Do not wrap the variables in quotes if you only want to use their content.

    
answered by 27.06.2018 / 09:14
source