[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1265
  • Last Modified:

How to populate Text Boxes upon selection of value from Drop Down Box using AJAX and PHP

Hello Experts,

I have a HTML Document that contains two Drop Down Boxes and two Text Boxes. The first Drop Down Box is for selecting Solicitor Firm Names.

The values in the second Drop Down box should contain Solicitor Names and depends on the selection of the first Drop Down Box. I have managed to get this working using AJAX and a PHP file that queries the database and returns the results back to the AJAX file.

However, the values in the two Text Boxes, which should contain the Solicitor Phone and Solicitor Email, depend on the selection of a Solicitor Name from the second Drop Down Box.

I have been unsuccessful at this and would required some help and guidance. I have laid out the codes as below:

The Code for the HTML is as follows:

<!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>Sections Demo</title>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src = "javascript/firmsAndSolicitors.js"></script>
</head>
<!-- Insolvency Eye Working Example -->
<body>

<table id = "tblFilterSearches">
    <tr>
        <td style = "width: 50%;">Solicitor Firms:</td>
        <td style = "width: 50%;">
            <select name="SolicitorFirms" id = "SolicitorFirms" class="SolicitorFirms">
                <option value = '0' selected="selected">--Select Solicitor Firm--</option>
                <?php
                    include('db.php');
                    $sql = mysql_query("SELECT SolicitorFirmID, SolicitorFirmName FROM tblSolicitorFirms ORDER BY SolicitorFirmName", $con);
                    while($row = mysql_fetch_array($sql))
                    {
                        $solicitorFirmID = $row['SolicitorFirmID'];
                        $solicitorFirmName = $row['SolicitorFirmName'];
                        echo "<option value = '" . $solicitorFirmID . "'>" . $solicitorFirmName . "</option>";
                    } 
                ?>
            </select>
        </td>
    </tr>
    <tr>
        <td style = "width: 50%;">Solicitors:</td>
        <td style = "width: 50%;">
            <select name="Solicitors" id="Solicitors" class="Solicitors">
                <option selected="selected">--Select Solicitor--</option>
            </select>
        </td>
    </tr>
    <tr>
        <td style = "width: 50%;">Solicitor Phone No:</td>
        <td style = "width: 50%;"><input name="SolicitorPhoneNo" id="SolicitorPhoneNo" class='inputBoxStyle' value = ''></td>
    </tr>
    <tr>
        <td style = "width: 50%;">Solicitor Email:</td>
        <td style = "width: 50%;"><input name='SolicitorEmail' id='SolicitorEmail' class='inputBoxStyle' value = ''></td>
    </tr>
    <tr>
        <td style = "width: 50%;">Constant Value:</td>
        <td style = "width: 50%;"><input name='ConstantValue' id='ConstantValue' class='inputBoxStyle' value = 'This is a Constant Value'></td>
    </tr>
</table>

</body>
</html>

Open in new window


The Code for the AJAX file (called firmsAndSolicitors.js) is as follows:

$(document).ready(function()
{
	//Send the SolicitorFirmID to the PHP file to repopulate the Solicitor Names
	$("#SolicitorFirms").change(function()
	{
		var solicitorFirmID = $(this).val();
		var dataString = 'SolicitorFirmID=' + solicitorFirmID;
		
		$.ajax
		({
			type: "POST",
			url: "ajax_city.php",
			data: dataString,
			cache: false,
			success: function(html)
			{
				$("#Solicitors").html(html);
			} 
		});
	});	


	//Send the SolicitorID to the PHP file to repopulate the Solicitor Phone and Solicitor Email
	$("#Solicitors").change(function()
	{
		var solicitorsID = $(this).val();
		var dataString = 'SolicitorsID=' + solicitorsID;
		
		$.ajax
		({
			type: "POST",
			url: "ajax_city.php",
			data: dataString,
			cache: false,
			success: function(data)
			{
				//alert("This is the Solicitor Name Change");
				
				//$("#SolicitorPhoneNo").attr('src', data);
				$("#SolicitorPhoneNo").val(data);
				$("#SolicitorEmail").val(data);				
			}
		});	
	});	

});

Open in new window


The Code for the PHP file (called ajax_city.php) is as follows:

<?php
	# Insolvency Eye Working Example
	
	include('db.php');
	
	# Send values for Solicitor Names depending on the Solicitor Firm that the user has selected
	if($_POST['SolicitorFirmID'])
	{
		$solicitorFirmID = $_POST['SolicitorFirmID'];		
		echo "<option value = '0' selected = 'selected'>--Select City--</option>";

		if ( $solicitorFirmID != 0 )
		{
			$sql = mysql_query("SELECT * FROM tblSolicitors WHERE SolicitorFirmID = " . $solicitorFirmID . " ORDER BY SolicitorName", $con);

			while($row = mysql_fetch_array($sql))
			{
				$solicitorsID = $row['SolicitorsID'];
				$solicitorName = $row['SolicitorName'];
				echo "<option value = '" . $solicitorsID . "'>" . $solicitorName . "</option>";
			}	# End of While
		}	# End of IF Statement checking value of SolicitorFirmID
	}
	else
	{
		echo "<option value = '0' selected = 'selected'>--Select City--</option>";		
	}	# End of IF Statement checking if the SolicitorID has been POSTED


	# Send values for Solicitor Phone and Email depending on the Solicitor Name that the user has selected
	if($_POST['SolicitorsID'])
	{
		$solicitorsID = $_POST['SolicitorsID'];		

		if ( $solicitorsID != 0 )
		{
			$sql = mysql_query("SELECT * FROM tblSolicitors WHERE SolicitorsID = " . $solicitorsID, $con);
			$row = mysql_fetch_assoc($sql);

			$solicitorPhoneNo = $row['SolicitorPhoneNo'];
			$solicitorEmail = $row['SolicitorEmail'];

			//echo $solicitorPhoneNo;
			//echo $solicitorEmail;
			echo "<input name='SolicitorPhoneNo' id='SolicitorPhoneNo' class='inputBoxStyle' value = '" . $solicitorPhoneNo . "'>";
			echo "<input name='SolicitorEmail' id='SolicitorEmail' class='inputBoxStyle' value = '" . $solicitorEmail . "'>";

		}	# End of IF Statement checking value of SolicitorFirmID
	}
	else
	{
		//echo "<input name='SolicitorPhoneNo' id='SolicitorPhoneNo' class='inputBoxStyle' value = ''>";
		//echo "<input name='SolicitorEmail' id='SolicitorEmail' class='inputBoxStyle' value = ''>";
	}	# End of IF Statement checking if the SolicitorID has been POSTED
?>

Open in new window


I need to know what output to send from the PHP file and what script to write in the AJAX file so that the Text Boxes are populated with the required return values i.e. the Solicitor Phone No to be populated into the Text Box with the ID 'SolicitorPhoneNo' and the Solicitor Email Address to be populated into the Text Box with the ID 'SolicitorEmail'.

Thanks in advance and all help is appreciated.

ref-IT
0
ref-IT
Asked:
ref-IT
  • 7
  • 7
3 Solutions
 
Chris StanyonCommented:
Probably the easiest option here is to do the whole thing with a single AJAX lookup. When you pass the SolicitorsID to your PHP function, just include the telephone number and email in the <OPTION> tags, using data elements, so instead of building it like this:

$solicitorsID = $row['SolicitorsID'];
$solicitorName = $row['SolicitorName'];
echo "<option value = '" . $solicitorsID . "'>" . $solicitorName . "</option>";

Open in new window


Build it like this:
$solicitorsID = $row['SolicitorsID'];
$solicitorName = $row['SolicitorName'];
$solicitorTel = $row['SolicitorPhoneNo'];
$solicitorEmail = $row['SolicitorEmail'];
echo "<option value = '" . $solicitorsID . "' data-tel='" . $solicitorTel . "' data-email='" . $solicitorEmail . "'>" . $solicitorName . "</option>";

Open in new window


This way you only ever have to make a single AJAX request to a single DB request. You can then retrieve these data tags like so:

$("#Solicitors").change(function() {
	var solicitor = $("#solicitor option:selected" );
	$('#SolicitorPhoneNo').val(solicitor.data('tel'));
	$('#SolicitorEmail').val(solicitor.data('email'));
});

Open in new window

0
 
ref-ITAuthor Commented:
Hey Chris,

Thank you very much for the reply. You are a genius man !!

Having an MS Access VBA coding background, I know that we can have multiple columns in a Drop Down Box. I had thought implementing something similar but I just wasn't sure how to go about doing it. I think your suggestion might just work.

Please give me some time to test it and I'll get back to you with full on points !!

Thanks,

ref-IT
0
 
Chris StanyonCommented:
No worries - once you get a handle on the data attributes, it may well save you a lot of time and effort - it means you can store a whole lot more data with the elements than you otherwise could :)
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
ref-ITAuthor Commented:
Hey Chris,

