简体   繁体   English

如何使用参数从javascript调用ajax函数

[英]how to call ajax function from javascript with parameters

I have a billing.php file where I have used autocomplete for an address input. 我有一个billing.php文件,其中使用自动完成功能输入地址。

So I am getting the latitude longitude of the location after address is selected. 因此,选择地址后,我将获得该位置的纬度经度。

Now my task is to calculate the distance from the selected address and the latitude ,longitude taken from session. 现在,我的任务是计算与所选地址的距离以及会话中的经度和纬度。

For this I need to create one php file which will calculate the distance and return the distance, after getting this distance I need to check if distance is greater than 1 km and if it is greater I need to show a check box showing 2 hour delivery at bottom. 为此,我需要创建一个php文件,该文件将计算距离并返回距离,获得该距离后,我需要检查距离是否大于1 km,如果更大,则需要显示一个显示2小时交货的复选框在底部。

Now I tried to create a calculateDistance function and a ajax function. 现在,我尝试创建一个calculateDistance函数和一个ajax函数。 But I am not sure how I have to call it from java script function the latitude,longitude variables are not used, I feel I am not passing parameters correct way. 但是我不确定如何从Java脚本函数调用它,未使用纬度,经度变量,我感觉我没有以正确的方式传递参数。

billing.php billing.php

<div class="margin_tb">

    <?php      session_start(); ?>

    <div class="main">
        <div class="bg_white">
            <form method="post" name="billing_frm" id="cart_form">
                <input type="hidden" name="command"/>
                <div align="center">

                    <h1 align="center">Billing Information</h1>

                    <table border="0" cellpadding="2px" width="50%">

                        <tr>
                            <td>Address:</td>

                            <td><input type="text" id="saddress1" name="sadd1" size="35" required/></td>
                        </tr>                           
</div>

<script>    

    // This example displays an address form, using the autocomplete feature
    // of the Google Places API to help users fill in the information.

    // This example requires the Places library. Include the libraries=places
    // parameter when you first load the API. For example:
    // <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">


    var autocomplete;

    var componentForm = {
        street_number: 'short_name',
        route: 'long_name',
        locality: 'long_name',
        administrative_area_level_1: 'short_name',
        country: 'long_name',
        postal_code: 'short_name'
    };

    function initAutocomplete() {
        // Create the autocomplete object, restricting the search to geographical
        // location types.
        autocomplete = new google.maps.places.Autocomplete(
            /** @type {!HTMLInputElement} */(document.getElementById('autocomplete')),
            {types: ['geocode']});

        // When the user selects an address from the dropdown, populate the address
        // fields in the form.
        autocomplete.addListener('place_changed', fillInAddress);
    }

    function fillInAddress() {
        // Get the place details from the autocomplete object.
        var place = autocomplete.getPlace();

        var address = place.formatted_address;
        var latitude = place.geometry.location.lat();
        var longitude = place.geometry.location.lng();

        var mesg = "Address: " + address;
        mesg += "\nLatitude: " + latitude;
        mesg += "\nLongitude: " + longitude;

        <?php $store = $_SESSION['oneShop'];?>

        var myVariable = <?php echo(json_encode($_SESSION['oneShop'])); ?>;

        var lat = <?php echo(json_encode($_SESSION['store_latitude'])); ?>;

        var long = <?php echo(json_encode($_SESSION['store_longitude'])); ?>;

            alert (myVariable);

        if(myVariable === 0) {


            calculateDistance(latitude,longitude,lat,long);


        }
        else
            {
                alert('Multiple shops');
            }



        for (var component in componentForm) {
            document.getElementById(component).value = componentForm.locality;
            document.getElementById(component).disabled = false;
        }

        // Get each component of the address from the place details
        // and fill the corresponding field on the form.
        for (var i = 0; i < place.address_components.length; i++) {
            var addressType = place.address_components[i].types[0];
            if (componentForm[addressType]) {
                var val = place.address_components[i][componentForm[addressType]];
                document.getElementById(addressType).value = val;
            }
        }

    }

    // Bias the autocomplete object to the user's geographical location,
    // as supplied by the browser's 'navigator.geolocation' object.

        function geolocate() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function (position) {
                var geolocation = {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude
                };
                var circle = new google.maps.Circle({
                    center: geolocation,
                    radius: position.coords.accuracy
                });
                autocomplete.setBounds(circle.getBounds());
            });
        }
    }

</script>
<script
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCP-j5J0xjTzFqTNoGCAxO_c46istGzHSA&libraries=places&callback=initAutocomplete"
    async defer></script>

<script>

    $(document).ready(function (e) {
            show_data(0);
        }
    );

    /*===========================================================
     To calculate distance
     ============================================================*/

     function calculateDistance(latitude,longitude,lat,long) {
    $("#cart_area").append('<div class="preloader"></div>');
    $.ajax
    ({
        url: "<?php echo 'http://views/cart/calculateDistance';?>",
        type: 'POST',
        data: { lat1: latitude,
            lat2 : lat,
            long1: longitude,
            long2: long
        },
        success: function (msg) {
            alert(msg);
        }
    });
}

calculateDistance.php computeDistance.php

<?php




   $lat1 = $_POST['lat1'];
   $lat2 = $_POST['lat2'];
   $long1 = $_POST['long1'];
   $long2 = $_POST['long2'];

        $url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=".$lat1.",".$long1."&destinations=".$lat2.",".$long2."&sensor=false&units=metric&mode=driving";
        //$url = "http://maps.googleapis.com/maps/api/directions/json?origin=". $lat1." , ". $long1." &destination= ". $lat2.",". $long2."&sensor=false&units=metric&mode=driving";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $response = curl_exec($ch);
        curl_close($ch);
        $response_a = json_decode($response, true);
        $dist = $response_a['rows'][0]['elements'][0]['distance']['text'];

        return $dist;

?>

I am a beginner in javascript ,php please help. 我是javascript的初学者,php请帮忙。 Thank you. 谢谢。

You point is right,you passed the wrong params in ajax function, change your code to: 您的观点是对的,您在ajax函数中传递了错误的参数,请将代码更改为:

    function calculateDistance(latitude,longitude,lat,long) {
        $("#cart_area").append('<div class="preloader"></div>');
        $.ajax
        ({
            url: "<?php echo base_url('cart/calculateDistance');?>",
            type: 'POST',
            data: { lat1: latitude,
                lat2 : lat,
                long1: longitude,
                long2: long
            },
            success: function (msg) {
                alert(msg);
            }
        });
    }

I think it's the wrong use of this , have a try. 我认为这是错误的使用this ,有一个尝试。 to know more about javaScript this ,just read you-dont-know-js-this--object-prototypes . 要了解有关javaScript this更多信息,只需阅读“ dont-know-js-this-object-prototypes”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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