My jQuery is failing to work the json it received from the back

Asked

Viewed 156 times

0

Guys, I’m since yesterday trying to solve this kkk. Well I’m making an ajax request for my back-end. So far so good, the data arrives and execute right, do what I want. I return an array converted into Json. When I get into my jQuery, I can’t use it as an object. It always gives the same error "Uncaught Syntaxerror: Unexpected end of JSON input" or simply gets empty. Please help me...

This is the Ajax.

$('.inicia-chat').click(function(){
$('#destinatario').val('24');
$.ajax({
    url: 'php/carrega-chat.php',
    type: 'POST',
    data:{
      'destinatario' : 24
    }
  }).done(function(dados_array){
    var parse = JSON.parse(dados_array);
    console.log(parse);
  });
});

This is the PHP

$conn = new mysqli('localhost', 'root', '', 'kashikoi');
   if ($conn->connect_error) {
       $erro = '<script>alert('.$conn->connect_error.')</script>';
   }

$consulta_mensagem = "select * from mensagem where id_destinatario = ".$destinatario."";
$consulta_m = $conn->query($consulta_mensagem);

$rows = $consulta_m->num_rows;

$array = array();

if($rows <= 0){
    echo 1;
}else{
    while($linha = $consulta_m->fetch_array(MYSQLI_ASSOC)){
        $wow = array($linha['id_destinatario'], $linha['id_remetente'], $linha['mensagem']);
        array_push($array, $wow);
    }

    echo json_encode($array);
}

  • 1

    You really need JSON.parse?

  • As Sergio said, apparently dados_array already enough being an object, no longer a JSON string, so you don’t have to parse it.

  • Add a dataType : "json". On the object that goes as a $.ajax parameter()

  • Guys, I tried both suggestions and it still didn’t work out :/ Thank you very much

  • The worst is that if I shoot that while and step a simple object it works, the problem is when it has an object inside the same.

No answers

Browser other questions tagged

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