User Name Password Register
DaniWeb IT Discussion Community
All
What is DaniWeb IT Discussion Community?
You're currently browsing the JavaScript / DHTML / AJAX section within the Web Development category of DaniWeb, a massive community of 402,733 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 2,459 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our JavaScript / DHTML / AJAX advertiser: Lunarpages Web Hosting

AJAX generated <select> and FIREFOX

Join Date: Sep 2007
Location: Nevada, U.S.A.
Posts: 38
Reputation: HazardTW is an unknown quantity at this point 
Rep Power: 1
Solved Threads: 1
HazardTW HazardTW is offline Offline
Light Poster

Re: AJAX generated <select> and FIREFOX

  #5  
Sep 13th, 2007
Try this out...

You need a table in your DB named email with at least one column named email.
The data in each row should be in this format: name,email Example: Bob,bob@bob.com

I did test this and verified that it works as long as:
a) you can connect to your database
b) you have a table named email with a column name email
c) you can run PHP on your host server I assume

The php file outputs an XML document, you can just open the PHP directly in the browser and see it's output, might help you get an idea of what it's doing.

The PHP filetest.ajax.php)
<?php
header('Content-Type: text/xml');
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
echo "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\r";
echo "<response>\r\r";
//=============================================================================//
$dbconn = NULL;
function dbconnect($verbose=true) {
	global $dbconn;
	include('<usernames and pws come in here>');
	if (!$dbconn = @mysql_connect("localhost",$name,$pw)){return false;}
	if($verbose){echo "\r<!-- opening mysql connection -->\r";}
	return true;}
//=============================================================================//

// this function creates a string delimited by "^": "Bob Smith,bob@abc.com^Sally White,sally@xyz.com^John Doe,jdoe@msn.com"

// this function actually serves a bunch of uses, not just the email, I stripped out everything else
// there are some queries where I want unique results only, others I want all results, hence the 'allowDuplicates' toggle


function db_fetch_str($table,$needle,$haystack_1=1,$match_1=1,$allowDuplicates=false,$haystack_2=1,$match_2=1) {
	$str = "";
	$sql = "SELECT $needle FROM $table WHERE $haystack_1 = '$match_1' AND $haystack_2 = '$match_2'";
	$result = @mysql_query($sql);
	if ( !$result || !mysql_affected_rows())
	{
		$str .= "-- NONE --";
	}
	else
	{
		$delimiter = "";
		$dups = array();
		while ( $row = @mysql_fetch_array($result))
		{
			if ( $allowDuplicates || !in_array($row[$needle],$dups) )
			{
				if (!$allowDuplicates){array_push($dups,$row[$needle]);}
				$str .= $delimiter.$row[$needle];
				$delimiter = "^";
			}
		}
	}
	return($str);
}
// ------------------------------------------------------------- //
$connection_open = dbconnect(false) or die("	<status>FAILED DBCONN</status>\r</response>");
@mysql_select_db("<name of your database>") or die("	<status>FAILED DBSELECT</status>\r</response>");

echo "<status>SUCCESS</status>\r";

echo "<email>".db_fetch_str('email','email',1,1,true)."</email>\r";

