The variable does not arrive by POST to PHP through AJAX

1

I have the following script which sends a variable taken from an input, makes a query and returns the fields of that query to then perform more actions, here the AJAX

$(document).ready(function (){
  $("#boton_comprobar_producto").click(function ()
  {
//tomo el texto del input
    var codigo_producto=document.getElementById("input_codigo_producto").value;

$.ajax({
      data: codigo_producto,
      url: "../PHP/consultar_datos_producto.php",
// he puesto y quitado esto de cache y no solucionó nada
      cache: false,
      dataType: "json",
      type: "POST",
      beforeSend: function()
      {
        $('#div_estado_busqueda_producto').html("buscando producto...");
        //ANTES ENVIAR EL DATO COMPRUEBO QUE SI LO ESTA TOMANDO, HASTA AQUI TODO VA BIEN YA QUE ME ALERTA LO QUE ESCRIBO EN EL INPUT
        alert(codigo_producto);
      },
      success: function(respuesta)
      {
        //COMPRUEBO SI NO HAY RESULTADOS
        if(respuesta=="producto no encontrado")
        {   
          $('#div_estado_busqueda_producto').html("Producto no encontrado");
        }
        else
        {
          //mostrar la descripcion del producto
          alert(respuesta[0]);

          //mostrar el costo del producto
          alert(respuesta[1]);

          //borrar contenido del div que decia "buscando producto..." ya que si lo encontró
          $('#div_estado_busqueda_producto').html("");
        }
      },
      error : function()
      {
        alert('Hubo un error');
      }
    });
  });
});

HERE THE check_data_product.php

<?php
require('conectar.php');
//SE SUPONE QUE AQUI RECIBO LA VARIABLE
$codigo_producto=$_POST['codigo_producto'];

//echo para probar que si se este recibiendo el dato, no muestra absolutamente nada en consola del explorador, ni siquiera un null o algo por el estilo lo cual se me hace raro
echo $codigo_producto;

//compruebo algun error en la consulta
if (!mysqli_query($conexion,"SELECT * FROM productos WHERE codigo ='$codigo_producto'"))
{
  echo("Error de MySQL: " . mysqli_error($conexion));
}

//realizo consulta, si aqui en vez de colocar codigo='$codigo_producto' uso codigo='ABC888' el cual yo se que existe, en ese caso funciona todo de maravilla

$result = mysqli_query($conexion,"SELECT * FROM productos WHERE codigo ='$codigo_producto'");

if(mysqli_num_rows($result) > 0)
{
  //armo un array con los resultados
   while($row = mysqli_fetch_array($result))
   {
        //posicion 0 la descripcion del producto
        $output[] = $row["descripcion"];
        //posicion 1 el costo del producto
        $output[] = $row["costo"];
   }
}
if(mysqli_num_rows($result) == 0)
{
     $output='producto no encontrado';
}

echo json_encode($output);

?>

The conclusion I get is that you are not sending the data to the server by POST because as I said before, if I change the variable for a product code that exists, everything works great. Either that or just something wrong with the php

Any ideas?

    
asked by Gabriel Uribe Gomez 04.01.2019 в 05:31
source

2 answers

0

In the javascript you are indicating that you are sending the data in json format. PHP does not automatically perform the parsing when the data comes in that format. You can do it manually like this:

    $_POST = json_decode(file_get_contents('php://input'), true);
    
answered by 04.01.2019 в 07:04
0

You must make the following corrections in JavaScript. What is described below is what you should continue to correct your JavaScript code:

$(document).ready(function (){
  $("#boton_comprobar_producto").click(function () {
    // Si estás utilizando jQuery, se recomienda 
    // obtener el valor de la siguiente manera:
    var codigo_producto = $("#input_codigo_producto").val();

    // Se recomienda crear un objeto para pasar los parámetros
    // al archivo «consultar_datos_producto.php»
    var parametros = {
      "codigo_producto": codigo_producto
    }

    $.ajax({
      data: parametros,
      url: "../PHP/consultar_datos_producto.php",
      cache: false,
      dataType: "json",
      type: "POST",

      beforeSend: function() {
        $('#div_estado_busqueda_producto').html("Buscando producto...");
      },

      success: function(content, status) {
        // Se recomienda realizar las comprobaciones así:
        if (status == "success") {
          $('#div_estado_busqueda_producto').html(content);
        }

      },

      error : function(jqXHR, textStatus) {
        // Debe mostrar el siguiente resultado si se presenta
        // un error en el archivo consultar_datos_producto.php
        $('#div_estado_busqueda_producto').html(jqXHR.responseText);
      }
    });

  });
});

As for the file « consult_product_data.php », I recommend you initialize the variable $ output if you have not done it in another file, that is:
$output = "";

In addition, you must put '@' so that no error is shown if the request has not been sent using the POST method. It is recommended to use it in production the '@'. For example:

$codigo_producto = @$_POST['codigo_producto'];

On the other hand, delete:

echo $codigo_producto; // De lo contrario, se producirá un error en tu proyecto.
    
answered by 04.01.2019 в 07:53