I have a parameter that I send to a javascript function, when I make an alert of said parameter it shows me its value, everything is correct there. The problem is that I want to send that parameter by Ajax to a php file, but I think it's not doing it right because with that value I make an sql query and load a select but it doesn't do anything.
The value of the select was sent to the function like this:
<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 am sending the variable correctly by ajax and how can I treat it in PHP?
The problem is that the variable "data" does not exist in PHP. The solution would be to create that variable in json/javascript and send it to PHP like this:
To send the parameters via Ajax, you must first create an array:
What you send in quotes is the name of the variable and the other the value
This is an example:
and in the PHP
Result
Jose Garcia