Okay, I've tested the data and the ajax_city.php file returns the values of the Solicitors Drop Down Box just fine together with the data-tel and data-email attributes. The Javascript file however, does not seem to be able to pick on the data-tel and data-email values.

I realised that you've made a slight mistake in the Javascript code but the data-tel and data-email values are still being returned as null values.

The following is the code that I've used to display the data-tel and data-email values:

	//Populate the Solicitor Phone No and the Solicitor Email based on the
	$("#Solicitors").change(function() {
		var solicitor = $("#Solicitors option:selected");
		
		var solicitorID = solicitor.val()
		var solicitorPhoneNo = solicitor.data("tel");
		var solicitorEmail = solicitor.data("email");
		
		alert(solicitorID + " " + solicitorPhoneNo + " " + solicitorEmail);
	});

Open in new window



I get the solicitorID just fine, but the data-tel and data-email values are returned as null.

Any ideas why this could be happening?

Thanks,

ref-IT
0
 
Chris StanyonCommented:
The only thing I see in your code is a missing semi-colon after the var SolicitorID line. Without seeing the generated HTML, can't realy see anything else wrong.
0
 
ref-ITAuthor Commented:
Hey Chris,

Thanks for the response.

The results are the same even if I put in the semi-colon after the var solicitorID = solicitor.val() line. The data-tel and data-email values are still being returned as null values.

