AJAX with PHP Finder that consults BBDD

0

I'm doing a kind of search engine, in which while you press a key, an AJAX request is made to consult it in the DB. The point is that I still do not know much about AJAX and it does not work for me. At the moment I am testing with any text instead of consulting the database.

HTML:

<input placeholder="Buscar..." id="buscador" type="text">
<p class="resultados"></p>

JAVASCRIPT:

$('#buscador').on('keypress', () => {
    let busqueda = $('#buscador').val();  

    // Ajax para recibir los 'posts'
    $.ajax({

        type: 'POST',
data: busqueda,

        url: 'ajax/indexAjax.php',
        success: function(respuesta) {
          $('.resultados').html(respuesta);
       }
    });

    });

PHP:

<?php
    $busqueda = $_POST['busqueda'];
    $data = "";
    if(isset($busqueda)){
        $data = $busqueda;
    }else{
        $data = "No existe";
    }

    return $data;
?>
    
asked by Csc99 28.09.2018 в 19:32
source

1 answer

1

The problem that I am seeing in your ajax is that in the attribute data you are not assigning an index to pass it to php , you should to look like this:

$('#buscador').on('keypress', () => {
    let busqueda = $('#buscador').val();  

    // Ajax para recibir los 'posts'
    $.ajax({

        type: 'POST',
        data: {busqueda:busqueda},
        url: 'ajax/indexAjax.php',
        error: function (request, status, error) {
          alert(request.responseText);
        },
        success: function(respuesta) {
          $('.resultados').html(respuesta);
       }
    });

  });

I also add an error handler to guide you if you get an error like a 404.

With respect to PHP you should change the return to a echo because the JS can not capture a return from the php but if a echo , it should look like this:

<?php
    $busqueda = $_POST['busqueda'];
    $data = "";
    if(isset($busqueda)){
        $data = $busqueda;
    }else{
        $data = "No existe";
    }

    echo $data;
?>

I hope it serves you.

    
answered by 28.09.2018 / 19:36
source