Display other data based on dropdown selection

OK, I have searched the internet and here and have not found what I need.

I am a noob to javascipt/java so need a LOT of help.

What I have is a form to update meeting places with certain data. The data for the meeting place is from a MySQL table and that table has the place, address, city, state, zip. So I need to have the address, city, state, zip changed based on the dropdown of the meeting place. My current code is below (and includes other things).


<?php
	session_start();

		include 'db_connect.php';
		
			
	if ($_SERVER['REQUEST_METHOD'] == 'POST')
  {
    $task = isset($_POST['task']) ? $_POST['task'] : false;
     if ($task == "Register") {
      $formValues = $_POST;
      $formErrors = array();
      if (!VerifyForm($formValues, $formErrors))
      DisplayForm($formValues, $formErrors);
      else     {
//        echo 'Processing form' ;
        ProcessForm($formValues);     }
      }
      else if ($task == 'ReturnToMainPage')
        header('Location: index.php');
  }
  else
  {

    DisplayForm(null, null);
}


function DisplayForm($values, $errors)
{ ?>
<!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>SACCC Meeting Information Change</title>
<link rel="stylesheet" type="text/css" href="view.css" media="all">
<script type="text/javascript" src="view.js"></script>
<script type="text/javascript" src="calendar.js"></script>
</head>
<body id="main_body" >

	<img id="top" src="top.png" alt="">
	<div id="form_container">
	
		<h1><a> Meeting Information Change</a></h1>
		<form id="form_754506" class="appnitro"  method="post" action="">
					<div class="form_description">
			<h2>Meeting Information Change</h2>
			<p>Use this form to change the Monthly Meeting information.</p>
		</div>						
		<ul >		
			</li>		<li id="li_4" >
			<label class="description" for="element_4">Meeting Place </label>
			<div>
				<input id="element_4" name="element_4" class="element text medium" type="text" maxlength="255" value=""/>
			</div>
			</li>		
			<li id="li_5" >
			<label class="description" for="element_5">Meeting Address </label>
			
			<div>
				<input id="element_5_1" name="element_5_1" class="element text large" value="" type="text">
				<label for="element_5_1">Street Address</label>
			</div>
		
			<div>
			<span style="float:left">
				<input id="element_5_3" name="element_5_3" class="element text medium" style="width:14em" value="" type="text">
				<label for="element_5_3">City</label>
			</span>
			<span style="float:left">
				<select id="element_5_4" name="element_5_4" class="element text medium" style="width:3.5em"  maxlength="2" value="" type="text">
				<label for="element_5_4">State</label>
				</select>
			</span>
			<span style="float:left">
				<input id="element_5_5" name="element_5_5" class="element text medium" style="width:6em" maxlength="5" value="" type="text">
				<label for="element_5_5">Zip Code</label>
				</span>
			</div>
		
			</li>		
			
				
			<li class="buttons">
				<input type="hidden" name="form_id" value="754506" />
				<input id="saveForm" method="post" class="button_text" type="submit" name="addNew" value="Add New" action="<?= $_SERVER['PHP_SELF'] ?>"/>
				<input id="saveForm" method="post" class="button_text" type="submit" name="submit" value="Submit" action="<?= $_SERVER['PHP_SELF'] ?>"/>
			</li>
		</ul>
		</form>	
		<?php }
		?>		
	</div>
	<img id="bottom" src="bottom.png" alt="">
	</body>
</html>


So, I assume I need some kind of javascript to be triggered when the dropdown place box changes. Right? And what is that code since I don’t know javascript.

Thanks
F

I think the best way to do this is to attach an onchange event handler to your select element, then have it fire off an AJAX request to your PHP script every time the user selects something.
The PHP script can then fetch whatever it needs from the database and return it to the JavaScript which can then insert it into the page.

OK, I think that approach would work but since my knowledge of this is, well, non-existent so far and I know this is asking a lot, but could you give me the code as to how it would work?

Thanks

