0

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.

3
  • 4
    Hi, read up on AJAX. It's the technology you'll need to use. Commented May 22, 2013 at 7:48
  • 1
    in same file without page refresh means AJAX! Commented May 22, 2013 at 7:51
  • He/she did mention AJAX in the question title. Perhaps they needed to be more specific in the body of the question. Commented May 22, 2013 at 7:51

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

i want to pass javascript variable to php function in same file.
That's what AJAX is for. It allows you to pass JavaScript data (a string, for example) to your server. JavaScript and PHP are completely separate technologies, but there are ways of communicating them just like you load a webpage.
0

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

1 Comment

Can't you create a rename the file to basic2.php for example and paste the php code there and remain the javascript in the basic.php?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.