Solved

Pass PHP SESSION Variable to Javascript Array

Posted on 2008-10-19
19
2,032 Views
Last Modified: 2013-12-13
I have a scenario where  I have a php call to retrieve a result set from a database.  the php file is called from a javascript function, and using AJAX it returns the rows and puts 2 of the fields into a select box option set.  

Now, what I need to do is to take the full result set and put it into a Javascript array that I have previously created in the Main js file.  
I had thought about using the SESSION variable in php to bring back the full array and then somehow loop through the SESSION array to move the results into the javascript array, but I'm not sure.

The sequence goes like this so far
Main php file --> js function file --> AJAX function file --> php query file --> Return to AJAX Function (statechanged) --> ?????

Help is greatly appreciated.

I can provide whatever code you think is needed to help me figure this out, just ask. :-)

OldHatt45
0
Comment
Question by:OldHatt45
  • 10
  • 9
19 Comments
 
LVL 19

Expert Comment

by:LordOfPorts
ID: 22753183
One approach would be to loop through the result set in PHP and construct a string whereby each item would be separated by a delimiter which should a unique combination which does not occur within the items. e.g. || and at the end you return the string from PHP which would look like:

"ItemA||ItemB||ItemC||ItemD"

Then on the client side you can use Javascript's split function http://www.w3schools.com/jsref/jsref_split.asp break the string into individual elements and construct an array, e.g.:

var str = "ItemA||ItemB||ItemC||ItemD";

var myArray = str.split("||");

for(var i = 0; i < myArray.length; i++) {
    alert(myArray[i]);
}
0
 

Author Comment

by:OldHatt45
ID: 22753239
LordOfPorts,

The Idea is GOOD!  But my problem is returning "the string" or SESSION or ????
from php to javascript.

Can you give me an example of how to do that??

Thanks
OldHatt45
0
 
LVL 19

Expert Comment

by:LordOfPorts
ID: 22753304
The return value is basically anything printed to the screen by the PHP page, i.e. when you e.g. use echo in your PHP page:

echo "ItemA||ItemB||ItemC||ItemD";

The responseText property of the XMLHttpRequest object in your AJAX implementation would contain the string above and you can call Javascript's split function on it.

So let's say you would like to return every single variable from a PHP array like e.g. the result set returned by a query:

// This would be the PHP page
foreach ($ArrayName as $value) {
    $StringToReturn .= $value.'||';
}

echo $StringToReturn;
0
 

Author Comment

by:OldHatt45
ID: 22753530
LordOfPorts,

I Apologize for being stupid.  
I just don't understand.  I don't want the array displayed on screen.  I just want the query result put into a javascript array, so I can use it elsewhere in the page.

Please see the code below and put in the right stuff.
The code below is the Query file (php).

Do you need any other code to help sort this out??

Thanks

OldHatt45



//From the js file that calls the query