Lol. Nice try.
I won’t just write the whole thing for you, but I don’t mind demonstrating how the principle works, so that you can apply it to your site.
This way, if you need to make any changes further down the line, you’ll be able to make them on your own.

Sound like a plan?

Ah, was worth a try. And, yes, please demo the principles so I can get some more knowledge. If I don’t understand, I will comment as such, OK?

Okay then. In light of this statement:

let’s use the jQuery library, as this will simplify the syntax of what we want to do considerably.

You include it in your page like this:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

This will pull in the most recent minified version of the 1.x branch of the library.

Then we need a select. I was about to say, let’s use yours, but there doesn’t appear to be one in the code you posted above.
What do you mean by “the dropdown of the meeting place”?

Let’s use a select anyway, we can change it if it isn’t correct:

<label for="meetingPlace">Meeting place: </label>
<select id="meetingPlace">
  <option>Please select</option>
  <option>Buckingham Palace</option>
  <option>The White House</option>
  <option>Mount Everest</option>
</select>

With that in place we need to hook into the select’s on change event.
We can do this in our JavaScript:

$("#meetingPlace").on("change", function(){
  // This code will fire every time the user selects something
})

All this does is select the element with an id of “#meetingPlace” and declare an anonymous function which should be run every time the user selects something different.

As a final step for this post, let’s have the JS output what the user selected to the page.

Create a div with an id of “results”:

<div id="results"></div>

Then within the onchange callback add the following code:

var selected = $(this).val();
$("#results").html("You selected: " + selected);

What this does is assign the value of the selected option element to a variable, then set the innerHTML of the results <div> accordingly.

Note: we haven’t actually specifed a value for the options tags, so jQuery defaults to the selected text instead.
Setting a value would be: <option value="Buck House">Buckingham Palace</option>
And this would cause our script to output “You selected: Buck House”.

Here’s the whole code.

<!DOCTYPE HTML>
<html>
  <head>
    <meta charset="utf-8">
    <title>Select - onchange example</title>
  </head>
  
  <body>
    <label for="meetingPlace">Meeting place: </label>
    <select id="meetingPlace">
      <option>Please select</option>
      <option>Buckingham Palace</option>
      <option>The White House</option>
      <option>Mount Everest</option>
    </select>
    <div id="results"></div>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script>
      $("#meetingPlace").on("change", function(){
        var selected = $(this).val();
        $("#results").html("You selected: " + selected);
      })
    </script>
  </body>
</html>

Have a look at that, try and understand what is going on, then let me know if you have any questions.
If you don’t, we’ll move on to contacting the server from within our JS as a second step.

OK,I think I understand. No matter what you select in the SELECT statement, the js will put the “results” in the div called “results”.

So, now on to the next step please. Am really awaiting how to the the DB info into these areas.

OK, well the next step involves firing off an AJAX request every time the user selects something in the dropdown.

We’ll start off by adding value attributes to the option tags:

<select id="meetingPlace">
  <option value="">Please select</option>
  <option value="buckingham-palace">Buckingham Palace</option>
  <option value="white-house">The White House</option>
  <option value="mount-everest">Mount Everest</option>
</select>

Then in the onchange callback change the code as follows:

$("#meetingPlace").on("change", function(){
  var selected = $(this).val();
  makeAjaxRequest(selected);
});

Now we have to define the makeAjaxRequest function, where we can use jQuery’s $.ajax() method to contact the server:

function makeAjaxRequest(opts){
  $.ajax({
    type: "POST",
    data: { opts: opts },
    url: "process_ajax.php",
    success: function(res) {
      // We'll put some code here in a minute
    }
  });
}

What this does is to POST any data it is passed to the file process_ajax.php.
The success callback is executed if the AJAX request is successful.
We’ll come to that in a minute.

Let’s hop into process_ajax.php.
All we’ll do here is output the contents of the $_POST array, but in reality, this is where your database queries and so would go, before returning the appropriate results:

<?php 
  // Database logic here

  echo '<pre>'; 
  print_r($_POST);
  echo '</pre>';
?>

Then in the success callback, we’ll insert the server’s response into the results div:

