Jump to content

Populating multiple text fields with MySQL data


codechimp

Recommended Posts

This is a really newbie question, but I have everything working but the last part - where I actually convert the XML result from the php page that returned the database responses

 

I'm trying to create a series of text fields that, once you enter the key (zip code) in the first, will return data and dynamically fill in a series of related text fields. My main problem is that I don't really know what to do with the data that I formatted to look like:

 

<results>

<station>LAX</station>

<zone>X</zone>

<city>Orange</city>

<state>CA</state>

</results>

 

I'm going for baby steps right now and am just trying to dump the (stripped) results into the "station" field, but when I use "httpObject.responseText;", it dumps everything (tags and all) into the field, and when I use "httpObject.responseXML;" it returns "[object XMLDocument]".

 

I know I'm probably supposed to parse the XMLDocument container a bit more, but after a couple hours of google searches, I hoped somebody else could help me out with this.

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="en">
  <head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>ZIP Populate</title>
<style type="text/css" media="screen">
    <!--
      BODY { margin: 10px; padding: 0; font: 1em "Trebuchet MS", verdana, arial, sans-serif; }
      BODY { font-size: 100%; }
      H1 { margin-bottom: 2px; font-family: Garamond, "Times New Roman", Times, Serif;}
      DIV.selHolder { float: left; border: 3px solid #ccc; margin: 10px; padding: 5px;}
      TEXTAREA { width: 80%;}
      FIELDSET { border: 1px solid #ccc; padding: 1em; margin: 0; }
      LEGEND { color: #ccc; font-size: 120%; }
      INPUT, TEXTAREA { font-family: Arial, verdana; padding: 3px; border: 1px solid #999; }
      LABEL { display: block; margin-top: 10px; } 
      IMG { margin: 5px; }
      SELECT { margin: 10px; width: 200px; }
-->
</style>

<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
<!--
// Get the HTTP Object
function getHTTPObject(){
   if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
   else if (window.XMLHttpRequest) return new XMLHttpRequest();
   else {
      alert("Your browser does not support AJAX.");
      return null;
   }

}

// Change the value of the outputText field
function setOutput(){
    if(httpObject.readyState == 4){
        document.getElementById('station').value = httpObject.responseXML;
    }

}

// Implement business logic
function lookItUp(){
        httpObject = getHTTPObject();
    if (httpObject != null) {
        httpObject.open("GET", "checkzip.php?zip_from="
                        +document.getElementById('zip_from').value, true);
        httpObject.send(null);
         httpObject.onreadystatechange = setOutput;
    }

}

var httpObject = null;

//-->
</script>

  </head>
  
  <body>
   <form>
   <table>
     <tbody><tr>
       <td>Zip Code:<br><input size="7" onChange="lookItUp();" name="zip_from" id="zip_from" type="text"></td>
       <td>Station:<br><input size="5" name="station" id="station" disabled="disabled" type="text"></td>
       <td>Zone:<br><input size="3" name="zone" id="zone" disabled="disabled" type="text"></td>
       <td>City:<br><input name="city" id="city" disabled="disabled" type="text"></td>
       <td>State:<br><input size="4" name="state" id="state" disabled="disabled" type="text"></td>
     </tr>
   </tbody></table>
  </form>
  </body>
  
  </html>

 

and here's the php form

 

<?php 

  header('Content-type: text/xml'); 
  $zip=$_REQUEST['zip_from'];
  
  [database login info]
  
  $query = "SELECT * FROM database.zip_code WHERE (zip=$zip)";
  $result = mysql_query($query);
  if(!result) {
echo "no results";
exit('<p>Error performing query: ' . mysql_error() . '</p>');
  }
  
  mysql_close();
  
  while ($row = mysql_fetch_array($result)) {
$station = $row['station'];
$zone = $row['zone'];
$city = $row['city'];
$state = $row['state'];
  }

  $returnXML = 
    '<response>
 <station>' . $station . '</station>
 <zone>' . $zone . '</zone>
 <city>' . $city. '</city>
 <state>' . $state . '</state>
 </response>';

  echo $returnXML;
  
?>

 

Is there a quick and dirty way to parse the XML data by tag? I played around with getElementsByTagName with no success, but I could have done it wrong.

 

Essentially, I have everything working except for the last step, where I need to interpret the incoming data and dump it into the correct text fields.

 

Thanks in advance for any advice you can give!

Link to comment
Share on other sites

The method .responseXML requires you to send a header to the browser telling the data is XML instead of text, which you didn't do. ALSO, that method ONLY works in Firefox. It doesn't work in IE 7 or lower. IE 8 will provide a way to use that method, but for now, I do not recommend you using .responseXML. Instead, use .responseText.

 

Regarding your problem:

document.getElementById('station').value = httpObject.responseXML;

 

If you change .responseXML to .responseText, it does work as you have written it to. That line will obviously dump everything into that input with the ID "station". So it does exactly as you written it. :)

Link to comment
Share on other sites

Ken, thanks for your response.

 

I was just working with the "station" field to keep things simple on my end; I know that doing the same to the rest of the fields will dump the data into them as well, but my main problem still stands - I have no idea how to parse out the data within the XML tags that my php script is returning.

 

Does this relate to the .responseXML problem that you were discussing, or am I missing a simple command switch that will just return the data within the XML?

 

I found some information on the internet regarding this sort of issue, but the format that I used evidently didn't work for me. This is how it was set up, and this didn't work at all for me.

 

function setOutput(){
    if(httpObject.readyState == 4) {

        xmlDoc=xmlHttp.responseXML; // Also tried .responseText
                 document.getElementById('station').innerHTML=
                 xmlDoc.getElementsByTagName('station')[0].childNodes[0].nodeValue;
                 document.getElementById('zone').innerHTML=
                 xmlDoc.getElementsByTagName('zone')[0].childNodes[0].nodeValue;
                 document.getElementByID('city').innerHTML=
                 xmlDoc.getElementsByTagName('city')[0].childNodes[0].nodeValue;
                 document.getElementByID('state').innerHTML=
                 xmlDoc.getElementsByTagName('state')[0].childNodes[0].nodeValue;

    }

}

 

Am I just being dense, or is there really no "simple" solution to filling in multiple fields?

 

If so, what is the convoluted way of going about it?

Link to comment
Share on other sites

Ok, I got it figured out.

 

function setOutput(){
    if(httpObject.readyState == 4){
	var response = httpObject.responseText.split('|');
      document.getElementById('station').value = response[0];
	document.getElementById('zone').value = response[1];
	document.getElementById('city').value = response[2];
	document.getElementById('state').value = response[3];
    }

}

 

Was my solution. I figured out how the .responseText.split(','); command works and it works marvelously on both IE and FF. Now I'm running into a problem implementing the same solution twice. I'm trying to populate the same types of fields twice, once with a "from" and once with a "to".

 

Everything seems to be working 100% on both lines, except the second request is pulling the original responseText as the first one. Is there a way to clear out the responseText and make the script start from scratch before the second query happens?

 

For the sake of brevity, this is currently what happens:

 

The first line populates with the correct data.

 

When the second line populates, it autofills with the same exact data as the first, despite calling a completely different file and being named completely different things, probably because it's drawing from the same response. How do I clear this response before I call the second query?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.