Solved

Populate input box in php page based on drop down selection

Posted on 2014-04-03
2
660 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
[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
2 Comments
 
LVL 110

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 34

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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
issue with DB import 1 37
if (is_singular not working 5 40
restriction of entering a a page 5 34
PHP Underscores vs. Directory separators 5 29
Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to count occurrences of each item in an array.

730 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