$("#results").html("<p>$_POST contained: " + res + "</p>");

And there you go, that’s all there is to it :slight_smile:

index.html:

<!DOCTYPE HTML>
<html>
  <head>
    <meta charset="utf-8">
    <title>Select - onchange AJAX example</title>
  </head>

  <body>
    <label for="meetingPlace">Meeting place: </label>
    <select id="meetingPlace">
      <option value="">Please select</option>
      <option value="buckingham-palace">Buckingham Palace</option>
      <option value="white-house">The White House</option>
      <option value="mount-everest">Mount Everest</option>
    </select>
    <div id="results"></div>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script>
      function makeAjaxRequest(opts){
        $.ajax({
          type: "POST",
          data: { opts: opts },
          url: "process_ajax.php",
          success: function(res) {
            $("#results").html("<p>$_POST contained: " + res + "</p>");
          }
        });
      }

      $("#meetingPlace").on("change", function(){
        var selected = $(this).val();
        makeAjaxRequest(selected);
      });
    </script>
  </body>
</html>

process_ajax.php:

<?php 
  // Database logic here

  echo '<pre>'; 
  print_r($_POST);
  echo '</pre>';
?>

OK, now I might be confused - but most say I am that by nature.

First, in my page, I fill the “<option>” areas from the same database that has the address, etc. So, how do I pass the “link” to the database to the “process_ajax.php” module?

Second, depending on your answer to the first question, what really is the best way to handle this?

Last, how do I use the information to post to my database?

Thanks

Hi there,

No probs :slight_smile:

I’m not sure I understand.
As far as the JS is concerned, it doesn’t matter where you fill the option tags from.
Main thing is that they exist in the DOM when the JS executes.

Again, I’m not sure I follow.
What you want to do, is have “process_ajax.php” extract whatever parameters it needs from the $_POST array, build a db query, execute it and then echo the (relevant parts of the) results back to your original page.
Then your success callback will receive this information and update the page accordingly.

To give you a concrete example:
When your meeting place dropdown changes, use AJAX to send the value of the dropdown to process_ajax.php
In process_ajax.php extract the value from the $_POST array into (for example) a variable named $place
Make a db query:

$stmt = $db->prepare("SELECT address, city, state, zip FROM table-nameWHERE place = :place;");
$stmt->bindParam(':place', $place);

Echo the results back to your original page, then from within the success callback, insert them into the page (as previously demonstrated).

Edit:

