Apr 02

Say we want to auto fill the rest of the fields when some one enters the member id,

<form>
	Member id:<input id="memberid" /><br />
	First name:<input id="firstname" /><br />
	Last name:<input id="lastname" /><br />
	Phone:<input id="phone" /><br />
	Email:<input id="email" /><br />
	<input type="submit" />
</form>

Now we make a php file to simply return the memeber info from for a POSTed id.
The use of JASON here will let us do a neat trick when populating the fields using Javascript.
If the memebrs not found, setting the header to ’500′ will return fail for the jason request.

//load_member.php
$id = mysql_escape_string($_POST['id']);
$array = mysql_fetch_assoc(mysql_query("SELECT firstname, lastname, phone, email FROM members WHERE id = '$id' "));
if(is_array($array))
	echo json_encode($array);
else
	header('HTTP/1.1 500 Internal Server Error');

Now, when a user moves the curser out of the memeber id input box, we will call the php file above though a normal javascript POST request.

$('memberid').addEvent('blur',function()
{	new Request.JSON(
	{	url: "load_member.php",
		onFailure:function()
		{	alert("Sorry, we couldn't find the id.");
		},
		onSuccess: function(member)
		{	for (var member_details in member)
			{	$(member_details).set('value',member[member_details]);
			}
		}
	}).post({'id': this.get('value')});
});

If we named the form id’s the same as table fields or used

 SELECT field_name AS html_id_name FROM table

then we can use the ‘for loop’ to populate the fields.