How to resolve Syntaxerror error: Unexpected token E in JSON at position 1

Asked

Viewed 9,093 times

-2

I’m trying to make a simple registration but I’m getting an error message:

Syntaxerror: Unexpected token E in JSON at position 1

I could not solve, the script is thus configured:

    $(document).ready(function () {
        $('#formulario').submit(function() {
            var dados = $('#formulario').serialize();           
            console.log(dados);
            $.ajax({
                type : 'POST',
                url  : 'insertKit.php',
                data : dados,
                dataType: 'json',
                success: function(response) {
                    if (response.codigo == "1") {
                         $("#mensagem").html('AVISO!' + response.mensagem  + '');                       
                        window.setTimeout(function() {
                            $(".alert-success").fadeTo(500, 0).slideUp(500, function() {
                                $(this).remove();
                                window.location.href = "TabelaKits.php?id_produto=";
                            });
                        }, 3000);   
                    } else {
                         $("#mensagem").html('AVISO!' + response.mensagem  + '');
                    }
                },
                error: function(xhr, ajaxOptions, thrownError) {
                    console.log(xhr, ajaxOptions, thrownError);
                    $("#mensagem").html('AVISO! Ocorreu um erro ao gravar o kit, entre em contato com o suporte técnico do site.');
                }
            });
            return false;
        });
    }); 

The insertion script in the database looks like this:

inserir a descrição da imagem aqui

When submitting my form is launched in my console the variables and their values:

Product%5B%5D=2&Number%5B%5D=10022&Quantity%5B%5D=600&Code%5B%5D=77&Description%5B%5D=44545

And then the error message:

{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}abort: ƒ (a)always: ƒ ()complete: ƒ ()done: ƒ ()error: ƒ ()fail: ƒ ()getAllResponseHeaders: ƒ ()getResponseHeader: ƒ (a)overrideMimeType: ƒ (a)pipe: ƒ ()progress: ƒ ()promise: ƒ (a)readyState: 4responseText: "↵ERRO ao inserir registro no Banco"setRequestHeader: ƒ (a,b)state: ƒ ()status: 200statusCode: ƒ (a)statusText: "OK"success: ƒ ()then: ƒ ()__proto__: Object "parsererror" SyntaxError: Unexpected token E in JSON at position 1
    at JSON.parse ()
    at m.parseJSON (jquery.js:8520)
    at Pb (jquery.js:8846)
    at x (jquery.js:9264)
    at XMLHttpRequest.b (jquery.js:9718)

I read something about form field names being the same, but my form looks like this:

<form id="formulario" action="" method="post" >   
   <div id="mensagem" class=""></div>   
	<div class="table-responsive">
	   <table id="products-table" class="table table-hover table-bordered">
		  <tbody>
			 <tr>
			   <th width="15%">Produto</th>
				<th width="15%">Nº</th>
				<th width="16%">Qtde.</th>
				<th width="15%">Código</th>
				<th width="32%">Descrição</th>
				<th width="22%" class="actions">Ações</th>
			 </tr>
			 <tr>
				<td><input type="text" name="produto[]" value="<?php echo $produto; ?>" readonly ></td>                        
				<td><input type="text" name="numero[]" ></td>
				<td><input type="text" name="quantidade[]"></td>
				<td><input type="text" name="codigo[]"></td>
				<td><input type="text" name="descricao[]"></td>
				<td class="actions">
				   <button class="btn btn-large btn-danger btn-xs" onclick="RemoveTableRow(this)" type="button">Remover</button>
			   </td>
			 </tr>
		  </tbody>
		  <tfoot>
			 <tr>
				<td colspan="6" style="text-align: left;">
				   <button class="btn btn-large btn-success" onclick="AddTableRow(this)" type="button">Adicionar Linha</button>
				   <button class="btn btn-large btn-primary" type="submit">Gravar</button>
				   <?php if ($totalRows_rcKits > 0) { ?>
				   <a href="AlteraKits.php?produto=<?php echo $produto; ?>"  class="btn btn-warning"> Tabela</a>                           
				   <?php } ?>
				   <p align="center"><a href="CadProdutos.php" class="btn btn-primary">Voltar</a></p>
				</td>
			 </tr>
		  </tfoot>
	   </table>
	</div>
 </form>

Locally that insert works perfectly.

One more detail I missed is that it is always falling in the exception message:

$("#message"). html('WARNING! An error occurred while saving the kit, please contact the website technical support.');

As requested follow the image of the Network tab:

inserir a descrição da imagem aqui

  • Why is PHP code as an image? What is the value of dados sent by the request?

  • Hi @Andersoncarloswoss, I couldn’t put the code because it was all messed up. The data value is this: product%5B%5D=2&number%5B%5D=10022&quantity%5B%5D=600&code%5B%5D=77&Description%5B%5D=44545

  • Was the request made by the browser (check through the developer tools, Network tab)? If yes, what was the HTTP response obtained, especially the body of the response?

1 answer

2


According to the console error message, there is a syntax error in json. When trying to convert the string, there is an unexpected token E. This is because your code is "dying" on query of INSERT. The return that Ajax receives is:

ERRO ao inserir registro no Banco

Or a simple php alert warning before displaying json. This would be enough to give syntax error.

In the insert the error is in the query string. You are trying to insert what is probably a quote-free string for example. This generates an error. Also, with arrays, I think you better work by concatenating the string thus:

$query = "INSERT INTO kits VALUES(".$Produto[$i].",'".$Descricao[$i]."')";
//                                                 ^   aspas simples  ^ - sem isso pode gerar erro

There may be other mistakes...

  • 1

    Hello @Andreicoelho, thanks for the tip.

  • @adventistapr quiet! Still can to improve more code in php, but I would need it written.

  • @adventistapr something else ... that or die() in your case, has to be removed from the code before going into production.

  • 1

    Yeah, I was testing locally, but thanks for the tip.

Browser other questions tagged

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