How to use jQuery variable in PHP

I use MVC in PHP, and I have this script created on my form page to validate three text fields. When these three text fields contain a value, my php code in my controller requests Google Map Api for the nearest directions, based on the input of these three fields.

In my script, I have a "direccion" variable that I need to pass to the controller using PHP, but I'm not sure how to do this.

Script Code (view) :

jQuery(document).ready(function () {

    var direccion="";
    var flag = false;
    jQuery(".validation").change(function () {
        flag = true;
        jQuery(".validation").each(function () {
            if (jQuery(this).val().trim() == "") {
                alert("false");
                flag = false;
            }
        });
        if (flag==true) {

            var calle = jQuery("#ff_elem295").val();
            var municipio = jQuery("#id_municipio option:selected").text();
            var provincia = jQuery("#id_provincia option:selected").text();             

            direccion = calle +","+ municipio +","+ provincia;
            direccion = direccion.replace(/\s/g,'+');
            //alert(direccion);
        }       
});

jQuery.ajax({
            url: "index.php?option=com_cstudomus&controller=saloninmobiliarios&task=calcularDistancias",
            data : direccion,
            dataType : 'html'
        }).done(function(){
                var data = data;
        });
});

PHP code (controller) :

function calcularDistancias(){

    $valor = JRequest::getVar('direccion');

    $url =  'http://maps.googleapis.com/maps/api/geocode/json?address='. $valor .'&sensor=false';

    $data = file_get_contents($url);

    $data_array = json_decode($data,true);

    $lat = $data_array[results][0][geometry][location][lat];
    $lng = $data_array[results][0][geometry][location][lng];
......
}
+4
source share
3 answers

data the property of the object passed to jQuery.ajax is an object.

data : { direccion: direccion }

direccion .

+4

if ajax,

if(flag == true) {
    jQuery.ajax({
        url: "index.php?option=com_cstudomus&controller=saloninmobiliarios&task=calcularDistancias",
        data : {direction : direccion},
        dataType : 'html'
    }).done(function(){
            var data = data;
    });
}
+1

In addition, the extracted data is not in your code, do not forget to put the data in the function done:

.done(function(){
    var data = data;
});

For

.done(function(data){
    var data = data;
});
0
source

Source: https://habr.com/ru/post/1530004/


All Articles