Consultation with ajax is not done and it does not give me an error

0

I'm starting with ajax. I have an input that generates a search with ajax in my mysql database, but it does not return any results and the console does not show any error

$(document).ready(function() {
    $("#resultadoBusqueda").html('<p>JQUERY VACIO</p>');
});

function buscar() {
    var textoBusqueda = $("input#busqueda").val();
 
     if (textoBusqueda != "") {
        $.post("buscar.php", {valorBusqueda: textoBusqueda}, function(mensaje) {
            $("#resultadoBusqueda").html(mensaje);
         }); 
     } else { 
        $("#resultadoBusqueda").html('<p>JQUERY VACIO</p>');
        };
};
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<form accept-charset="utf-8" method="POST">
 <input type="text" name="busqueda" id="busqueda" value="" placeholder="" maxlength="30" autocomplete="off" onKeyUp="buscar();" />
</form>
<div id="resultadoBusqueda"></div>

And this is the code of the search.php file

<?php
require('../conexion.php');

$consultaBusqueda = $_POST['valorBusqueda'];

$caracteres_malos = array("<", ">", "\"", "'", "/", "<", ">", "'", "/");
$caracteres_buenos = array("& lt;", "& gt;", "& quot;", "& #x27;", "& #x2F;", "& #060;", "& #062;", "& #039;", "& #047;");
$consultaBusqueda = str_replace($caracteres_malos, $caracteres_buenos, $consultaBusqueda);

$mensaje = "";