echo "\r</response>";
if ($connection_open){@mysql_close($dbconn);}?>
And the HTML with javascript in it:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<script type="text/javascript">
<!--
function HttpClient() { } // HTTPCLIENT CLASS
HttpClient.prototype = {
	// type GET,POST passed to open
	requestType:'GET',
	// when set to true, async calls are made
	isAsync:true,
	// where an XMLHttpRequest instance is stored
	xmlhttp:false,
	// what is called when a successful async call is made
	callback:false,
	// what is called when send is called on XMLHttpRequest
	// set your own function to onSend to have a custom loading
	// effect
	onSend:function()
	{
		//document.getElementById('HttpClientStatus').style.display = 'block';
	},
	
	// what is called when readyState 4 is reached, this is
	// called before your callback
	onload:function()
	{
		//document.getElementById('HttpClientStatus').style.display = 'none';
	},
	
	// what is called when an http error happens
	onError:function(error)
	{
		alert(error);
	},
	
	// method to initialize an xmlhttpclient
	init:function()
	{
		try
		{
			// Mozilla / Safari
			this.xmlhttp = new XMLHttpRequest();
		}
		catch (e)
		{
			// IE
			var XMLHTTP_IDS = new Array('MSXML2.XMLHTTP.5.0',
				 'MSXML2.XMLHTTP.4.0',
				 'MSXML2.XMLHTTP.3.0',
				 'MSXML2.XMLHTTP',
				 'Microsoft.XMLHTTP');
			var success = false;
			for (var i=0;i < XMLHTTP_IDS.length && !success; i++)
			{
				try
				{
					this.xmlhttp = new ActiveXObject
					(XMLHTTP_IDS[i]);
					success = true;
				}
				catch (e)
				{}
			}
			if (!success)
			{
				this.onError('Unable to create XMLHttpRequest.');
			}
		}
	},
	// method to make a page request
	// @param string url  The page to make the request to
	// @param string payload  What you're sending if this is a POST
	//                        request
	makeRequest: function(url,payload)
	{
		if (!this.xmlhttp)
		{
			this.init();
		}
		this.xmlhttp.open(this.requestType,url,this.isAsync);
		
		// set onreadystatechange here since it will be reset after a
		//completed call in Mozilla
		var self = this;
		this.xmlhttp.onreadystatechange = function()
		{
			self._readyStateChangeCallback();
		}
		if (this.requestType == "POST")
		{
			this.xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			this.xmlhttp.setRequestHeader("Content-length", payload.length);
			this.xmlhttp.setRequestHeader("Connection", "close");
		}
		
		this.xmlhttp.send(payload);
		
		if (!this.isAsync)
		{
			return this.xmlhttp.responseXML;
		}
	},
	
	// internal method used to handle ready state changes
	_readyStateChangeCallback:function()
	{
		switch(this.xmlhttp.readyState)
		{
			case 2:
				this.onSend();
				break;
			case 4:
				this.onload();
				if (this.xmlhttp.status == 200)
				{
					this.callback(this.xmlhttp.responseXML);
				}
				else
				{
					this.onError('HTTP Error Making Request: ' + '[' + this.xmlhttp.status + ']' + ' ' + this.xmlhttp.statusText);
				}
				break;
		}
	}
}

var client = new HttpClient();// create an instance of the object
client.isAsync = false;// I personally set this to false to hold execution until the request is finished
var company_email = null;// declare the global
var http_status = null; // global I use to keep track of status
function get_global_email()
{
	client.requestType = "GET";
	// function to handle completed calls
	client.callback = function(XMLresult)
	{
		if (XMLresult.getElementsByTagName("status"))// did XML page create a 'status' element?
		{
			http_status = XMLresult.getElementsByTagName("status")[0].childNodes[0].nodeValue;
		}else{// if no 'status' element was returned, set global http_status to FAILED NO STATUS
			http_status = "FAILED NO STATUS";
			return;
		}
		if (http_status == "SUCCESS") {// if we got a SUCCESS in 'status' element, put row data in global variable
			// use of split("^") gives us an array of "name,email" pairs.
			company_email = XMLresult.getElementsByTagName("email")[0].childNodes[0].nodeValue.split("^");
		}
	}
	client.makeRequest('test.ajax.php?sid='+Math.random(),null);
	return;
}

function build_contact_list()
{
        http_status=null; // make sure it's clear beforehand 
	get_global_email(); // call our ajax function to retrieve contact info from database
	
        // handle incomplete requests
        if (http_status != "SUCCESS"){alert("something went wrong:"+http_status);return;}
	
        var cm = document.getElementById("contact_menu"); // get the select element
	
	// remove all options from this select element
	while ( cm.options.length )
	{
		cm.remove(cm.options[0]);
	}
	
	for ( var i = 0; i < company_email.length; i++ )
	{
		var newOpt=document.createElement('option');
		// now seperate the name from the email address
		var tmp = company_email[i].split(",");
		newOpt.text=tmp[0];// set the persons name as the text of the option element
		try
		{
			cm.add(newOpt,null); // standards compliant
		}
		catch(ex)
		{
			cm.add(newOpt); // IE only
		}
		cm.options[i].value = tmp[1];// set the email address as the value of the option element
		cm.selectedIndex = 0;
	}
}


-->
</script>
</head>

<body>
	<div>
		<select id="contact_menu">
			<option></option><!-- dummy option so you don't throw validation errors -->
		</select>
		<br>
		<button type="button" onClick="build_contact_list()">Build The Menu</button>
	</div>
</body>
</html>

My disclaimer is that I have never been trained in programming, only self taught, so any pro's out there that see anything they wish to comment on, I would be happy to receive the critique.(with the exception of the HTML portion of the doc above that I just threw together for this example)

For simplicity I have been retrieving all rows I get from my database this way, in a "^" delimited string that I split once I have retrieved it.

Hope this helps you with your menu building.

This method has worked great so far, my goal for the app I am working on is to never have to reload the page and the menus are updated every time the layer is they are on is made visible.
Reply With Quote  
All times are GMT -4. The time now is 7:17 am.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC