?
Solved

XHTML Forms, Javascript, JSON, populate form fields question

Posted on 2010-11-17
14
Medium Priority
?
1,257 Views
Last Modified: 2013-11-08
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
0
Comment
Question by:mrh14852
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 6
14 Comments
 
LVL 82

Accepted Solution

by:
leakim971 earned 2000 total points
ID: 34157680
For example a simple example with jQuery and the jquery getJSON function (ajax call) :


<!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() {
			$.getJSON("myphpjson.php", {"id_num":$(this).val()}, function(data) {
				$("#customer_name").val(data.customername);
				$("#customer_location").val(data.customerloc);
			});
		});
	});
</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" />
</form>
</body>
</html>

Open in new window

0
 
LVL 82

Expert Comment

by:leakim971
ID: 34157688
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

0
 
LVL 82

Expert Comment

by:leakim971
ID: 34157782
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

0
Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

 
LVL 8

Author Comment

by:mrh14852
ID: 34158477
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....
0
 
LVL 82

Expert Comment

by:leakim971
ID: 34158583
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');
0
 
LVL 8

Author Comment

by:mrh14852
ID: 34158816
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



0
 
LVL 8

Author Comment

by:mrh14852
ID: 34158827
Sorry typo.

return json_encode($array)

is actually

return json_encode($arr)
0
 
LVL 82

Expert Comment

by:leakim971
ID: 34158851
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

0
 
LVL 8

Author Comment

by:mrh14852
ID: 34159088
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.
0
 
LVL 8

Author Comment

by:mrh14852
ID: 34159512
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....
0
 
LVL 82

Expert Comment

by:leakim971
ID: 34159981
>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

0
 
LVL 82

Expert Comment

by:leakim971
ID: 34159993
>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
0
 
LVL 82

Expert Comment

by:leakim971
ID: 34160025
Hey!? Thanks for the points! :))
0
 
LVL 8

Author Comment

by:mrh14852
ID: 34160101
Much appreciated for you help!
0

Featured Post

Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article shows how to create and access 2-dimensional arrays in JavaScript.  It includes a tutorial in case you are just trying to "get your head wrapped around" the concept and we'll also look at some useful tips for more advanced programmers. …
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.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

752 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