function ShowBACEType(Grppicked, Catpicked) { // Shows the pictures in that category.

  //Need this to bridge to selecting from the database.

  alert (" In ShowBACEType ");

  xmlHttp=GetXmlHttpObject();

  if (xmlHttp==null) {

	 alert ("Browser does not support HTTP Request");

     return;

  }

  var url="http://sentinel/BACE/BACETypeQry.php"

  //Next Line for Production 

  url=url+"?q="+escape(Catpicked)+"&r="+escape(Grppicked);

  url=url+"&sid="+Math.random();

  alert ("ShowBACEType  url =  " + url);

  xmlHttp.onreadystatechange=stateChanged 

  xmlHttp.open("GET",url,true)

  xmlHttp.send(null)

//end of calling function - js file.
 

//start - from the QryType.php file

$query_rsBACEstkType = "SELECT stkdesigntypes.sku, stkdesigntypes.typepicture, stkdesigntypes.stkdestitle, stkdesigntypes.stkCategory, stkdesigntypes.stkGroup, stkdesigntypes.stkType, stkdesigntypes.stkdesComment FROM stkdesigntypes WHERE stkCategoryIndex = " .$q. " AND stkGrpIndex = " .$qryALL. ""; 

// If uncommented, the query shows up on screen.  For test only.;

// echo ( "query_rsBACEstkType  = " .$query_rsBACEstkType);

$rsBACEstkType = mysqli_query($BACEMySQL, $query_rsBACEstkType ) or die(mysql_error());

$totalRows_rsBACEstkType = mysqli_num_rows($rsBACEstkType);
 

      while ($row_rsBACEstkType = mysqli_fetch_assoc($rsBACEstkType)) { 

      // while ($row = mysql_fetch_array($result)) 

        $SDsku = $row_rsBACEstkType['sku'];

	$SDpicfile = $row_rsBACEstkType['typepicture'];

	$SDTitle = $row_rsBACEstkType['stkdestitle'];

	$SDstkCat = $row_rsBACEstkType['stkCategory'];

	$SDstkGrp = $row_rsBACEstkType['stkGroup'];

	$SDstktype = $row_rsBACEstkType['stkType'];

	$SDstkcommnt = $row_rsBACEstkType['stkdesComment']; 

	$myStkDes[] = $row_rsBACEstkType;

         }
 

//End of queryType php file

Open in new window

0
 
LVL 19

Expert Comment

by:LordOfPorts
ID: 22753632
OldHatt45, no problem at all, in the above code snippet you have a while loop starting on line 27, this is where you would begin constructing the string you wish to return to Javascript, e.g.:

$StringToReturn = "";

while ($row_rsBACEstkType = mysqli_fetch_assoc($rsBACEstkType)) {
  foreach($row_rsBACEstkType as $value) {
      $StringToReturn .= $value.'||';
  }
}

echo $StringToReturn;

Ok, so in your Javascript code you call the stateChanged function in which you retrieve the returned text by checking the responseText property, this property will contain the entire string you returned from PHP and at that point you can use the split function to create an array out of the value.
0
 

Author Comment

by:OldHatt45
ID: 22753759
LordOfPorts

This makes sense except that I'm already using the xmlHttp.responsetext command to create the select box.
I apologize, I didn't show that piece of the code in the php file.
A more complete piece of the code is attached

Hope you can follow this whole thing.

Thanks
OldHatt45
<?php 

session_start();

require_once("./Connections/BACEMySQL.php"); 
 

ini_set('display_errors', 1);

error_reporting(E_ALL);

 

mysqli_select_db($BACEMySQL, $database_BACEMySQL);

if ( ! $BACEMySQL) {

     die( "Couldn't connect to MySQL:  ".mysql.error() );

}
 

// function retrieveQueryType($debug=FALSE) { 

$debug=FALSE;
 

// USAGE: 

//  retrieveQueryType(TRUE);  -- will die with debug info on failures 

//   retrieveQueryType(); || retrieveQueryType(FALSE); -- no debugging (default) 

// RETURNS: 

//  number of rows if successful 

//  0 if no rows selected 

//  FALSE if query failed 

$q=$_GET["q"];

$r=$_GET["r"];

//$q="7";  //for testing qry file 

//$r="4";  //for testing qry file
 

if ( $r == 0 || $r == "0") {

	$qryALL = "*";

} else {

	$qryALL = $r;

}

//$qryALL = $r;
 

//$query_rsBACEstkType = "SELECT sku, typepicture, stkdestitle, stkCategory, stkGroup, stkType, stkdesComment FROM stkdesigntypes WHERE stkCategory = $_REQUEST[firstlvl] AND stkGroup = $qryALL"; 

$query_rsBACEstkType = "SELECT stkdesigntypes.sku, stkdesigntypes.typepicture, stkdesigntypes.stkdestitle, stkdesigntypes.stkCategory, stkdesigntypes.stkGroup, stkdesigntypes.stkType, stkdesigntypes.stkdesComment FROM stkdesigntypes WHERE stkCategoryIndex = " .$q. " AND stkGrpIndex = " .$qryALL. ""; 

// echo ( "query_rsBACEstkType  = " .$query_rsBACEstkType);

$rsBACEstkType = mysqli_query($BACEMySQL, $query_rsBACEstkType ) or die(mysql_error());

$totalRows_rsBACEstkType = mysqli_num_rows($rsBACEstkType);

//$_SESSION['totalSDrows'] = $totalRows_rsBACEstkType;
 

	  

  if($totalRows_rsBACEstkType > 0)

  // if($result = mysql_query($query)) 

  { 

    if($success = mysqli_num_rows($rsBACEstkType) > 0) 

    { 

      //echo "<select name='selBACEStkDes' onchange='submitForm();'>\n"; 

      echo("<select size=15 style='width:200px; font:8pt verdana' name=\"selBACEStkDes\" onchange=\"ShowBACEPic(frmBACEStk.selBACEStkDes.options.selectedIndex);\">"); 

      //echo "<option>-- Please select --</option>\n"; 

     //echo ("Working");

      //Now fill the table with data 

		$myStkDes = array();

		$StringToReturn = "";

      while ($row_rsBACEstkType = mysqli_fetch_assoc($rsBACEstkType)) { 

      	    foreach($row_rsBACEstkType as $value) {

		  $StringToReturn .= $value.'||';

	    }

        $SDsku = $row_rsBACEstkType['sku'];

		$SDpicfile = $row_rsBACEstkType['typepicture'];

		$SDTitle = $row_rsBACEstkType['stkdestitle'];

		$SDstkCat = $row_rsBACEstkType['stkCategory'];

		$SDstkGrp = $row_rsBACEstkType['stkGroup'];

		$SDstktype = $row_rsBACEstkType['stkType'];

		$SDstkcommnt = $row_rsBACEstkType['stkdesComment']; 

		$myStkDes[] = $row_rsBACEstkType;

		//if (isset($_SESSION)) {

     	//	$_SESSION['myStkDes'] = $row_rsBACEstkType;

		//}

		// $Customername = $row['Customername'];

		//echo $SDTitle ."\n";

        //$type = $row['type']; 

		echo("<option value=\"$SDpicfile\">$SDTitle</option>"); 

		//MainArray[MainVar++] = new Fix($SDsku, $SDpicfile, $SDTitle, $SDstkCat, $SDstkGrp, $SDstktype, $SDstkcommnt)

		//alert (" MainArray row is " + MainArray[MainVar];

      } 

      echo("</select>"); 

    } elseif ($debug) { 

      die("retrieveQueryType(): No rows returned by query"); 

    } 

  } else { 

    $success = FALSE;

	echo ("No Pictures Available");

    if($debug) { 

      die("retrieveQueryType(): query failed - ".mysql_error()); 

    } 

  } 

  // return($success); 

 
 

?>
 

========================== End of QryType.php file ==================
 

============= Start of ShowBACE function ============================

=============== From js file ===================================

function ShowBACEType(Grppicked, Catpicked) { // Shows the pictures in that category.

  //Need this to bridge to selecting from the database.

  alert (" In ShowBACEType ");

  xmlHttp=GetXmlHttpObject();

  if (xmlHttp==null) {

	 alert ("Browser does not support HTTP Request");

     return;

  }

  var url="http://sentinel/BACE/BACETypeQry.php"

  url=url+"?q="+escape(Catpicked)+"&r="+escape(Grppicked);

  url=url+"&sid="+Math.random();

  alert ("ShowBACEType  url =  " + url);

  xmlHttp.onreadystatechange=stateChanged 

  xmlHttp.open("GET",url,true)

  xmlHttp.send(null)

}

================ End of ShowBACEType function ======================
 

================Start of StateChanged function =====================

================ From ajax js file =================================

function stateChanged()

{

   alert ( " IN stateChanged  readyState =  " + xmlHttp.readyState);

   if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")

   {

      if (xmlHttp.status == 200) { 

	  <!-- document.getElementById("txtResult").innerHTML= xmlHttp.responseText; -->

           <!--document.getElementById("typeList").innerHTML= xmlHttp.responseText; -->

		   //alert ("xmlHttp.responsetext =  " + xmlHttp.responseText);

           //PicSpot is the div tag in the main file with the form;

           document.getElementById("PicSpot").innerHTML= xmlHttp.responseText; 

	  } else {

		  //Handle error

	  } 

   } else {

           //alert(xmlHttp.status);

   }

}

Open in new window

0
 
LVL 19

Expert Comment

by:LordOfPorts
ID: 22753849
I would recommend changing that if you would like to pass all of the data to the client. Basically the intention of AJAX is to separate the user interface from the data so your PHP page should not be building the select box or other elements, its only purpose should be to retrieve the data and provide it to the client, in best case scenario in XML or JSON format or for simplicity in a simple format such as a string in this case with each element separated by a delimiter such as ||. The client would receive the data in the xmlHttp.responseText property and parse it; Javascript itself should be building user interface elements such as the select box.
0
 

Author Comment

by:OldHatt45
ID: 22754406
Lord ofPorts

OK, I can understand that.  Since the Select Box is built from parts of the query result it should be doable.  

I changed the Type Qry.php file to echo back the $StringToReturn.  That part works, I get a "||" delimited string.  I've looked at the split function reference you provided and understand that.

So I know that I'm gettiing a return result.  The responsetext is a delimited string.  
I just tried substituting the following code in statechanged function.
           var respString = xmlHttp.responsetext;
           document.getElementById("PicSpot") = respString;
for
           document.getElementById("PicSpot").innerHTML= xmlHttp.responseText;

I get an error "Wrong number of arguements or invalid property assignment" that refers me to the 2nd line above where I set the PicSPot to respString.  Don't understand that??

Now, each record is 7 fields long.  How do I break the responsetext into separate records of 7 fields each?

Thanks

OldHatt45
0
 

Author Comment

by:OldHatt45
ID: 22755046
LordOfPorts
OK, I figured out what I did wrong.
In the statechanged function, I changed it to what I've attached below.
I am getting the Results as what looks like a single record in an array.

Now all I need to do is figure out how to break up the result into records of 7 fields each.
Any ideas would be appreciated.

Thanks
OldHatt45
function stateChanged()

{

   var respStringArray = new Array();

   alert ( " IN stateChanged  readyState =  " + xmlHttp.readyState);

   if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")

   {

      if (xmlHttp.status == 200) { 

	  <!-- document.getElementById("txtResult").innerHTML= xmlHttp.responseText; -->

           <!--document.getElementById("typeList").innerHTML= xmlHttp.responseText; -->

		   alert ("xmlHttp.responsetext =  " + xmlHttp.responseText);

           var respString = xmlHttp.responseText;

		   respStringArray = respString.split("||");

		   alert ("the respStringArray Var is  " + respStringArray);

		   //document.getElementById("PicSpot") = respString; 

		   // document.getElementById("PicSpot").innerHTML= xmlHttp.responseText; 

	  } else {

		  //Handle error

	  } 

   } else {

           //alert(xmlHttp.status);

   }

}

Open in new window

0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 19

Expert Comment

by:LordOfPorts
ID: 22759724
Excellent! There are several approaches that can be taken depending on what you would like to do with the data; since we know that each record is represented by 7 array elements we can e.g. loop through the array and at every 7 elements break to do a task. The code snippet below has an example algorithm along with comments to demonstrate this approach. It shows how to add 7 elements at a time to a string however one can of course do another action such as add them to an array or use them as a value of an HTML element such as a select box:
<script type="text/javascript">
 

// Data returned by the PHP page

var ReturnedData = "1||2||3||4||5||6||7||8||9||10||11||12||13||14";
 

// Split the data by the delimiter

var aArray = ReturnedData.split("||");
 

// Inform us how many items there are

alert(aArray.length);
 

// String variable to store 7 items at a time

var sRecord = "";
 

var nItems = 7; // how many items compose a record
 

// Loop through the array and create one string record for every 7 items

for(var i = 0; i < aArray.length; i++) {

	// Add the array element to the string

	sRecord += aArray[i];

	

	// If we have reached 7 elements we break

	if((i + 1) % nItems == 0 && i != 0) {

	

		// sRecord now contains a segment of 7 elements

		alert("Record : " + sRecord); 

		sRecord = "";

	}

}
 

</script>

Open in new window

0
 

Author Comment

by:OldHatt45
ID: 22766651
Lord of Ports

Could you provide an example of adding the 7 field elements per record to an array?
Would appreciate it.

This example was great, and it works,  but I need the elements added to an array.
Thanks
OldHatt45
0
 
LVL 19

Expert Comment

by:LordOfPorts
ID: 22768146
Yes, certainly. To do that we need to create a two-dimensional array, an array of arrays whereby each record in the array will be an array of 7 items. Once the array is created you will be able to reference the items by specifying the index of the record and the sub-index, so e.g. if you wish to access the third of seven values of the second record:

NameOfArray[1][2];
<script type="text/javascript">

 

// Data returned by the PHP page

var ReturnedData = "1||2||3||4||5||6||7||8||9||10||11||12||13||14";

 

// Split the data by the delimiter

var aArray = ReturnedData.split("||");

 

// Inform us how many items there are

alert(aArray.length);
 

// Create the 2-D array

var TwoDArray = new Array();
 

var NUM_OF_ITEMS = 7; // Per record
 

// Add new array to the 2 dimensional array for each record

for(var n = 0; n < aArray.length / NUM_OF_ITEMS; n++) {

	TwoDArray.push(new Array());

}
 

var nIndex = 0;
 

for(var i = 0; i < aArray.length; i++) {

	TwoDArray[nIndex].push(aArray[i]);

	

	// If we have reached 7 elements we increment the 2-D array's index

	if((i + 1) % NUM_OF_ITEMS == 0 && i != 0) {

		nIndex++;

	}

}
 

// Let's display the content of the new 2-D array

for(var m = 0; m < TwoDArray.length; m++) {

	document.write("TwoDArray[" + m + "] : ");

	

	for(var x = 0; x < TwoDArray[m].length; x++) {

		document.write(TwoDArray[m][x] + " ");

	}

	document.write("<br />");
 

}
 

</script>

Open in new window

0
 

Author Comment

by:OldHatt45
ID: 22773574
LordOfPorts

OK, I've Got it working.  But I seem to ave a timing problem.
I have to put an "alert" message in to slow things down.
It's weird.  Any ideas?????  I can post the code if you want to look at it.

Thanks
OldHatt45
0
 
LVL 19

Expert Comment

by:LordOfPorts
ID: 22778647
Yes, please post the code and can you describe what happens regarding the timing issue? Does it call a function before it finishes obtaining the data?
0
 

Author Comment

by:OldHatt45
ID: 22778960
LordOfPorts
OK, I have posted the code below.  
If I remove the comment "Loading Designs Now" the select box entries don't get there.
If I put the comment in, all is fine and everything works the way it's supposed to.
I purposely removed the one function call from the routine figuring this is something you might want to have me remove. :-)

