How to pass a variable from encapsulated function

Not all in one go. No.

since it’s not possible to make it in one go…can you tell me how to make it in several goes…

The techniques to use depend on what you want to achieve.

What are you wanting to use num for?

actually i have certain query as below:

$query2 = “SELECT ObjectID FROM $table where FamilyName=‘$field4’ and FirstName=‘$field5’”;
$test=mysql_query($query2);
while ($array2 = mysql_fetch_row($test))
{
foreach ($array2 as $objID)
{
/print_r(array_values($array2(0)));//echo " $array2[$num]";/
/echo " $array2[“.”<script type=‘text/javascript’> num; </script>"; . “]”;/
/*NOTHING IS DISPLAYED */
}
echo “</tr>”;
}

the array “$array2” contains rows belongs to one attribute “ObjectID”…and i want to refere to this array elements depending on the value of the variable “num”…in other words, i want to use num as index, like:

echo " $array2[$num]";

It seems that the value of num and the contents of the table are quite circuitous.

no, num is a variable the holds the row numbers…
actually, there is a table contains rows based on the query retrieved from mySQL server…
when i click certain row of that table then the variable num holds the row number…then based on the row number the variable num holds …i want index that array “array2”

ImageShack® - Online Photo and Video Hosting

this a link to screen shot maybe gonna help

I’m confused. I’ll have to sleep on this to see if things improve.

to be honest, i#m also confused…:slight_smile:
i’ll try to find any solution for this

It would appear as though you have the table built in PHP and displayed in the browser.
When you click on a table row, you want to get that row index and then use that value to reference data in a secondary array ($array2), right?

The first question that comes to mind is, how is this num value to be used?

  1. as a reference in order to retrieve secondary information
  2. as a reference value to update values in a db
  3. as a reference value to retrieve more data from a db
  4. none of the above…

For each of these scenarios, there are some distinct techniques that can be used to facilitate the requirements but you need to make some distinct changes to your code base. I can help provide that structure, but I will NOT design the functionality or debug. That is for you to do and is how you learn.

First off, you must understand that there is NO natural intrinsic connection between PHP and JAVASCRIPT!!! NONE, NADA, ZIP, ZILCH!!! As has been stated before, PHP is code that resides on the server. It is code that will process on the web server, creating the html code pages that are sent to the client. Once at the client, JS takes over and runs code localized to the client machine. Intrinsically, PHP cannot talk directly to JS and JS cannot talk directly to PHP. LETS GET THIS STRAIGHT RIGHT NOW!!!

As with most anything else, there is a way that they can communicate, but it requires a moderator to happen. This moderator is called AJAX. AJAX provides a means by where JS can talk to and retrieve information from a server via a transparent URL request. This is all done in the background. There is one slight caveat to this technique in that the AJAX request can only be sent to the host PC (server) and not to any other remote server (there are other ways to get this to work).

AJAX can be put in place relatively easy using XMLHttpRequest but you will find that certain browsers (cough cough IE) can be temperamental and may not work correctly (even though MS developed this technique, go figure). Because of this, I would highly recommend you use something like JQuery for you AJAX requests. This package handles all the background cross browser overhead for you.

Anyways… onward. A basic JQuery AJAX request JS function has the following structure:


function doAjax(url, args){
        var retVal;
        retVal =   $.ajax({  
                        type: "GET",
                        url: url,
                        data: args,
                        async: false,
                    }).responseText;
        if(retVal==null || retVal=="")retval=99;
        return retVal;
    }

This is a simple get request, you can choose any type you want, check the documentation:.

I am going to assume you know how to get the “num” value from your table row. What I am going to show you is how to ‘get’ the related data from your PHP server.


function rowclicked(){
   var num = getTableRowSelected();
   var other = getOtherData();
   var url = 'http://'+window.location.hostname+'/mySite/webServices/getRowData.php'; 
   var args = 'num='+num+'&other='+otherdata;
   var retData = doAjax(url,args);
   processRetVal(retVal);
}

Thats all you have to do to request data!!! JS will send a transparent html request to the server, and when it gets the data back, it will process it.

Oh, by the way. You need to now write the PHP request code now.

Simplistically, the basic structure of the PHP code is as follows:


include_once $_SERVER['DOCUMENT_ROOT'].'requiredIncludeFile.php'
$num = 0;
$retVal = 0;

// be smart and do escape tests on the GET data

if(isset($_GET['num'])){
        $num = $_GET['num'];
        if(!is_numeric($num)){
            $retVal = 1;
            echo $retVal;
            exit;
        }
    }
    else {
        $retVal = 1;
        echo $retVal;
        exit;
    }
