Solved

XHTML Forms, Javascript, JSON, populate form fields question

Posted on 2010-11-17
14
1,239 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
  • 8
  • 6
14 Comments
 
LVL 82

Accepted Solution

by:
leakim971 earned 500 total points
Comment Utility
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
Comment Utility
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
Comment Utility
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
 
LVL 8

Author Comment

by:mrh14852
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Sorry typo.

return json_encode($array)

is actually

return json_encode($arr)
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 82

Expert Comment

by:leakim971
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
>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
Comment Utility
>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
Comment Utility
Hey!? Thanks for the points! :))
0
 
LVL 8

Author Comment

by:mrh14852
Comment Utility
Much appreciated for you help!
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

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. …
The task A number given should be formatted for easy reading by separating digits into triads. Format must be made inline via JavaScript, i.e., frameworks / functions are not welcome. So let’s take a number like this “12345678.91¿ and format i…
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…

728 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

9 Experts available now in Live!

Get 1:1 Help Now