I think I've got all the pertinent code posted below.  If I don't, please Ask.

Thanks, and I really appreciate all the HELP!!!!!

OldHatt45

//When the user clicks on the Group Select box and makes a selection,

//  The SHowBACEType function is called with the numerical indexes

//  of the Caategory and Group select boxes.
 

function ShowBACEType(Grppicked, Catpicked) { // Shows the pictures in that category.

  //Need this to bridge to selecting from the database.

  //alert (" In ShowBACEType ");

  xmlHttp=GetXmlHttpObject();

  if (xmlHttp==null) {

	 alert ("Browser does not support HTTP Request");

     return;

  }

  MainVar = 0;

  //Next Line for Production 

  var url="http://bace.com/Test/BACETypeQry.php"

  url=url+"?q="+escape(Catpicked)+"&r="+escape(Grppicked);

  url=url+"&sid="+Math.random();

  xmlHttp.onreadystatechange=stateChanged; 

  xmlHttp.open("GET",url,true);

  xmlHttp.send(null);

  

  ActiveArray.length = 0;

  PicList = "<SELECT size=13 style='width:200px; font:8pt verdana; font-weight:bold' name='selBACEStkDes' onChange='ShowBACEPic(frmBACEStk.selBACEStkDes.options.selectedIndex);'>";

  ActiveVar = 0;

  current = 0;

  

  alert ("Loading Designs Now");

  for (loop=0; loop < MainVar; loop++) {

      PicList = PicList + "<option value=" + MainArray[loop][1] + ">" + MainArray[loop][5] + "</option>"; 

  }

  PicList = PicList + "</select>";

  //alert (PicList);

  document.getElementById("PicSpot").innerHTML = PicList;

}
 

