-2

I have a form, when the user fill the location, it will show the map route and route distance. I want to pass the distance into my PHP variable but I don't know how to do it. Can we pass the JS variable value into JSON and extract it into a PHP variable? If can help me or if there is alternative method(s) please tell me.

Jonathan Eustace
  • 2,469
  • 12
  • 31
  • 54
ascc
  • 33
  • 7

1 Answers1

-1
<script>
jQuery.ajax({
     url:"ajax.php",
     type:"POST",
     data:{distance:distance},
     success:function(data){
        if(data){
            then do something
        }
     }
});
</script>

In ajax.php you can get it as below.

<?php
    $distance = $_REQUEST['distance'];
?>

If you array of values you can do as below.

<script>
dataArray[] = {1000,2000,3000}
var jsonString = JSON.stringify(dataArray);
jQuery.ajax({
     url:"ajax.php",
     type:"POST",
     data:{distance:jsonString},
     success:function(data){
        if(data){
            then do something
        }
     }
});
</script>

In ajax.php you can easily get the request data.

<?php
    $distance = $_REQUEST['distance'];
    foreach($distance as $dist){


    }
?>
Anders
  • 8,307
  • 9
  • 56
  • 88
Gaurav Srivastav
  • 2,381
  • 1
  • 15
  • 18
  • This is a badly formatted mess that is full of syntax errors and bad practises. The question isn't tagged jQuery either. – Quentin Aug 22 '15 at 09:44