if($retVal==0){
   // either process directly or just call a function to process and get return value(s)
   $retVal = processNumInPHP();
}
// here is where the differences lie... this service page needs to ECHO the responce
echo $retVal;
exit;

One thing to keep in mind is that the return value must be text. You cannot return arrays, objects, or anythig else (JSON and XML areOK but the JQuery requester needs to be setup to manage this). Typically a preformatted string works great. You can then just dump it into your current page innerhtml or something.

Them there’s the basics. Go crazy and have fun getting it to work.

thanks alot,
would u mind helping me embed these functions in …because i have embedded them in the beginneg of PHP code but after that the code doesnt work any more…



<html>
<head>
   <!-- Script Sources-->
    <link rel="stylesheet" type="text/css" href="styles.css" />
    <style type="text/css">
    <!--@import url("styles.css")-->
    </style>
    <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=DioG219lPJG3WTn3zmQqebsjVg" type="text/javascript"></script>
    <script src="http://serverapi.arcgisonline.com/jsapi/gmaps/?v=1.6" type="text/javascript" ></script>
    <script type="text/javascript">
    
    
    
      var gmap = null;
      var findTask = null;
      var params = null;
      var mapExtension = null;
      var gOverlays = null;
      var gOverlays1 = null;
      var bounds = null;
      var posLatLng = null;
   
      
	function initialize() {
        // GMap construction
        gmap = new GMap2(document.getElementById('gmap'));
	gmap.setCenter(new GLatLng(48.539444, 18.566389), 13); //Velke Pole
        gmap.enableScrollWheelZoom();
	gmap.setMapType(G_HYBRID_MAP);
	gmap.addControl(new GLargeMapControl3D());
	gmap.addControl(new GMapTypeControl());
	gmap.enableScrollWheelZoom();

	
	// Set the min and max scale for each layer
	bounds = gmap.getBounds();
	var minMapScale = 11;
	var maxMapScale = 19;
	
	// get array of map types
	var mapTypes = gmap.getMapTypes();
	//Create MapExtension utility class
	mapExtension = new esri.arcgis.gmaps.MapExtension(gmap);
	
	
       // Find Task
        findTask = new esri.arcgis.gmaps.FindTask("http://g-ags93.hs-karlsruhe.de/ArcGIS/rest/services/slovakei/0617final_WGS/MapServer");
cell();
	}
    //Function for find
	function executeFind(searchText){
	// Find Parameters
		 params = new esri.arcgis.gmaps.FindParameters();
		 params.layerIds = [1];
       
		 var qYear = document.getElementById("qYear").value;
		 
		 	params.searchFields = ["ObjectID"];
			
		// clear map overlays and event listeners using MapExtension removeFromMap
		mapExtension.removeFromMap(gOverlays);
 
		// set find parameters
		params.contains = false;
		params.searchText = searchText;;
		
		// execute find task
	findTask.execute(params, findCompleteCallback);
		
	}
    
	
	//Function for Find function results (zoom to and info window)  
	function findCompleteCallback(response) {
        	var house = response.findResults[0];
		// [API Reference: ArcGIS JavaScript Extension for Google Maps](http://resources.esri.com/help/9.3/arcgisserver/apis/javascript/gmaps/help/topics/apiref.htm#class_esri.arcgis.gmaps.FindResults)

		var houseGeometry = house.feature.geometry[0];
		// [API Reference: ArcGIS JavaScript Extension for Google Maps](http://resources.esri.com/help/9.3/arcgisserver/apis/javascript/gmaps/help/topics/apiref.htm#class_esri.arcgis.gmaps.FindResult)
		// [API Reference: ArcGIS JavaScript Extension for Google Maps](http://resources.esri.com/help/9.3/arcgisserver/apis/javascript/gmaps/help/topics/apiref.htm#class_esri.arcgis.gmaps.Feature)
		// Feature.geometry is an array of GPolygon objects because, Hawaii for example is an ArcGIS Polygon that has multiple rings --
		// where each ring is represented as a GPolygon object in Google Maps API

		var infoWindowOptions1 = {
			contentTabs: [{label:"Building", content: "<b><p>House Number 1850:  </b>{HsNr1850}<br/> <b>Owner:  </b>{owner}<br/><b>Usage:  </b>{house_usag}<br/>"},
			{label:"Other", content:"<br/><b>House Number 1925:  </b>{HsNr1925}"}
			],
			selectedTab:0
		};

		// center and zoom to the result
		var polygonBounds = houseGeometry.getBounds();
		// GPolygon.getBounds method 
		// [Google Maps JavaScript API V2 Reference - Google Maps JavaScript API V2 - Google Code](http://code.google.com/apis/maps/documentation/reference.html#GPolygon)

		var zoomLevel = gmap.getBoundsZoomLevel(polygonBounds);
		// GMap2.getBoundsZoomLevel method
		// [Google Maps JavaScript API V2 Reference - Google Maps JavaScript API V2 - Google Code](http://code.google.com/apis/maps/documentation/reference.html#GMap2)
        
		var polygonCenter = polygonBounds.getCenter();
		// GLatLngBounds.getCenter method 
		// [Google Maps JavaScript API V2 Reference - Google Maps JavaScript API V2 - Google Code](http://code.google.com/apis/maps/documentation/reference.html#GLatLngBounds)
        
		gmap.setCenter(polygonCenter, zoomLevel);
		
		// add the findresutls to google map without any style
		gOverlays = mapExtension.addToMap(house, null, infoWindowOptions1);
      }
	
	
	function ChangeColor(tableRow, highLight)
	{
		if (highLight)
		{
		tableRow.style.backgroundColor = '#7496C2';
		}
		else
		{
		tableRow.style.backgroundColor = 'white';
		}
	}
	