function ShowBACEPic(newpic) { // Shows the photo and text on the page.

  current = newpic;

  SelectionBox = document.frmBACEStk.selBACEStkDes;

  //alert ("In ShowBACEPic newpic is = " + newpic + "  The SelectionBox variable is  " + SelectionBox.selectedIndex);

  if (current >= 0) {

  	SelectionBox.options[current].selected = true;

  	//alert ("Line 198");

  	document.getElementById("BACESpot").innerHTML = '<a href=javascript:BACERemPic("' + ActiveArray[current].PicVal + '");><img name="PicShowing" src=' + ActiveArray[current].PicVal + ' height=200 border=0></a>';

  	document.getElementById("Journal").outerHTML = '<div id=journal><br><b>' + ActiveArray[current].TitVal + '</b><p>' + ActiveArray[current].DatVal + '<p style="text-align:justify; text-indent:25px">' + ActiveArray[current].TxtVal + '</div>';

  //if (document.frmBACEStk.WhereView[1].checked) {

  //  timerID = setTimeout("BACERemPic(ActiveArray[current].PicVal)",1000)

  //}

  	if (document.frmBACEStk.SelectedMode[0].checked) {

		timerSlideShow = setTimeout("NxtBACEPic();",document.frmBACEStk.Timer.value*1000)

		LoadNextPic();

	} else {

		LoadNextPic();

	}

  }

}
 

