Solved

Populate input box in php page based on drop down selection

Posted on 2014-04-03
2
626 Views
Last Modified: 2014-04-07
Hi all.

I'm trying to populate an input box ("modelnumber") based on what is selected in the drop down box ("model name") but with my code below, it is not populating anything in the modelnumber input box. What am I doing wrong? Below is the code for DataEntry.php and loadmodelnumber_dataentry.php.  Thank you in advance!

DataEntry.php:

<?php 

    // First we execute our common code to connection to the database and start the session 
    require("common.php");

if(!$_SESSION['user']){
 header("Location: index.php");
 exit();
}

        
      $smt1 = $db1->prepare('SELECT FieldSuperAssignment.BuilderCommunityID,Builder, Community FROM BuilderCommunity INNER JOIN FieldSuperAssignment ON BuilderCommunity.BuilderCommunityID = FieldSuperAssignment.BuilderCommunityID   WHERE UserID = :user_id AND BuilderCommunity.Status = "Active" ORDER BY Builder, Community');

      $smt1->execute(array(':user_id' => $_SESSION['user']['userid']));
      $data1 = $smt1->fetchAll();
      
      $smt = $db-> prepare('SELECT jobtypeid, jobtypedescription FROM JobType ORDER BY jobtypeid');
      $smt->execute();
      $data = $smt->fetchAll();



$_SESSION['action_token'] = generate_secure_token(); 
?> 

<!DOCTYPE html>
<head>
  <title>MyPage</title>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <link rel="stylesheet" href="style.css" type="text/css" />
  <link href="iphone-icon1.png" rel="apple-touch-icon">
  <script>
function showModel(str)
{
if (str=="")
{
document.getElementById("modelname").innerHTML="";
return;
} if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("modelname").innerHTML=xmlhttp.responseText;
}
}

xmlhttp.open("GET","loadmodelname_dataentry.php?q="+str,true);
xmlhttp.send();
}

function showModelNumber(str1)
{
if (str1=="")
{
document.getElementById("modelnumber").innerHTML="";
return;
} if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("modelnumber").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","loadmodelnumber_dataentry.php?q1="+str1,true);
xmlhttp.send();
}
</script>

</head>
<body>
<?php echo "User: " . $_SESSION['user']['Name'] ?>
<div class="wrapper">
    <div id="logo"></div>
    
   <form class="form4" action="ProcessFieldSuperDataEntry.php" method="post">
<div class="formtitle4">My Data Entry</div>

	<div class="input2">
          <div class="inputtext">Builder/Community:</div>           
                 	<div class="inputcontent" ><select name="BuilderCommunity" id="BuilderCommunity" onchange="showModel(this.value)" style="width: 250px"><option selected="selected"></option>    
                
                <?php foreach($data1 as $row) { printf("<option value='%s'>%s --- %s </option>", html_escape($row['BuilderCommunityID']), html_escape($row['Builder']), html_escape($row['Community'])); }?>
                 	</select></div>

 <div class="inputtext">Model Name:</div> 
                    <div class="inputcontent" ><select name="modelname" id="modelname" onchange="showModelNumber(this.value)" style="width: 250px"><option selected="selected"></option>
                            
                     </select></div>
                <br>
                <br>
                <br> 
                <div class="inputtext">Model Number:</div>
               
	            <div class="inputcontent"><input name="modelnumber" id="modelnumber" input type="text"/>   
	            
               </div>
 </div>  
            
            <div class="input2"> 
            	<div class="inputtext">Type:</div>           
                 	<div class="inputcontent" ><select name="type" id="type" style="width: 20em;"><option selected="selected"> </option>    
                     <?php foreach($data as $row) { printf("<option value='%s'>%s</option>", html_escape($row['jobtypeid']), html_escape($row['jobtypedescription']) ); }?>

				 		</select>
				 	</div>
			     
  
            </div>        
<div class="buttons" align = center>

				<input class="button1"  type="submit" value="Save" onclick="return checkFields()" />
				<input class="button1"  type="submit" formaction="Menu.php" value="Menu" /> 

		
			</div>


</form>
</body>
</html>

Open in new window


loadmodelnumber_dataentry.php:

<?php
    // First we execute our common code to connection to the database and start the session 
    require("common.php");
    
    if(!$_SESSION['user']){
        header("Location: index.php"); 
        exit();
        }
$smt1 = $db1->prepare('SELECT Modelid,ModelNumber FROM Models WHERE Modelid = :q1 ');

$smt1->execute(array(':q1' => $_GET["q1"]));
$data1 = $smt1->fetchAll();


foreach($data1 as $row){ echo '<input type="text" name="modelnumber" id="modelnumber" value="' . html_escape($row['ModelNumber']) . '">'; }

Open in new window

0
Comment
Question by:Sim1980
2 Comments
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 250 total points
ID: 39974824
You might want to think about using jQuery to do this.  Writing your own JavaScript is kind of 1999.  A jQuery "Hello World" example is available in this article.
http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Jquery/A_10712-The-Hello-World-Exercise-with-jQuery-and-PHP.html
0
 
LVL 33

Assisted Solution

by:Slick812
Slick812 earned 250 total points
ID: 39980402
greetings Sim1980, , You have the beginnings of an AJAX exchange update here, BUT, in looking at your code work, you do NOT understand the processes of the AJAX exchange. You code (PHP) almost as if you are doing a <form> submit Without AJAX, especially with these lines -
if(!$_SESSION['user']){
  header("Location: index.php");
  exit();
  }

The above code is VERY INCORRECT for an AJAX return! ! You SHOULD NEVER send back a <html> doctype web page to the browser in an AJAX exchange (as index.php).

however your Real Big Code Mistake is in the Javascript line-
document.getElementById("modelnumber").innerHTML=xmlhttp.responseText;


Because the element for the ID "modelnumber" is a text Input you have as -
<input name="modelnumber" id="modelnumber" input type="text"/>

And text inputs DO NOT HAVE ANY  innerHTML, and besides this error, , you do another code error , , because set a series of text inputs in the PHP with -
echo '<input type="text" name="modelnumber" id="modelnumber" value="' . html_escape($row['ModelNumber']) . '">';

which is ALL WRONG for this kind of AJAX exchange! You can not pour several text inputs into another text input! !

But I am not sure how to help you with this? ? your code in Javascript needs to be corrected and improved if not replaced, and the PHP code needs to be corrected and improved, if not replaced. I maybe can help with some code, but AJAX in native javascript or some JS framework like MoTools or Jquery, IS NOT EASY TO UNDERSTAND the processes needed for success, unless you do the most basic Copy and Paste code work.
Can you tell us some more about the way you need this to go, I guess that you need the single input -
<input name="modelnumber" id="modelnumber" input type="text"/>

to be replaced by the AJAX send back from the showModelNumber( ) function? if this is so then change the html line (add the ID to the <div>) -
<div id="mndiv" class="inputcontent"><input name="modelnumber" id="modelnumber" input type="text"/>

and change this JS line -
document.getElementById("modelnumber").innerHTML=xmlhttp.responseText;


and correct it to (mndiv as the ID of the DIV) -
document.getElementById("mndiv").innerHTML=xmlhttp.responseText;

Please ask questions if you need more information or corrections.
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to count occurrences of each item in an array.

758 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

16 Experts available now in Live!

Get 1:1 Help Now