Or do you mean that you need dependent selects (i.e. the options in the ZIP select change depending on what you select in the meeting place select?

Oh, I must be really dense as I am getting more confused as this goes on. (:

Based on which “place” is selected (in the query), the appropriate address, city, state and zip need to be displayed in their own Input boxes. So, based on what examples you have given, I am not sure how the javascript will put the info in the right place - or where I would like it to be.

So, I guess either (1) I am really not “qualified” to use this :sick: and/or (2) I am not getting what you have tried to teach me. :eye:

Please let me know if I can continue with this endeavor.

And I really do appreciate your time and help - even if I might still need more (and really MORE) handholding so to speak.

Hi there,

Yeah, sure :slight_smile:
It might seem a bit frustrating that nothing is working right now, but we’ll get there in the end.

I think now it is important for me to understand what you are trying to do.
Let’s also try to use the same terminology, as we can then avoid confusion.

What I have understood:

You have a select menu on a webpage which you can use to select places:

<select>
  <option>Place 1</option>
  <option>Place 2</option>
</select>

Based on what the user selects in this select menu, you would like to display additional information about the place, namely address, city, state and zip.
This additional information is stored in a database.

In order to fetch this additional information every time the select menu changes, we are sending an AJAX request to a PHP script, passing it the value of the selected option in the select menu.

Based on what parameters it receives, the PHP script then builds and executes a database query.

The PHP script then returns the results of this database query to the JavaScript that initialised the AJAX request.

The JavaScript uses the information it received from the PHP script to update the page.

Did I get all of that right?
If not please let me know what I have misunderstood.

Hi there,
You have a select menu on a webpage which you can use to select places:

<select>
  <option>Place 1</option>
  <option>Place 2</option>
</select>

Based on what the user selects in this select menu, you would like to display additional information about the place, namely address, city, state and zip.
This additional information is stored in a database.

Yes, the info is selected using the place. Yes, the info is in a database. The “Place1”, “Place2”, etc. is from the same db queried in a different place to start all of this.

In order to fetch this additional information every time the select menu changes, we are sending an AJAX request to a PHP script, passing it the value of the selected option in the select menu.

Based on what parameters it receives, the PHP script then builds and executes a database query.

The PHP script then returns the results of this database query to the JavaScript that initialised the AJAX request.

So, in the PHP script, does the db need to be re-opened? I would like it to not be as that is somewhat inefficient, yes?

The JavaScript uses the information it received from the PHP script to update the page.

This part is where I need to be clear. The first page has an input box (html) that I want to place the information. So… need to see how that is going to work.

Did I get all of that right?
If not please let me know what I have misunderstood.

Looks like you have a good understanding of what I want/need for this project.

Thanks again

Hi there,

Yes and no (in that order).
You would render your initial page (which I’m assuming is a PHP script). In this initial page, you open a connection to a database, so that you can get the information necessary to output your place select menu.
On the same page, you then use JavaScript to attach the event handler to the select menu.

When the select menu changes, the event handler is executed and sends an AJAX request to a separate second page (which you have created solely for this purpose)
This second page opens a database connection, selects a record, based on the parameters it was passed, then returns these to your initial page.

The JavaScript code in your initial page receives the results from the PHP script and inserts them into the page.

This is not inefficient, as there is no page reload for your user (it’s asynchronous) and only the necessary part of the page is updated.

What do you mean by input box?
Do you mean a div container, or a text input element (<input type="text />) or a text area (<textarea></textarea>), or something else?
Either way, it won’t be difficult - you just need to select the element using JavaScript and set it’s content to whatever came back from the AJAX request.

How to proceed:
Let me know about the input box, then I’ll make you a small demo that queries a live database and inserts the results into the page.
Also, if you could give me three examples of meeting places, as well as their corresponding address, city, state, zip information, that’d be great.

HTH

What do you mean by input box?

Please check post #1 as that is my code for the form that I want the information to show.

How to proceed:
Let me know about the input box, then I’ll make you a small demo that queries a live database and inserts the results into the page.
Also, if you could give me three examples of meeting places, as well as their corresponding address, city, state, zip information, that’d be great.

Post #1 has that in it (the input boxes that is - they are id’d as “element_5_x” where x is an incrementing number).
Here is some data for the db.
Darcy’s Restaurant and Spirits
10502 E Sprague Ave
Spokane Valley, WA 99206

Shari’s of Spokane Valley
320 N Sullivan Rd
Veradale, WA 99037

Elmers Restaurant
290 W Appleway Ave
Coeur d’Alene, ID 83814

Thanks once more and I am starting to grasp this but still have a LONG way to go.
F

Hi there,

Now I’m confused :slight_smile:

We have been talking about a select menu the whle time from which you can select a meeting place.
However, in the code from post#1 Meeting place is a text input field.

Also, there are two text input fields for Street address (as far as I can see), whereas City state is a select element.
Zip code seems to be ok as a text input field.

In addition to that (and please don’t take this the wrong way) the markup is quite broken.
Running the following code through the W3 validator produces 19 errors and 3 warnings:

<!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>SACCC Meeting Information Change</title>
<link rel="stylesheet" type="text/css" href="view.css" media="all">
<script type="text/javascript" src="view.js"></script>
<script type="text/javascript" src="calendar.js"></script>
</head>
<body id="main_body" >

	<img id="top" src="top.png" alt="">
	<div id="form_container">
	
		<h1><a> Meeting Information Change</a></h1>
		<form id="form_754506" class="appnitro"  method="post" action="">
					<div class="form_description">
			<h2>Meeting Information Change</h2>
			<p>Use this form to change the Monthly Meeting information.</p>
		</div>						
		<ul >		
			</li>		<li id="li_4" >
			<label class="description" for="element_4">Meeting Place </label>
			<div>
				<input id="element_4" name="element_4" class="element text medium" type="text" maxlength="255" value=""/> 
			</div> 
			</li>		
			<li id="li_5" >
			<label class="description" for="element_5">Meeting Address </label>
			
			<div>
				<input id="element_5_1" name="element_5_1" class="element text large" value="" type="text">
				<label for="element_5_1">Street Address</label>
			</div>
		
			<div>
			<span style="float:left">
				<input id="element_5_3" name="element_5_3" class="element text medium" style="width:14em" value="" type="text">
				<label for="element_5_3">City</label>
			</span>
			<span style="float:left">
				<select id="element_5_4" name="element_5_4" class="element text medium" style="width:3.5em"  maxlength="2" value="" type="text">
				<label for="element_5_4">State</label>
				</select>
			</span>
			<span style="float:left">
				<input id="element_5_5" name="element_5_5" class="element text medium" style="width:6em" maxlength="5" value="" type="text">
				<label for="element_5_5">Zip Code</label>
				</span>
			</div>
		
			</li>		
			
				
			<li class="buttons">
				<input type="hidden" name="form_id" value="754506" />
				<input id="saveForm" method="post" class="button_text" type="submit" name="addNew" value="Add New" action=""/>
				<input id="saveForm" method="post" class="button_text" type="submit" name="submit" value="Submit" action=""/>
			</li>
		</ul>
		</form>	
	
	</div>
	<img id="bottom" src="bottom.png" alt="">
	</body>
</html>

We need to fix this and agree on the markup we are going to use before we can implement any JS.

OK, found out that what I posted in the first one is not good. I started with something from the internet form design site and, well, will change that later.

For now, how about this code to get started.

<?php
// Call the db connection routine
include 'db_connect.php';


  $db_selected = mysql_select_db($database, $link);
  if (!$db_selected) {
      die ('Can\\'t use ' . $database . ' : ' . mysql_error());
  }

  	mysql_select_db($database, $link);

    $myQuery = "SELECT * FROM Meeting_Places ";

	mysql_query($myQuery) or die('Error: ' . mysql_error());
	
	$result = mysql_query($myQuery, $link);

?>

<!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 charset="utf-8">
    <title>Select - onchange AJAX example</title>
  </head>

  <body>
    <label for="meetingPlace">Meeting place: </label>
    <select id="meetingPlace">
      <option value="">Please select</option>
	  <?php
		  $myQuery = "SELECT * FROM Meeting_Places ";

		mysql_query($myQuery) or die('Error: ' . mysql_error());
		
		$result = mysql_query($myQuery, $link);
		
		while ($info = mysql_fetch_assoc($result))
		{
			echo '<option>' . $info['MeetingPlace'] . '</option>';
		}
	  ?>

    </select>
		<div>
			<label for="element_5_1">Street Address</label>
			<input id="element_5_1" name="element_5_1" class="element text large" type="text">
		</div>
		<div>
		<span style="float:left">
			<label for="element_5_3">City</label>
			<input id="element_5_3" name="element_5_3" class="element text medium" style="width:14em" type="text">

		</span>
		<span style="float:left">
			<label for="element_5_4">State</label>
			<input id="element_5_4" name="element_5_4" class="element text medium" style="width:4em" type="text">
			</select>
		</span>
		<span style="float:left">
			<label for="element_5_5">Zip Code</label>		
			<input id="element_5_5" name="element_5_5" class="element text medium" style="width:6em" type="text">

			</span>
		</div>
  </body>
</html>

Hope this can help get us started

That’s much better. Thanks!

So I did this:

CREATE TABLE Meeting_Places(
  id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  MeetingPlace varchar(256),
  StreetAddress varchar(256),
  City varchar(256),
  State varchar(256),
  ZipCode smallint(6)
) DEFAULT CHARACTER SET utf8 ENGINE=InnoDB;

Then:

INSERT INTO meeting_places SET
MeetingPlace = "Darcy's Restaurant and Spirits",
StreetAddress = "10502 E Sprague Ave",
City = "Spokane Valley",
State = "WA",
ZipCode = "99206"

INSERT INTO meeting_places SET
MeetingPlace = "Shari's of Spokane Valley",
StreetAddress = "320 N Sullivan Rd",
City = "Veradale",
State = "WA",
ZipCode = "99037"

INSERT INTO meeting_places
SET MeetingPlace =  "Elmers Restaurant",
StreetAddress =  "290 W Appleway Ave",
City =  "Coeur d'Alene",
State =  "ID",
ZipCode =  "83814"

Now we should be on the same page.

Before we start, I want to point out that it is not good practice to use PHP’s old mysql API to connect to your databases.
You should really migrate to PDO.
See here for more info.

That out of the way, I tidied up your PHP a little. In the code you posted above you were selecting everything twice from the DB. There is no need.
This gives us what we need and outputs a list of meeting places accordingly.:

<?php
  # Connect
  mysql_connect('localhost', 'user', 'pass') or die('Could not connect: ' . mysql_error());
   
  # Choose a database
  mysql_select_db('sitepoint') or die('Could not select database');
   
  # Perform database query
  $query = "SELECT * from meeting_places";
  $result = mysql_query($query) or die('Query failed: ' . mysql_error());
?>

<!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 charset="utf-8">
    <title>Select - onchange AJAX example</title>
  </head>

  <body>
    <label for="meetingPlace">Meeting place: </label>
    <select id="meetingPlace">
      <option value="0">Please select</option>
      <?php
        while ($row = mysql_fetch_assoc($result)) {
            echo '<option value="' . $row['id'] . '">' . $row['MeetingPlace'] . '</option>';
        }
      ?>
    </select>

    <div>
      <label for="element_5_1">Street Address</label>
      <input id="element_5_1" name="element_5_1" class="element text large" type="text">
    </div>

    <div>
      <span class="floatLeft">
        <label for="element_5_3">City</label>
        <input id="element_5_3" name="element_5_3" class="element text medium" style="width:14em" type="text">
      </span>

      <span style="float:left">
        <label for="element_5_4">State</label>
        <input id="element_5_4" name="element_5_4" class="element text medium" style="width:4em" type="text">
        </select>
      </span>

      <span style="float:left">
        <label for="element_5_5">Zip Code</label>   
        <input id="element_5_5" name="element_5_5" class="element text medium" style="width:6em" type="text">
      </span>
    </div>
  </body>
</html>

Now we need to hook into the onchange event of the select element:

$("#meetingPlace").on("change", function(){
  var id = $(this).val();
  if (id === "0"){
    clearForm();
  } else {
    makeAjaxRequest(id);
  }
});

I have given all of the option elements a value. If the value is 0, the user has selected the default and we want to clear the remaining fields.
If the value is something else, we want to fire our AJAX request, passing the function the id of the place that has just been selected.

On to the AJAX:

function makeAjaxRequest(placeId){
  $.ajax({
    type: "POST",
    data: { placeId: placeId },
    dataType: "json", 
    url: "process_ajax.php",
    success: function(json) {
      insertResults(json);
    }
  });
}

Nothing new here, except that we are specifying dataType: “json”, as we want json back from the server.

And finally the success callback and the function to clear the fields:

function insertResults(json){
  $("#element_5_1").val(json["StreetAddress"]);
  $("#element_5_3").val(json["City"]);
  $("#element_5_4").val(json["State"]);
  $("#element_5_5").val(json["ZipCode"]);
}

function clearForm(){
  $("#element_5_1, #element_5_3, #element_5_4, #element_5_5").val("");
}

Nothing exciting here, either. Our server will return a json object representing the database record (as we will see in a minute) and we are setting those values as the values of the input elements.

In the clearForm() function, we are simply setting the values of all inputs to that of an empty string.

And on the serever:

<?php
  mysql_connect('localhost', 'user', 'pass') or die('Could not connect: ' . mysql_error());
  mysql_select_db('sitepoint') or die('Could not select database');
   
  $placeId = $_POST['placeId'];

  $query = "SELECT * from meeting_places";
  $result = mysql_query($query) or die('Query failed: ' . mysql_error());
  while ($row = mysql_fetch_assoc($result)) {
    if ($placeId == $row['id']){
      echo json_encode($row);
    }
  }
?>

We are retrieving the id of the place selected in the select element from $_POST, then querying the database for all records.
When we have the records, we are looping through them to find the one which matches the place id, encoding it as json and returning it to our script.

Note: you could do this more efficiently if you sanitise the input from the JS and use it directly. This is where PDO and prepared statements shine.

And finally here’s the complete code.

index.php:

<?php
  # Connect
  mysql_connect('localhost', 'user', 'pass') or die('Could not connect: ' . mysql_error());
   
  # Choose a database
  mysql_select_db('sitepoint') or die('Could not select database');
   
  # Perform database query
  $query = "SELECT * from meeting_places";
  $result = mysql_query($query) or die('Query failed: ' . mysql_error());
?>

<!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 charset="utf-8">
    <title>Select - onchange AJAX example</title>
  </head>

  <body>
    <label for="meetingPlace">Meeting place: </label>
    <select id="meetingPlace">
      <option value="0">Please select</option>
      <?php
        while ($row = mysql_fetch_assoc($result)) {
            echo '<option value="' . $row['id'] . '">' . $row['MeetingPlace'] . '</option>';
        }
      ?>
    </select>

    <div>
      <label for="element_5_1">Street Address</label>
      <input id="element_5_1" name="element_5_1" class="element text large" type="text">
    </div>

    <div>
      <span class="floatLeft">
        <label for="element_5_3">City</label>
        <input id="element_5_3" name="element_5_3" class="element text medium" style="width:14em" type="text">
      </span>

      <span style="float:left">
        <label for="element_5_4">State</label>
        <input id="element_5_4" name="element_5_4" class="element text medium" style="width:4em" type="text">
        </select>
      </span>

      <span style="float:left">
        <label for="element_5_5">Zip Code</label>   
        <input id="element_5_5" name="element_5_5" class="element text medium" style="width:6em" type="text">
      </span>
    </div>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script>
      function insertResults(json){
        $("#element_5_1").val(json["StreetAddress"]);
        $("#element_5_3").val(json["City"]);
        $("#element_5_4").val(json["State"]);
        $("#element_5_5").val(json["ZipCode"]);
      }

      function clearForm(){
        $("#element_5_1, #element_5_3, #element_5_4, #element_5_5").val("");
      }

      function makeAjaxRequest(placeId){
        $.ajax({
          type: "POST",
          data: { placeId: placeId },
          dataType: "json", 
          url: "process_ajax.php",
          success: function(json) {
            insertResults(json);
          }
        });
      }

      $("#meetingPlace").on("change", function(){
        var id = $(this).val();
        if (id === "0"){
          clearForm();
        } else {
          makeAjaxRequest(id);
        }
      });
    </script>
  </body>
</html>

process_ajax.php:

<?php
  mysql_connect('localhost', 'user', 'pass') or die('Could not connect: ' . mysql_error());
  mysql_select_db('sitepoint') or die('Could not select database');
   
  $placeId = $_POST['placeId'];

  $query = "SELECT * from meeting_places";
  $result = mysql_query($query) or die('Query failed: ' . mysql_error());
  while ($row = mysql_fetch_assoc($result)) {
    if ($placeId == $row['id']){
      echo json_encode($row);
    }
  }
?>

I hope that helps. Let me know how you get on :slight_smile:

I hope that helps. Let me know how you get on :slight_smile:

YES, this helps. I have tried this but have one problem. The information works - the other data is put in and works pretty well. However, why does the last line have State, Zip then City instead of like it is listed in my code?

Thanks

Hi there,

I’m glad it works.

I’m really not sure what you mean by this. Could you expand a little?