简体   繁体   中英

How to use jQuery variable in PHP

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

In my script I have the variable "direccion" which is what I need to pass to the controller using PHP but im not sure how to accomplish 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];
......
}

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

data : { direccion: direccion }

Then you can access the value of direccion in your controller as a request parameter.

In the if condition put your ajax request like

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;
    });
}

In addition the retrieved data are missing in your code, don't forget to put data in done function :

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

To

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM