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.
            Asked
            
        
        
            Active
            
        
            Viewed 38 times
        
    -2
            
            
        - 
                    Pass the variable into a hidden input element and send across with the post data. – Joshua Terrill Aug 22 '15 at 09:00
- 
                    use ajax to send POST or GET request to a backend php script which can then read that request and process accordingly – Professor Abronsius Aug 22 '15 at 09:00
- 
                    i use window.location.href to pass js variable into php and it works but another problem is . the web page reload continously. – ascc Aug 22 '15 at 09:24
1 Answers
-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
 
    