=================================================================
 

function stateChanged()

{

   var respStringArray = new Array();

   //alert ( " IN stateChanged  readyState =  " + xmlHttp.readyState);

   if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")

   {

	  ActiveVar = 0;

      if (xmlHttp.status == 200) { 

	  <!-- document.getElementById("txtResult").innerHTML= xmlHttp.responseText; -->

           <!--document.getElementById("typeList").innerHTML= xmlHttp.responseText; -->

		   //alert ("xmlHttp.responsetext =  " + xmlHttp.responseText);

           var respString = xmlHttp.responseText;

		   respStringArray = respString.split("||");

		   //alert ("the respStringArray Var is  " + respStringArray);

		   var respLen = respStringArray.length;

		   //alert ("respLen =  " + respLen);

			// String variable to store 7 items at a time

//			var sRecord = "";

			 

			var nItems = 7; // how many items compose a record
 

			// Create the 2-D array

			var TwoDArray = new Array();

			MainArray.length=0;

			//var NUM_OF_ITEMS = 7; // Per record

			 

			// Add new array to the 2 dimensional array for each record

			for(var n = 0; n < respStringArray.length / nItems; n++) {

//				TwoDArray.push(new Array());

				MainArray.push(Array());

			}

			 

			var nIndex = 0;

			 

			for(var i = 0; i < respStringArray.length; i++) {

//				TwoDArray[nIndex].push(respStringArray[i]);

				MainArray[nIndex].push(respStringArray[i]);

				

				// If we have reached 7 elements we increment the 2-D array's index

				if((i + 1) % nItems == 0 && i != 0) {

					nIndex++;

					MainVar = nIndex;

				}

			}  

	  } else {

		  //Handle error

	  } 

   } else {

           //alert(xmlHttp.status);

   }

Open in new window

0
 
LVL 19

Expert Comment

by:LordOfPorts
ID: 22779829
Ok, to correct the problem move line 13 and lines 22-33 in the code snippet above from the ShowBACEType function to the end of the stateChanged function. You can comment out the alert line. The issue is that stateChanged does not finish obtaining and parsing the data before the new select box is created in the lines 22-33, this part of the code should go to the end of the stateChanged function; the alert gave stateChanged function some time to finish the work however if you move the code as specified it should work w/o the alert.

Also on lines 67 and 68 use // to comment them out, the HTML comment <!-- is a syntax error in JS.

I have updated the configuration below if you would like to try, please let me know if it works:
// When the user clicks on the Group Select box and makes a selection,

//  The SHowBACEType function is called with the numerical indexes

//   of the Caategory and Group select boxes.

 

function ShowBACEType(Grppicked, Catpicked) 

{ 

    // Shows the pictures in that category.

    // Need this to bridge to selecting from the database.

    // alert (" In ShowBACEType ");

    xmlHttp=GetXmlHttpObject();

  

    if (xmlHttp==null) {

	  alert ("Browser does not support HTTP Request");

      return;

    }

  

    //Next Line for Production 

    var url="http://bace.com/Test/BACETypeQry.php"

    url = url+"?q=" + escape(Catpicked) + "&r=" + escape(Grppicked);

    url = url+"&sid=" + Math.random();

    xmlHttp.onreadystatechange=stateChanged; 

    xmlHttp.open("GET",url,true);

    xmlHttp.send(null);

}

 

function ShowBACEPic(newpic) 

{ 

    // Shows the photo and text on the page.

    current = newpic;

    SelectionBox = document.frmBACEStk.selBACEStkDes;

    //alert ("In ShowBACEPic newpic is = " + newpic + "  The SelectionBox variable is  " + SelectionBox.selectedIndex);

    if (current >= 0) {

  	    SelectionBox.options[current].selected = true;

  	    //alert ("Line 198");

  	    document.getElementById("BACESpot").innerHTML = '<a href=javascript:BACERemPic("' + ActiveArray[current].PicVal + '");><img name="PicShowing" src=' + ActiveArray[current].PicVal + ' height=200 border=0></a>';

  	    document.getElementById("Journal").outerHTML = '<div id=journal><br><b>' + ActiveArray[current].TitVal + '</b><p>' + ActiveArray[current].DatVal + '<p style="text-align:justify; text-indent:25px">' + ActiveArray[current].TxtVal + '</div>';

        //if (document.frmBACEStk.WhereView[1].checked) {

        //  timerID = setTimeout("BACERemPic(ActiveArray[current].PicVal)",1000)

        //}

  	    if (document.frmBACEStk.SelectedMode[0].checked) {

		    timerSlideShow = setTimeout("NxtBACEPic();",document.frmBACEStk.Timer.value*1000)

		    LoadNextPic();

	    } 

	    else {

		    LoadNextPic();

	    }

    }

}

 

//=================================================================

 

function stateChanged()

{

    var respStringArray = new Array();

    //alert ( " IN stateChanged  readyState =  " + xmlHttp.readyState);

    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {

	    ActiveVar = 0;

        if (xmlHttp.status == 200) { 

	        // <!-- document.getElementById("txtResult").innerHTML= xmlHttp.responseText; -->

            // <!--document.getElementById("typeList").innerHTML= xmlHttp.responseText; -->

		    // alert ("xmlHttp.responsetext =  " + xmlHttp.responseText);

            var respString = xmlHttp.responseText;

		    respStringArray = respString.split("||");

		    // alert ("the respStringArray Var is  " + respStringArray);

		    var respLen = respStringArray.length;

		    // alert ("respLen =  " + respLen);

			// String variable to store 7 items at a time

            // var sRecord = "";

			 

			var nItems = 7; // how many items compose a record

 

			// Create the 2-D array

			var TwoDArray = new Array();

			MainArray.length=0;

			//var NUM_OF_ITEMS = 7; // Per record

			 

			// Add new array to the 2 dimensional array for each record

			for(var n = 0; n < respStringArray.length / nItems; n++) {

                // TwoDArray.push(new Array());

				MainArray.push(Array());

			}

			 

			var nIndex = 0;

			 

			for(var i = 0; i < respStringArray.length; i++) {

                // TwoDArray[nIndex].push(respStringArray[i]);

				MainArray[nIndex].push(respStringArray[i]);

				

				// If we have reached 7 elements we increment the 2-D array's index

				if((i + 1) % nItems == 0 && i != 0) {

					nIndex++;

					MainVar = nIndex;

				}

			}

			

			MainVar = 0;

			

			ActiveArray.length = 0;

            PicList = "<SELECT size=13 style='width:200px; font:8pt verdana; font-weight:bold' name='selBACEStkDes' onChange='ShowBACEPic(frmBACEStk.selBACEStkDes.options.selectedIndex);'>";

            ActiveVar = 0;

            current = 0;

  

            //alert ("Loading Designs Now");

            for (loop=0; loop < MainVar; loop++) {

                PicList = PicList + "<option value=" + MainArray[loop][1] + ">" + MainArray[loop][5] + "</option>"; 

            }

            PicList = PicList + "</select>";

            //alert (PicList);

            document.getElementById("PicSpot").innerHTML = PicList;

	   } 

	   else {

		   //Handle error

	   } 

   } else {

           //alert(xmlHttp.status);

   }

}

Open in new window

0
 

Author Comment

by:OldHatt45
ID: 22805568
LordOfPorts,
Sorry, got sidetracked on something else.
I tried making the changes as you suggested.  
The result was a blank select box.  Using Fiddler, I do see that it does return the right result from the query, but doesn't seem like it's putting the options into the select box.  It is creating the select box, just not putting in the options.  

I need to do some investigating but I think there is a problem with the arrays.  Any ideas on how to pin that down????

Thanks
OldHatt45
0
 
LVL 19

Accepted Solution

by:
LordOfPorts earned 500 total points
ID: 22808025
No problem at all and sorry it did not work right away. Please try this version of stateChanged, I have tested it with fake data in IE and FF successfully:
function stateChanged()

{

    var respStringArray = new Array();

    

    if(xmlHttp.readyState==4 || xmlHttp.readyState == "complete") {

        var ActiveVar = 0;

        if (xmlHttp.status == 200) { 

	        

            var respString = xmlHttp.responseText;

            respStringArray = respString.split("||");

			 

	   var nItems = 7; // how many items compose a record

 

	   // Create the 2-D array

	   var MainArray = new Array();

			 

	   // Add new array to the 2 dimensional array for each record

	   for(var n = 0; n < respStringArray.length / nItems; n++) {

	       MainArray.push(new Array());

	   }

			 

	   var nIndex = 0;

			 

	   for(var i = 0; i < respStringArray.length; i++) {

         

	       MainArray[nIndex].push(respStringArray[i]);

				

	       // If we have reached 7 elements we increment the 2-D array's index

	       if((i + 1) % nItems == 0 && i != 0) {

	           nIndex++;

	       }

	   }

			

            PicList = "<SELECT size=13 style='width:200px; font:8pt verdana; font-weight:bold' name='selBACEStkDes' onChange='ShowBACEPic(frmBACEStk.selBACEStkDes.options.selectedIndex);'>";

            ActiveVar = 0;

            current = 0;

  

            

            for(var loop = 0; loop < MainArray.length; loop++) {

                PicList = PicList + "<option value=" + MainArray[loop][1] + ">" + MainArray[loop][5] + "</option>"; 

            }

            PicList = PicList + "</select>";

            

            document.getElementById("PicSpot").innerHTML = PicList;

	   } 

	   else {

		   //Handle error

	   } 

   } else {

           //alert(xmlHttp.status);

   }

}

Open in new window

0
 

Author Closing Comment

by:OldHatt45
ID: 31507610
LordOfPorts,
Sorry, I got pulled in about 20 different directions!  Just got back to this now.  I really appreciate the help!
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to count occurrences of each item in an array.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now