Populate a ListBox with data from MySQL Database using PHP

In this post we are going to show you how to populate a jQuery ListBox widget with data from MySQL Database using PHP.

1. Create a new file named data.php with the following content in it:

<?php

/*
   Connecting to the database
*/
$dbuser = 'root';
$dbpass = '';
$host = 'localhost';
$db = 'sample';
mysql_connect($host, $dbuser, $dbpass) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());

/*
  Executing SQL query
*/
$queryResult = mysql_query('SELECT name FROM users') or die(mysql_error());
$source = array();

/*
  Building the source string
*/
while ($row = mysql_fetch_array($queryResult)) {
  array_push($source, $row['name']);
}

/*
  Printing the source string
*/
echo json_encode($source);

?>

2. Create a new file in the same directory (for example index.html) and retrieve the data by making an ajax call with jQuery to the data.php. Then parse the result with the $.parseJSON function and save it in the source variable. The final step is to select the ‘listbox’ div tag and call the jqxListBox constructor. It is important to set the ListBox’s source property to the ‘source’ variable. Otherwise, the ListBox will not display any data.

<!DOCTYPE html>
<html>
<head>
<title>jqxListBox</title>
<link rel="stylesheet" href="styles/jqx.base.css" />
<link rel="stylesheet" href="styles/jqx.classic.css" />
<script src="scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="scripts/jqxcore.js" type="text/javascript"></script>
<script src="scripts/jqxbuttons.js" type="text/javascript"></script>
<script src="scripts/jqxlistbox.js" type="text/javascript"></script>
<script src="scripts/jqxscrollbar.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $.ajax({
            url: 'data.php',
            success: function (data) {
                var source = $.parseJSON(data);
                $("#listbox").jqxListBox({ source: source, width: '200px', height: '250px', theme: 'classic' });
            },
            error: function () {
                alert('The source is unavailable!');
            }
        });
    });
</script>
</head>
<body>
<div id="listbox"></div>
</body>
</html>


The resulting ListBox is shown below:

About admin


This entry was posted in JavaScript, JavaScript Plugins, JavaScript Widgets, jQuery, jQuery Plugins, jQuery UI, jQuery UI Plugins, jQuery UI Widgets, jQuery Widgets, jQWidgets, jqxListBox and tagged , , , , , , , , , , , , , , , , , , , . Bookmark the permalink.



3 Responses to Populate a ListBox with data from MySQL Database using PHP

  1. Neelam says:

    Its amazing. Nice article and did work for me.
    Thanks for great help.

Leave a Reply