Home > Tutorials > PHP Tutorials > How To Populate A DIV via an HTML SelectBox, PDO, and jQuery

How To Populate A DIV via an HTML SelectBox, PDO, and jQuery

Imagine you have a database full of information, and you want to let users browse that data in the simplest way possible. Say you have a wide selection of data surrounding song titles & their artists, and you want to create a simplified search system that lets users select a song and instantly see who that song was by. You can accomplish with the help of PHP data objects (PDO), and a little bit of jQuery/AJAX.

For this PHP tutorial we’re going to recreate the above animation. Showing the artist information once a song title has been selected. The information will be pulled from a MySQL database via PHP and AJAX. The way it works, is when the page is loaded, a query is made to a database in order to acquire the list of music titles to be shown in the SELECTBOX. This information is stored in the $data variable, and the actual selectbox is populated via a FOREACH loop.

When the user selects something with the SELECTBOX, then jQuery detects a change in the SELECTBOX element and sends a post request to the server. This request runs a script to pull data from the database and send it back in JSON format. When the response is received, it is shown in a DIV with the “artist” id via AJAX/jQuery.

Here is an overview of the example database we will be using for this tutorial. If you wish to follow along you can download an .SQL file of this database here.

Let’s Get Started

We’re going to kick things off by setting up a way to actually connect to our MySQL database, and save that within a conn.php file. I won’t go into detail on how we’re going to do this, however I do have a full tutorial on how to connect to a MySQL database using PHP data objects which you can read.

Here is the code for our conn.php file. Take note that lines 11 & 15 are there for debugging purposes – should you wish to test your database connection.

<?php
$servername = "localhost";
$username = "someusername";
$password = "apassword123";
$database="tutorials";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
    //set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        //echo "Connected successfully"."<br>"; 
    }
catch(PDOException $e)
    {
        //echo "Connection failed: " . $e->getMessage()."<br>";

    }
?>

With our database connection setup, we can start working on the meat of our script. Our index.php page which will hold our select box and information div. To properly utilize jQuery to update your information div without reloading the page, make sure to include a jQuery library. During the writing of this tutorial I utilize version 3.2.1. With that out of the way, we’re going to start selecting the initial information from our MySQL database to populate our selectbox.

<?php
	//Load database connection
	require_once("conn.php");

	//Query the table
	$sql="SELECT * FROM `music`";
	$stm = $conn->prepare($sql);
	$stm->execute();
	$data=$stm->fetchAll(PDO::FETCH_OBJ);

?>

Having gotten the database info and stored it within the $data variable, we can now utilize a FOREACH loop to make our selectbox:

<p><strong>Music: Select Title to know the Artist</strong></p>
		<select id="selectbox_id" name="selectbox_name" class="form-control" required>
				<option value=""></option>

				<?php foreach ($data as $register): ?>
					<option value="<?php echo $register->id ?>"><?php	echo $register->title; ?></option>
				<?php endforeach; ?>

		</select>

Now we just need to utilize jQuery to fire a custom script whenever our selectbox is updated by the user. So right before the closing BODY tag, we’re going to add the following jQuery code:

<script type="text/javascript">
		$(document).ready(function() {

			//Populate textbox depending on drop-down selection
			$('#selectbox_id').change(function(){

				var selectbox_id = $(this).val();
				if (selectbox_id!=0) {
					var data_String;
					data_String = 'selectbox_id='+selectbox_id;
					//alert(data_String);
					$.post('selectbox_query.php',data_String,function(data){
						var data= jQuery.parseJSON(data);
						$('#artist').text(data.artist);
					});

				}else{
					$('#artist').text("");

				}
			});
		});
	</script>

As you can see on line 79 we utilize $.post to make a call to our selectbox_query.php file. This is the one responsible for actually querying our database to get the information we want. This information is then sent over in JSON format, and our jQuery script above parses that data and displays it inside the #artist div. This would also be a good time to go ahead and create that div within your index.php file.

<div id="artist"></div>

Now let’s setup our selectbox_query.php file. Here is the code we use, taking note that we’re including our conn.php file once more so we can connect to our MySQL database.

<?php

require_once("conn.php");

$artist_id =$_POST['selectbox_id']; 

//Run your query here to fetch the result and store it in a variable $data
if(isset($_POST['selectbox_id'])){

	$sql="SELECT * FROM `music` WHERE `id`=:artist_id LIMIT 1";
	$stm = $conn->prepare($sql);
	$stm->bindValue(':artist_id',(int) $artist_id,PDO::PARAM_INT);
	$stm->execute();
	$result=$stm->fetch(PDO::FETCH_OBJ);  

	$data['artist']= $result->artist;
    echo json_encode($data);
    exit();

}else{
    $data['artist']= "";
	echo json_encode($data);
    exit();
}

?>

As you can see we first check to see if a selectbox_id even exists. If it doesn’t the script simply sends back a blank. However if selectbox_id is provided, we query the database and select the appropriate information.

Feel free to download all the necessary code or make your own Git branch here. If you have any questions feel free to leave them down in the comments below.

About Michael Boguslavskiy

Michael Boguslavskiy is a full-stack developer & online presence consultant based out of New York City. He's been offering freelance marketing & development services for over a decade. He currently manages Rapid Purple - and online webmaster resources center; and Media Explode - a full service marketing agency.

Check Also

5 Must Have WordPress Optimization Plugins For A Fast Loading Website

Having a fast loading website is essential these days. First off, users are impatient. If ...

Like every other website, this site uses cookies to analyze our traffic. Cookies may also be utilized by our advertisers and partners. By using this website you agree to the use of said cookies. More Information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings, continuing to navigate past this message, or you click "Accept" below then you are consenting to the use of cookies on the Rapid Purple website.

Close