An example of the generated HTML when some of the Solicitor Firms are selected is as follows:

<!-- When Solicitor Firm name Wardhaway is selected -->
<select name="Solicitors" id="Solicitors" class="Solicitors">
<option value="0" selected="selected">--Select Solicitor--</option>
<option value="1" data-tel="020 8564 1245" data-email="steven.petrie@wardhadaway.com">Steven Petrie</option>
<option value="2" data-tel="020 8716 1249" data-email="sue.wood@wardhadaway.com">Sue Wood</option>
</select>

<!-- When Solicitor Firm name Pannone Corporate is selected -->
<select name="Solicitors" id="Solicitors" class="Solicitors">
<option value="0" selected="selected">--Select Solicitor--</option>
<option value="8" data-tel="020 8741 2369" data-email="daniel.clarke@pannonecorporate.com">Daniel Clarke</option><option value="7" data-tel="020 8125 1369" data-email="karl.williams@pannonecorporate.com">Karl Williams</option></select>

<!-- When Solicitor Firm name Zain & Associates is selected -->
<select name="Solicitors" id="Solicitors" class="Solicitors">
<option value="0" selected="selected">--Select Solicitor--</option>
<option value="62" data-tel="0208 451 3461" data-email="ali@zainassociates.co.uk">Ali Smith</option>
<option value="63" data-tel="" data-email="">Joseph Smith</option>
<option value="58" data-tel="0208 451 3461" data-email="sarah@zainassociates.co.uk">Sarah Smith</option></select>

Open in new window


Hope this helps to figure out what the problem could be.

Thanks,

ref-IT.
0
 
Chris StanyonCommented:
OK. It all looks good to me.

You can see it working correctly here -> http://jsfiddle.net/ChrisStanyon/6f0ew1kb/

Is there a live demo page that I can take a look at to see where things are going wrong?
0
 
ref-ITAuthor Commented:
Hey Chris,

Let me upload it to my Web Server and I'll send you the link and you can take a look.

Thanks,

ref-IT
0
 
ref-ITAuthor Commented:
Hey Chris,

My apologies for the delay.

Please take a look at the following link:

http://www.insolvencyeye.co.uk/sandbox/Dynamic_Select_Box/InsolvencyEye%20Working%20Example/sections_demo.php

Thanks,

ref-IT.
0
 
Chris StanyonCommented:
Ahhh. Got it - you're using a really old version of jQuery (1.4.2) so it won't work - upgrade to at least 1.4.3 (preferably a lot newer) - you're at least 30 versions behind the current one!!!
0
 
ref-ITAuthor Commented:
WOW ... I would never have thought of looking there !!

Just tested the code and it worked seamlessly as soon as I changed the version to 1.4.3. How do I find out what the latest version is so that I can change it to that.

Chris, honestly thanks a lot mate. You've allowed me to make the application I'm working on look even slicker.

Thanks,

ref-IT.
0
 
Chris StanyonCommented:
Excellent news - knew we'd get there in the end :)

You can head to jquery.com to see which is the latest version or if you want to carry on using the google CDN, then you can check out their page - it'll show you which versions they host:

https://developers.google.com/speed/libraries/devguide

Here's another trick. If you use the google CDN, you can drop the minor version numbers and google will automatically serve the highest version it can, so if you link to this:

//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js

It will automatically deliver the highest version 1 package it can (1.11.2)

If you do this, you'll always have the latest version, but obviously your site will automatically update when google's does and that may break some part of your application.

Also, in your script tag, drop out the http: and you'll never receive 'unsecure' error messages - if your page is on https, you'll get the https version. If it's on http, then you'll get the http version. Saves headaches down the line :)

To link to the latest version 1 jquery, your script tag would look like this:

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

Open in new window

0
 
ref-ITAuthor Commented:
Thanks a million for all the help there Chris.

You've not only been spot on and punctual, but also highly informative. Certainly hope to learn a lot more from you in the future.

ref-IT
0
 
Chris StanyonCommented:
No worries. Thanks for the points :)
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.

  • 7
  • 7
Tackle projects and never again get stuck behind a technical roadblock.
Join Now