data return with Jquery (AJAX) and PHP

Asked

Viewed 35 times

-3

I’m trying to learn AJAX and I’m beating head here

I want to return the data via AJAX and display, but my code is not returning anything

const caixabusca = $("#caixabusca");
const form = $("#formulario");
const botaoenvio = $("#botaoenviar");

var caixatext = caixabusca.val();

//pegar botao e cancelar evento, apos isso realizar fazer ajax
botaoenvio.click((e)=> {
  e.preventDefault();
  $.ajax({
    type: 'POST',
    url: 'j.php',
    data: {comentario: caixabusca.val()},
    dataType: 'json',
    success: function(data) {
      console.log(data);
   }
 });

});

PHP file

<?php
  header('Content-Type: application/json; charset=utf-8')
  $comentario = $_POST['comentario'];
  include ("conectar.php");
  $sql = "select * from comentarios WHERE comentario LIKE '%". $comentario ."%'";
  $resultado = $conexao -> query($sql);
  if($resultado -> num_rows > 0){
    echo json_encode('sucesso');
    while($linha = $resultado-> fetch_assoc()){
      //echo json_encode($linha['comentario']);
      //Tentei exibir a consulta no banco de dados mas nao consegui
    }
  }else{
    echo json_encode('Nao achamos');
  }
 ?>
  • error: Function(err) in your ajax and see the code for err... should be 500, if it is, it is a problem in php

  • @Willknippelberg I received "Requested JSON parse failed.". It may be that the error ta being in JS then?

  • Try to do so in returns: json_encode ( ['message': 'success']);

1 answer

0

 <?php
 
 $comentario = $_POST['comentario'];
 include ("conectar.php");
 $sql = "select * from comentarios WHERE comentario LIKE '%". $comentario ."%'";
 $resultado = $conexao -> query($sql);
 if($resultado->num_rows > 0){ //removi o excesso de espaço
   echo json_encode(['success'=>false, 'message'=> 'sucesso']);
   while($linha = $resultado-> fetch_assoc()){
     echo json_encode(['success' => true, 'content' => $linha['comentario']]);
   }
 }else{
    echo json_encode(['success' => false, 'message'=> 'Não encontrado']);
 }
?>

Browser other questions tagged

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