var num;

function setrownum(par)
{
 document.getElementById('idnum').value = par;
 num=par;

}
function  getrownum()
{
return num;
}
	function cell(){
		var tableElem = document.getElementById('Table2').getElementsByTagName('tr');
		for (i = 0; i < tableElem.length; i++) {
			tableElem[i].onclick = function() {
				//alert(this.rowIndex + 1);
			par=this.rowIndex+1;
			setrownum(par);
		        //alert(getrownum()*10);
					
				}
				
		}
		
	//alert(num*100);
  	}
	
  </script>


</head>


<body onload="initialize()">

<div id ="logoCont" style="background-color: #7496C2;">
	<div class = "headline">Cultural Heritage Map of Velk&eacute; Pole, Slovakia
	
	</div>
</div>

<div id="topRightCont" class = "content" style="width: 415px;"><h1>Enter in Last and First Name</h1> 
	<form action="thisBackUpphpProject6Formate.php" method="get">
 
    Family Name:<input type="text" name="field4"><br>
    First Name:<input type="text" name="field5"><br>
           
    <input type="Submit">
    
     NUM: <input type="text" id="idnum" name="num" value=""><br>
   

<div id = "credit" style="position:absolute;top: 817px;">
	<table>
	<tr>
		<td style="vertical-align:top;">
		<div class = "quicklinks" >
		&copy; Hochschule Karlsruhe - Technik und Wirtschaft 2009, <a href="impressum.html">Impressum</a>
		</div>
		</td>
		<td style="vertical-align:top;width:15px;">
		</td>  
		<td style= "width:225px;">
		<a href="http://www.daad.de"><img src="http://www.g.hs-karlsruhe.de/geo/img/daad.gif" width="179" height="13" border="0"></a>
		<a href="http://www.asiin.de"><img src="http://www.g.hs-karlsruhe.de/geo/img/asiin_klein.jpg" width="100" height="53" border="0" vertical-align="bottom" align="left"></a> 
		<a href="http://www.facebook.com/pages/Fakult%C3%A4t-f%C3%BCr-Geomatik-Hochschule-Karlsruhe/166116110093298"><img src="http://www.g.hs-karlsruhe.de/geo/bilder_neue/facebook-logo.png" width="100" height="38" border="0" align = "right" vertical-align="bottom"></a>
		</td>
	</tr> 
	</table>
      </div>	

</form>
	

</div>


<div id="navcontainer" style="position: absolute; top: 185px; left: 15px; width: 815px; height:25px;">
<ul id="navlist">
<li id="active">
	<li><a href="HomePage.html">Home</a></li>
	<li><a href="Map.html">Map</a></li>
	<li><a href="History.html">History</a></li>
	<li><a href="About.html">About</a></li>
</ul>
</div>



<div style="position:absolute; top: 208px; left: 15px; width: 810px; height:500px; overflow:auto; border-style:solid;border-width:3px;border-color:#7496C2">


<?php
function rowclicked()
{   
	var num = getTableRowSelected();   
	var other = getOtherData();   
	var url = 'http://'+window.location.hostname+'/mySite/webServices/getRowData.php';    
	var args = 'num='+num+'&other='+otherdata;   
	var retData = doAjax(url,args);   
	processRetVal(retVal);
}

function doAjax(url, args)
{        
var retVal;        
retVal =  $.ajax(
{                          
type: "GET",                        
url: url,                        
data: args,                        
async: false,                    
}
).responseText;        
if(retVal==null || retVal=="")retval=99;       
return retVal;   
}

