Populating Data Without Refreshing the Page Using AJAX
Posted at Apr 4, 2008 1:10:49 PM by Enid Glasgow | Share
I recently encountered a situation with a website we were working on and, yes, I know that there are hundreds of lines of code out there that do exactly what I am about to discuss, but to me, this is probably the simplest solution and could be easily configured to do what you need it to do.
What was needed you ask? Well, a simple thing really. The client wanted their request form to be a little intuitive. If their users selected an option from the dropdown that was the U.S, then show the U.S. States; if not, then show a textbox for the user to input their area, city, whatever. Granted there is no Database associated with this site, nor did they want one created. So I wrote this little piece to make it do just that.
var handleSuccess = function(transport)
if(transport.responseText !== undefined)
document.getElementById('WHEREYOUWANTTHEINFOTOSHOW').innerHTML = transport.responseText;
var handleFailure = function()
document.getElementById('WHEREYOUWANTTHEINFOTOSHOW').innerHTML = "";
// IF YOU WANT, YOU CAN WRITE SOME HTML BETWEEN THE QUOTES TO SAY THAT THIS FAILED.
var request_country = sel.options[sel.selectedIndex].value;
var sUrl = "getSubInfo.php?sub=" + request_country;
This code actually received the value of the selected option and sends that value to a php page runs through a function and the information gets returned; which in this case is either the US State drop down or a textbox.
3. Now the php page we were just talking about. As you can see I removed much of it for protection, but its pretty straight forward. It grabs the value that was sent, checks if the value is equal to one (which will show the states) and, if not, will show the textbox. Simple? Yep. You can copy this and save it as getSubInfo.php
**** Note that I removed security features and such from this code. You should add some of your own so that people are not injecting into your code; although this is really nothing sensitive.
$sub = $_GET['sub'];
if ($sub == "USA")
print("State / Area ");
4. Now for the HTML of it. This is pretty straight forward. Write out your select statement as usual, but add an onChange call to handle the dynamic content retrieval. Add this to your page.
So all in all, this was a pretty simple thing to accomplish. Its nothing major; just thought I would share it with you all.