user2393867
user2393867

Reputation:

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.

Upvotes: 0

Views: 5766

Answers (2)

Jared
Jared

Reputation: 3016

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.

Upvotes: 1

Deepsy
Deepsy

Reputation: 3800

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'];
}
}
?>

Upvotes: 0

Related Questions