Ajax does not send the value of the data to php

2

I have a parameter that I send to a javascript function, when I make an alert of that parameter it shows me its value, there everything is correct. The problem is that I want to send this parameter via Ajax to a php file, but I think it is not doing well because with that value I make an sql query and load a select but it does not do anything.

The value of the select was sent to the function as follows:

<select id="tipo" onchange="cargarCategoria(this.value)">

AJAX Code

function cargarCategoria(dato)
{
    alert(dato)//Me muestra su valor correctamente
    $.ajax({
        data: dato, //Esto es lo que envio a php, que es un elemento de un select
        type: "POST",
        url: '../consultas/consultarCategoria.php',
        success: function(resp){
            $('#categoria').html(resp);
        }
    });
}

PHP Code

 $valor = $_POST["dato"];
  echo '<script>alert ("DATO: '.$valor.'");</script>';

  $tipo = mysqli_real_escape_string($con,$_POST['dato']);

  $sql = "SELECT DISTINCT categoria FROM formacion WHERE tipo = ".$tipo;
  $result = mysqli_query($con, $query);

  while($fila = mysqli_fetch_array($result))
  {
      echo '<option value="'.$fila["categoria"].'">'.$fila["categoria"].'</option>';
  }

How can I know if I'm sending the variable by ajax and how can I handle it in PHP?

    
asked by Mario Guiber 22.05.2018 в 18:53
source

3 answers

3

The problem is that the "data" variable does not exist in PHP. The solution would be to create that variable in json / javascript and send it to PHP like this:

function cargarCategoria(dato)
{
    alert(dato)//Me muestra su valor correctamente
    $.ajax({
        data: {"dato": dato}, //Esto es lo que envio a php, que es un elemento de un select
        type: "POST",
        url: '../consultas/consultarCategoria.php',
        success: function(resp){
            $('#categoria').html(resp);
        }
    });
}
    
answered by 22.05.2018 / 18:56
source
0

To send the parameters via Ajax, you must first create an array:

var Parametros = {
'dato' : dato
}

$.ajax({
        data: Parametros, //Esto es lo que envio a php, que es un elemento de un select
        type: "POST",
        url: '../consultas/consultarCategoria.php',
        success: function(resp){
            $('#categoria').html(resp);
        }
    });
    
answered by 22.05.2018 в 18:56
0

What you send in quotes is the name of the variable and the other the value

This is an example:

data: {"dato": dato},

var nombre="Jose";
var apellido="Garcia";
data: {"Nombre":nombre,
       "Apellido":apellido},

and PHP

echo $_POST['Nombre'];
echo $_POST['Apellido'];

Result

Jose GArcia

    
answered by 22.05.2018 в 19:23