简体   繁体   中英

Pass javascript variable to php function using ajax in same file without page refresh

I am using PHP function to display geofences. I want to pass javascript variable to php function in same file without page refresh.

function load(id,type){
if(type===2){
  window.location.href="basic.php?idd=" + id;  // i want to change code here

<?php
   $cir =  get_fence_by_type($_GET['idd']);
   if($cir) {
   foreach($cir as $row){
     $fence_id  = $row['geo_id'];
   }
 }
?>

PHP function is:

function get_fence_by_type($id){
    $query = "Select * from geofence where geo_id=".$id;
    $result = pg_exec($query);
    $d  = array();
    while($myrow = pg_fetch_assoc($result)) { 
        $d[] = $myrow;
    }   
    return  $d; //returns result in array
}

javascript window.location.href passes javascript value to php function but it reloads page also.

If you're using jQuery, you can use $.ajax() . It allows you to send data to your server and do something with the response.

Eg:

$.ajax({
    type: 'POST',
    data: myvar
    success: function(Response) { console.log(Response); }
});

will send myvar to your server (with a bit of tweaking of parameters of course) and log whatever the server sends back to your browser console.

Have a read of what you can do with jQuery.

You can do this using jQuery. Basically you don't refresh the page, you just do an async query to the server and you get the response. In the following example the response is showed in alert box.

Your "index" file:

function load(id,type)
{
    $.post("basic.php", { idd: idd }, function(data){ 
          alert(data); 
    });
}

and basic.php

<?php

function get_fence_by_type($id){
$query = "Select * from geofence where geo_id=".$id;
$result = pg_exec($query);
$d  = array();
while($myrow = pg_fetch_assoc($rs)) { 
    $d[] = $myrow;
}   
return  $d;
}
 $cir =  get_fence_by_type($_GET['idd']);
if($cir) {
 foreach($cir as $row){
 $fence_id  = $row['geo_id'];
}
}
?>

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