include_once $_SERVER['DOCUMENT_ROOT'].'thisBackUpphpProject6Formate.php'
$num = 0;
$retVal = 0;// be smart and do escape tests on the GET data
if(isset($_GET['num']))
{        
$num = $_GET['num'];        
if(!is_numeric($num))
{            
$retVal = 1;            
echo $retVal;            
exit;       
 }   
 }    
 else {       
 $retVal = 1;        
echo $retVal;        
exit;    
}
if($retVal==0){   // either process directly or just call a function to process and get return value(s)   
$retVal = processNumInPHP();
}// here is where the differences lie... this service page needs to ECHO the responce
echo $retVal;
exit; 

$username="gisPrj6@localhost";/*g-ags93*/
$password="$l0vaki4";
$database="slovakia";



$field4=$_GET['field4'];
$field5=$_GET['field5'];
$num=$_GET['num'];

echo "$num";/*NOTHING IS DISPLAYED */

$link =mysql_connect(localhost,'gisPrj6','$l0vaki4');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}

mysql_select_db($database) or die( "Unable to select database");


$table = 'eventtable';


if (empty($field5)) {
    /*echo 'FirstName is either 0, empty, or not set at all';*/
    $query = "SELECT * FROM $table where FamilyName='$field4'";/*Year,Date,FamilyName,FirstName,EventType,AgeSpouse*/
}
else
{
  $query = "SELECT * FROM $table where FamilyName='$field4' and FirstName='$field5'";
}


if (!$sth = mysql_query($query)) {
   die("Ausführen der Abfrage <b>$query</b> nicht möglich: ".mysql_error()."\
");
} 
/*else {
   echo "Ausführen der Abfrage <b>$query</b> war erfolgreich.\
<br />\
";
}*/

echo "<table border='1' cellpadding='2' cellspacing='0' width='790px'><tr>";

/*echo "Table: <b>$table</b><br />\
";*/
for ($i = 0; $i < mysql_num_fields($sth); $i++) {
   $col = mysql_field_name($sth,$i);

   echo "<td width='13%'> <b>$col&nbsp;&nbsp;</b> </td>";
}
echo "</tr></table>";

echo "<table id='Table2' border='1' cellpadding='2' cellspacing='1' width='790px' height='300px'>";


while ($array = mysql_fetch_row($sth)) {
echo "<tr onmouseover='ChangeColor(this, true);' 
              onmouseout='ChangeColor(this, false);' 
              onclick=''>";
   foreach ($array as $col) {
	   
      echo "<td width='13%'>$col&nbsp;&nbsp;&nbsp;</td>";
   }
   
echo "</tr>";
   
}
echo "</table>";

$query2 = "SELECT ObjectID FROM $table where FamilyName='$field4' and FirstName='$field5'";
$test=mysql_query($query2);


while ($array2 = mysql_fetch_row($test)) {
	
	foreach ($array2 as $objID) {
     /*print_r(array_values($array2(0)));*//*echo " $array2[$num]";*/
     /*echo " $array2["."<script type='text/javascript'> num; </script>"; . "]";*/ 
     /*NOTHING IS DISPLAYED */
}
echo "</tr>";
 
}
echo "<script type='text/javascript'> num; </script>";
echo"   $num";/*NOTHING IS DISPLAYED */
mysql_free_result($sth);

?>
</div>


<div id="gmap"  style="position:absolute; top: 208px; left: 915px; width: 810px; height:500px; border-style:solid;border-width:3px;border-color:#7496C2">
</div>
</body>
</html>

The function I provided:

function rowclicked()
{   
    var num = getTableRowSelected();   
    var other = getOtherData();   
    var url = 'http://'+window.location.hostname+'/mySite/webServices/getRowData.php';   
    var args = 'num='+num+'&other='+otherdata;   
    var retData = doAjax(url,args);   
    processRetVal(retVal);
} 

is a dummy function and will not work because the ‘getTableRowSelected()’, ’ getOtherData()', and ‘processRetVal(retVal)’ do not exist, you need to write them or replace them with real data and code.

I provided a shell layout for you to recode to your requirements.

As I stated previously, this is your site, the only way to learn is to do the work, research problems, apply fixes and move on. Asking someone to do it for you is, well, bad form.

I am a self taught developer, and not a very good one. BUT, issues like this make us better in the long run. The answers are right in front of you.

I still am totally confused as to what you are using the num value for. What data are you retrieving with it and how do you use said retrieved data??

One thing I forgot to mention is that you need to either download the JQuery code onto your site, or use something like this to always get the latest release:


<script type="text/javascript">
    //=== Load in any web modules necessary
        google.load("jquery", "1");
        google.load("jqueryui", "1");
</script>

hey guys,
many many thanks for helping me…really i appreciate your efforts.
yesterday i have submitted the project … and the project is accepted although i couldnt manage to implement that functionality the professor wants …but actually i have done what he wants in different way … i would have liked to use jquery and ajax…but according to the time frame i couldnt

any way thank you so much :slight_smile: