Link to home
Start Free TrialLog in
Avatar of mrh14852
mrh14852

asked on

XHTML Forms, Javascript, JSON, populate form fields question

I am still learning javascript and JSON and hoping someone can steer me in the right direction.

I have a simple HTML form.

<form>
<label>Customer ID</label><input type="text" name="id_num" id="id_num" />
<label>Customer Name</label><input type="text" name="customer_name" id="customer_name" /><label>Customer Location</label><input type="text" name="customer_location" id="customer_location" />
<input name="submit" type="submit" value="submit" />
</form>

I also have a PHP script that echos JSON in the following array.

{"idnum":"1234","customername":"ABC Corp","customerloc":"CA"}  

So what I would like to do is populate my formfields based off the first input (id_num)

When someone puts the number in the first field and then goes to the next field it sends the number to my PHP script and then returns the JSON array and fills in the rest of the fields from the array.  After which they can submit the form.

Would really appreciate help getting started in writing the JS for this.

Thanks
ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Work with this simple php page (myphpjson.php) :


<?PHP
	header('Content-type: application/json');
	if($_GET["id_num"] == "1234") {
		echo '{"idnum":"1234","customername":"ABC Corp","customerloc":"CA"}';
	}
	else {
		echo '{"idnum":"","customername":"NOT FOUND","customerloc":"NOT FOUND"}';
	}
?>

Open in new window

The same with simple javascript (no jQuery) :

A good link about ajax : http://www.w3schools.com/ajax/ajax_xmlhttprequest_create.asp
And $.getJSON : http://api.jquery.com/jQuery.getJSON/
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script language="javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script language="javascript">
	function eve(o) {
		if(window.XMLHttpRequest) xmlhttp=new XMLHttpRequest(); else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4 && xmlhttp.status==200) {
				var json = eval( "(" + xmlhttp.responseText + ")" );
				document.getElementById("customer_name").value = json.customername;
				document.getElementById("customer_location").value = json.customerloc;
			}
		}
		xmlhttp.open("GET","myphpjson.php?id_num=" + document.getElementById("id_num").value, true);
		xmlhttp.send();
	}
</script>
</head>
<body>
<form>
    <label>Customer ID</label><input type="text" name="id_num" id="id_num" onblur="eve(this)" onchange="eve(this)" />
    <label>Customer Name</label><input type="text" name="customer_name" id="customer_name" /><label>Customer Location</label><input type="text" name="customer_location" id="customer_location" />
    <input name="submit" type="submit" value="submit" />
</form>
</body>
</html>

Open in new window

Avatar of mrh14852
mrh14852

ASKER

I am useing the jQuery method since I use it in other places however it's not working for me.

I looked at it though firefox/firebug console and I can see it makes the request to the json.php and it echos back the encoded array, but it's not populating the fields.  There are no errors posted....
Try with my php function too. I test it and it work.
Post your php code too.

You need to be sure to return JSON object not a JSON string else you get an error on client side.
To prevent that I used : header('Content-type: application/json');
php code

<?php
header('Content-type: application/json');
$idnum = $_GET['id_num'];
$idq = simplexml_load_file('http://myurl?detail=' .$idnum);

$string = $idq->asXML();
$arr = "";

preg_match("/&gt;(.*)&lt;\/CUSTOMERNAME/",$string,$matches);
if (!isset($matches[1])) 
{
  $arr['customername'] =  "";
} 
else 
{
  $arr['customername'] =  $matches[1];
}

preg_match("/&gt;(.*)&lt;\/CUSTOMERLOC/",$string,$matches);
if (!isset($matches[1])) 
{
  $arr['customerloc'] =  "";
} 
else 
{
  $arr['customerloc'] =  $matches[1];
}

return json_encode($array)

?>

Open in new window


And the output

{"idnum":"1234","customername":"ABC Corp","customerloc":"CA"}


This is what I see in firebug console.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
{"idnum":"1234","customername":"ABC Corp","customerloc":"CA"}
</body>
</html>

Open in new window



Sorry typo.

return json_encode($array)

is actually

return json_encode($arr)
You MUST remove the HTML
You only need to return the JSON object, only this :




{"idnum":"1234","customername":"ABC Corp","customerloc":"CA"}

Open in new window

My goodness.  I moved a file outside my IDE so I was updating the wrong file...idiot.

This works perfectly now.

One question...is there a way to sort of freeze the form or show some indication that its processing something.  It can take ~5 seconds to return data.
Additionally it seems that this could be a much better way to build other parts of a form, such as select drop downs.  I currently do this using a musql query to get the options and I use a while loop in the form to create the select options.

For this I guess my question would be for a form that you can update and re-submit you would need to display the current value, but also offer the drop down options....
>One question...is there a way to sort of freeze the form or show some indication that its processing something.

use a picture like this one : http://i277.photobucket.com/albums/kk65/Xibit_Subho/Subho/loading-1.gif
show it just before the call, hide it at the end of the success function
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script language="javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script language="javascript">
	$(document).ready(function() {
		$("#id_num").bind("change blur", function() {
			$("#loading").show();
			$.getJSON("myphpjson.php", {"id_num":$(this).val()}, function(data) {
				$("#customer_name").val(data.customername);
				$("#customer_location").val(data.customerloc);
				$("#loading").hide();
			});
		});
	});
</script>
</head>
<body>
<form>
    <label>Customer ID</label><input type="text" name="id_num" id="id_num" />
    <label>Customer Name</label><input type="text" name="customer_name" id="customer_name" /><label>Customer Location</label><input type="text" name="customer_location" id="customer_location" />
    <input name="submit" type="submit" value="submit" />
    <div id="loading" style="position:absolute;left:150px;top:150px"><img src="http://i277.photobucket.com/albums/kk65/Xibit_Subho/Subho/loading-1.gif" /></div>
</form>
</body>
</html>

Open in new window

>For this I guess my question would be for a form that you can update and re-submit you would need to display the current value, but also offer the drop down options....

It's bandwidth and server ressources saving to send data from server to web browser and build the object on the client side
Hey!? Thanks for the points! :))
Much appreciated for you help!