if (isset($consultaBusqueda)) {

  $consulta = mysqli_query($conexion, "SELECT * FROM respuestos
  WHERE maquina COLLATE UTF8_SPANISH_CI LIKE '%$consultaBusqueda%' 
  OR repuesto COLLATE UTF8_SPANISH_CI LIKE '%$consultaBusqueda%'
  OR CONCAT(maquina,' ',repuesto) COLLATE UTF8_SPANISH_CI LIKE '%$consultaBusqueda%'
  ");

  $filas = mysqli_num_rows($consulta);

  if ($filas === 0) {
    $mensaje = "<p>No hay ninguna maquina y/o repuesto</p>";
  } else {
    echo 'Resultados para <strong>'.$consultaBusqueda.'</strong>';

    while($resultados = mysqli_fetch_array($consulta)) {
      $maquina = $resultados['maquina'];
      $repuesto = $resultados['repuesto'];
      $ref = $resultados['ref'];

      $mensaje .= '
      <p>
      <strong>maquina:</strong> ' . $maquina . '<br>
      <strong>repuesto:</strong> ' . $repuesto . '<br>
      <strong>Ref.:</strong> ' . $ref . '<br>
      </p>';

    };
  };
};
echo $mensaje;
?>

This is the SQL of my table with 1 record

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";

CREATE TABLE 'repuestos' (
  'id' int(11) NOT NULL,
  'ref' varchar(100) CHARACTER SET utf8 COLLATE utf8_spanish_ci NOT NULL,
  'tipo' varchar(100) CHARACTER SET utf8 COLLATE utf8_spanish_ci NOT NULL,
  'maquina' varchar(400) CHARACTER SET utf8 COLLATE utf8_spanish_ci NOT NULL,
  'repuesto' varchar(400) CHARACTER SET utf8 COLLATE utf8_spanish_ci NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;


INSERT INTO 'repuestos' ('id', 'ref', 'tipo', 'maquina', 'repuesto') VALUES
(1, 'BM-154D80', 'Sierra', 'Sierra BM-180', 'Cinta 1600 Hueso');

ALTER TABLE 'repuestos'
  ADD PRIMARY KEY ('id');

ALTER TABLE 'repuestos'
  MODIFY 'id' int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
COMMIT;

And here the connection file, this file has worked well with another table for a year so I do not think it's the problem

<?php
function dbConnect (){
 	$conn =	null;
 	$host = 'Localhost';
 	$db = 	'****';
 	$user = '*****';
 	$pwd = 	'*****';
	try {
	   	$conn = new PDO('mysql:host='.$host.';dbname='.$db, $user, $pwd);

	}
	catch (PDOException $e) {
		echo '<p>Error al conectar a la base de datos</p>';
	    exit;
	}
	return $conn;
 }

 ?>
    
asked by Tefef 28.12.2018 в 13:07
source

2 answers

1

partner: I'll put this in another answer, because there are several reasons why it does not work for you.

The first, the connection is created by a function in conexion.php , but in buscar.php you do not call that function to recover the connection, which, at no time, you have available.

The second. Your table is called spare parts , and in the query you have it as respuestos , which means that, even if you had the connection, the table will not locate it.

But the most important thing. The connection you are making using PDO (which is, of course, the best option). However, in buscar.php you use the mysqli extension in procedural, which does not work with the PDO connection. If you use PDO for the connection, you must use the object created for the queries. I include the buscar.php code here (of course, tested and working).

<?php
    require('conexion.php');

    $conexion = dbConnect();

    $consultaBusqueda = $_POST['valorBusqueda'];


    $consulta = "SELECT * FROM repuestos
      WHERE maquina COLLATE UTF8_SPANISH_CI LIKE '%$consultaBusqueda%' 
      OR repuesto COLLATE UTF8_SPANISH_CI LIKE '%$consultaBusqueda%'
      OR CONCAT(maquina,' ',repuesto) COLLATE UTF8_SPANISH_CI LIKE '%$consultaBusqueda%';";

    $resultado = $conexion->query($consulta, PDO::FETCH_ASSOC);

    $mensaje = '';
    foreach ($resultado as $item) {
      $mensaje .= '
            <p>
            <strong>maquina:</strong> ' . $item["maquina"] . '<br>
            <strong>repuesto:</strong> ' . $item["repuesto"] . '<br>
            <strong>Ref.:</strong> ' . $item["ref"] . '<br>
            </p>';      
    }

    if ($mensaje == '') $mensaje = 'Sin resultados';

    echo $mensaje;

?>

I also suggest that when you create a PDO connection you activate the exception detection, which is a help in debugging. The conexion.php script would look like this:

<?php
    function dbConnect (){
        $conn = null;
        $host = 'localhost';
        $db =   'soe';
        $user = 'root';
        $pwd =  '';
        try {
            $conn = new PDO('mysql:host='.$host.';dbname='.$db, $user, $pwd);
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        catch (PDOException $e) {
            echo '<p>Error al conectar a la base de datos</p>';
            exit;
        }
        return $conn;
    }
?>

Look at the line I placed just below the creation of the connection.

Queries in PDO are easier and "cleaner" than in procedural mode. I suggest a couple of links that can help you: link and link .

Keep in mind that in the tests I have put all the codes in the same directory for the test. If you put them in different directories, keep this in mind when doing require .

I hope I helped you. If you have any doubt with this, here I am.

PD. Do not capitalize the name of the host. Instead of Localhost, put localhost. I know it seems to work, but I've been given cases for some time when, suddenly, for no apparent reason, it did not work and it was because of the capitalization.

    
answered by 28.12.2018 / 20:00
source
1

I do not know if it will be a code transcription error, but in HTML you do not have any container with id="resultadoBusqueda" , which is the one you use to host the result.

Since you use jQuery, let it be the one who manages the text field. Replace the following line:

<input type="text" name="busqueda" id="busqueda" value="" placeholder="" maxlength="30" autocomplete="off" onKeyUp="buscar();" />

for this:

<input type="text" name="busqueda" id="busqueda" value="" placeholder="" maxlength="30" autocomplete="off">

When loading the document, it incorporates event detection. Replaces:

$(document).ready(function() {
    $("#resultadoBusqueda").html('<p>JQUERY VACIO</p>');
});

by:

$(document).ready(function() {
    $("#resultadoBusqueda").html('<p>JQUERY VACIO</p>');
    $("#busqueda").on('keyup', function() {
        buscar();
    });
});

Apart from that, as a suggestion, in the browser inspection window, open the Network tab. Each time you press a character in the search field, the php has to "react". For example, below $filas = mysqli_num_rows($consulta); add echo "FILAS: ".$filas; and you should see that result on the Network tab. If it does not appear, the PHP is not running.

It starts there, and if it is not solved you tell me the results and we keep looking for answers. If you can, add the SQL of the export of your table, and the connection file, to be able to reproduce it as you have it, and be able to help you better.

Greetings.

    
answered by 28.12.2018 в 13:40