Error returning a query’s value with php and ajax (Request failed: parsererror)

Asked

Viewed 582 times

0

I am trying to return the result of a query via ajax with php and jquery, but it is not working, I get a parser error message and am unable to identify the problem.

FUNCAO JS

function buscaCliente() {
    var cnpj = $('#cnpjCliente').val();
        $.ajax({
        url: "buscaCliente.php",
        method: "POST",
        data: {'cnpj':cnpj},
        dataType: "JSON"

    }).done(function(response) {
        console.log(JSON.parse(response));

    }).fail(function(jqXHR, textStatus ) {
        console.log("Request failed: " + textStatus);

    }).always(function() {
        console.log("completou");
    });
  }

PHP SEARCH CLIENT.

<?php 

require_once 'pdo.php';

$cnpjCliente = filter_input(INPUT_POST,'cnpj');

$sql = "SELECT nome
        FROM php.clientes 
        WHERE cnpj = ?";

$stmt = $pdo->prepare($sql);
$stmt->execute([$cnpjCliente]);

$nome = $stmt->fetch();

echo json_encode($nome);

?>

ERROR MESSAGE

Request failed: parsererror

  • If possible display the error that is returning

1 answer

1


Convert JSON with $.parseJSON(response) and remove the dataType: "JSON" of $.ajax. being like this:

function buscaCliente() {
  var cnpj = $('#cnpjCliente').val();
  $.ajax({
    url: "buscaCliente.php",
    method: "POST",
    data: {'cnpj':cnpj}
  }).done(function(response) {
    console.log($.parseJSON(response));

  }).fail(function(jqXHR, textStatus ) {
    console.log("Request failed: " + textStatus);

  }).always(function() {
    console.log("completou");
  });
}

Browser other questions tagged

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