how to get the value from ajax to php?

0
$(document).ready(function(){

    $('#estados_visa').on('change', function(){
        var distritos= $('#estados_visa').val();


        console.log(distritos)
        $.ajax({
            type:'POST',
            url: 'cargar_distritos.php',
            data:{dato1: distritos}
        })
        .done(function(lista_rep){
            $('#distritos_visa').html(lista_rep);
        })
        .fail(function(){
            alert('error al cargar las listas');
        });
    })
});

This is my carga_distritos

function getListDis(){
$con = getCon();
$id = $_POST['dato1'];
$query = "SELECT commerce_brand, commerce_region, commerce_district FROM commerc WHERE commerce_region = $id GROUP BY commerce_district  ORDER BY commerce_district, commerce_region";
$result = $con->query($query);
$listas_distritos = '<option value="">Elige una opcion</option>';
$listas_distritos .= '';
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$listas_distritos .= "<option value='$row[commerce_region]'>$row[commerce_district]</option>";
}
return $listas_distritos;
}
    
asked by ivan fuenmayor 24.10.2018 в 23:31
source

1 answer

2

In PHP the functions are not called alone.

If everything you have in the PHP file is what you sample, that code will never be executed because getListDis() is never called.

You can do the following:

  • Verify the POST variable.
  • If it exists, you pass it to the function, if there is no sample an error message or whatever.

For example:

$dato=(empty($_POST['dato1'])) ? NULL : $_POST['dato1'];

if ($dato){
    getListDis($dato);
}else{
    return "Error, no se posteó dato1";
}

function getListDis($id){
    $con = getCon();
    $query = "
               SELECT commerce_brand, commerce_region, commerce_district 
               FROM commerc 
               WHERE commerce_region = $id 
               GROUP BY commerce_district  
               ORDER BY commerce_district, commerce_region";
    $result = $con->query($query);
    $listas_distritos = '<option value="">Elige una opcion</option>';
    $listas_distritos .= '';
    while($row = $result->fetch_array(MYSQLI_ASSOC)){
        $listas_distritos .= "<option value='$row[commerce_region]'>$row[commerce_district]</option>";
    }
    return $listas_distritos;
}
  

NOTE ON SECURITY:

     

Your query is highly vulnerable to SQL injection attacks.   It is advisable that you implement prepared queries to avoid this serious   risk.

    
answered by 25.10.2018 в 00:29