Populating a Drop Down Menu (select) - php

I've been trying to solve my question based off of this answer:
Populate select box from database using jQuery
I've attempted to implement what is said in the answers there but I am not having any luck here. As of now all that appears in the drop down menu is the default "Stone" item that starts in it.
Could anyone spare some time and give me a hand fixing my issue. My code should essentially read from a MySQL database which has over 150 ID's in order starting at 1 and use the corresponding name in the same ID's row to populate the drop down menu on load.
Example of what drop down menu would look like inside of it:
Stone
Grass
Diamond
What corresponding DB would look like:
ID item_name
1 Stone
2 Grass
3 Diamond
The code I'm using to try and do this is:
PHP (process_item_list.php):
$con = mysql_connect($DB_HOST,$DB_USER,$DB_PASSWORD);
$dbs = mysql_select_db($DB_NAME, $con);
$tableName = "itemlist";
$result = mysql_query("SELECT * FROM $tableName");
$data = array();
while ( $row = mysql_fetch_row($result) )
{
$data[] = $row;
}
echo json_encode( $data );
?>
jQuery/Javascript
<script type="text/javascript">
$(function(){
var items="";
$.getJSON("process_item_lists.php",function(data){
$.each(data,function(index,item)
{
items+="<option value='"+item.id+"'>"+item.name+"</option>";
});
$("#tradeItems").html(items);
});
});
</script>
HTML
<select id="tradeItems">
<option value="">Stone</option>
</select>
I'm open to different ways to do this as well, as long as it still fills the drop down menu on load!
Edit: With the help of wirey the PHP issue is fixed. Here is what the results look like from running the PHP file: http://fogest.net16.net/mctrade/php/process_item_list.php
When I run the actual page using the alert boxes which should give me the ID and the item name they both return undefined rather then the correct values.

The results at http://fogest.net16.net/mctrade/php/process_item_list.php doesn't look like what you're expecting, it looks like this:
[ ["1","Stone","images\/stone.png"],
["2","Grass Block","images\/grass_block.png"],
/* snip a lot of rows */
]
But what you are expecting is something like this:
[ { "id":"1", "name":"Stone", "image?":"images\/stone.png"},
{ "id":"2", "name":"Grass Block","image?":"images\/grass_block.png"},
/* and so on */
]
I think that you'll want to use mysql_fetch_assoc() instead of mysql_fetch_row(), that might give you proper output.
Bonus: you can give the response a proper content-type by adding a row before the echo:
header("Content-type: application/json");
echo json_encode($data);
Remark: when I inspected the source of http://fogest.net16.net/mctrade/php/process_item_list.php I found this at the end:
<!-- Hosting24 Analytics Code -->
<script type="text/javascript" src="http://stats.hosting24.com/count.php"></script>
<!-- End Of Analytics Code -->
This should not be part of the response, it will probably make the JSON parser crash.

Related

PHP jQuery dynamically populated SELECT

Have been looking around for a solution to this and have found some help on stack overflow but in most cases the examples I have found are not using arrays formed from a database query. Here is some code for what I am trying to achieve...
$stores = mysql_query("SELECT * FROM Stores");
$staff = mysql_query("SELECT * FROM Staff");
I would like to create two elements, one for stores and another for staff but I want to filter the staff based on the store client side. So if the user selects "Sydney" from the first dropdown, they are presented with only staff that work at the Sydney store in the second dropdown. Then if the user chooses "London" from the first dropdown, the Sydney staff are replaced by the London staff and so on.
My server side scripting is done with PHP and I am able to create the two dropdowns with PHP. But I am stuck on the jQuery to remove the I don't want from the second dropdown.
I know this is possible, because I see it used all the time. I have seen lots of examples of how to manage this but none of the examples use data from the PHP array to insert the .
You need ajax.
When the user selects something in a dropdown, this fires an event that you can process. Inside of this process you take the value of the selection like jQuery('#id_dropdown').val(), and send this via ajax (I like using POST since you dont run into GET request size limits).
You process this on the server side with php, accessing to the database with the value selected and sent via ajax. When you have the right results for the second dropdown you can output it via echo.
Finally, when the response is returned to jQuery, you can insert all the options in the new dropdown.
JAVASCRIPT PART:
Bind event to the first dropdown
Get value of the option selected in the dropdown
Make ajax request
Here is some example code:
var parameters='value_selected='+value_dropdown;
jQuery.Post({
url: '/destiny_when_I_process',
data: parameters,
success: func_callback
});
//here you can imagine a pause, because PHP is processing the data you send by post
//....
//....
//this part is executed when php send the information
function func_callback(response_from_php){
jQuery('#second_dropdown').html(response_from_php);
}
PHP PART:
get value from POST
access database using this value
echo (send response). You send a chain of text (in HTML), really this is not very professional, but is OK for demonstration purposes. Professionals send JSON, since JSON is lighter-weight.
JAVASCRIPT PART (SECOND PART)
in the callback function, you receive the response data via the first parameter
Insert new data in the second dropdown (since the data is already HTML, you do not need to process it)
for the secondary drop down, yes, you'll need some ajax.
You can create a script that go fetch the result coresponding to the store and send back the option listm witch is inserted in the ooption.
Using jquery and php you'll need a few thing.
A php file to get the result and return the options. (let say getStaff.php)
<?php
//get the store id by post is it is set
if (isset($_POST['store->id']) $store_id = mysqli_real_escape_string($_POST['store_id']);
//get the data !! notice the WHERE caluse
$r = mysql_query("SELECT * FROM Staff" *WHERE store=''$store->is*);
//split the data in the array
$staffs=array();
while ($assoc = mysql_fetch_assoc($r)) {
//Varialbe = $assoc['colum_name'];
$staff->id=$assoc['id'];
$staff->name=$assoc['name'];
//and so on for each colum in your table.
array_push($staffs, $assoc);
}
//echo the result as option
foreach ($staffs as $staff) echo "<option value='$staff->id'>$staff->name</option>";
?>
In you first select, add
onchange="$.post('getStaff.php', {store_id:$(this).val()}, function (data){ $('#staff_select').html(data);});"
and add an id to your second select (staff_select) in this ecample.
As an explanation: When the 1st dropdown change, it send a request to getStaff.php with the store_id as a POST argument. The php sript get the syaff according to the store Id and bring back a list of option tags for your secondary select. Than jquery add the 'data' to your secondary select and VOilĂ !
Hope tih sis clear cause it's a bunch of little thing together that will make it work. Sorry if it's seems sloppy as an answer but it's really simple once you know it.
Spent the afternoon learning how to do this and it's working quite well. Posted the new code here for others....
Thanks to http://forum.codecall.net/topic/59341-php-sql-jquery-and-ajax-populate-select-boxes/ for the tutorial.
And thanks to everyone here.
PHP to build for the first :
function agency_select() {
include('../include/dbase.php');
$agencies = $pdo->query("SELECT * FROM agency WHERE Status='active' ORDER BY AgencyName");
$opt = '';
while ($age_array = $agencies->fetch(PDO::FETCH_ASSOC)) {
$opt .= '<option value="'.$age_array['AgencyId'].'">'.$age_array['AgencyId'].' - '.$age_array['AgencyName'].' - '.$age_array['AgencySuburb'].'</option>'."\n\t\t\t\t\t\t\t";
}
return $opt;
}
HTML for the two elements:
<label for="AgencyId">Client/Agency:</label>
<select class="uniform" id="AgencyId" name="AgencyId" style="width: 400px; overflow-x: hidden">
<?php echo agency_select(); ?>
</select>
<label for="Contact">Contact: </label>
<select class="uniform" id="Contact" name="Contact" style="width: 300px; overflow-x: hidden">
<option value="">----Select Client/Agency----</option>
</select>
AJAX file:
if(isset($_POST['AgencyId'])) {
include('../include/dbase.php');
$option = '<option value="">----Select Contact----</option>';
$query = $pdo->prepare("SELECT * FROM client WHERE AgencyId= ? AND Status='active' ORDER BY FirstName");
$result = $query->execute(array($_POST['AgencyId'])));
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$option .= '<option value="'.$row['id'].'">'.$row['FirstName'].' '.$row['LastName'].'</option>';
}
echo $option;
}
jQuery:
$(document).ready(function () {
update_contacts();
});
function update_contacts() {
$('#AgencyId').change(function() {
$('#Contact').fadeOut();
$('#loader').show();
$.post('../ajax/ajax_contact_select.php', {
AgencyId: $('#AgencyId').val()
}, function (response) {
setTimeout("finishajax('Contact', '"+escape(response)+"')", 400);
});
return false;
});
}
function finishajax(id,response) {
$('#loader').hide();
$('#'+id).html(unescape(response));
$('#'+id).fadeIn();
}
i'll try to help you as much as i can a explain it.
mysql_query, you sould use mysqli btw, mtsql being decrecated, return a result set.
This means you will have all the records from your query. You need to brak down your result into before you can work with it. This is done by using methids like mysql_fetch_assoc, mysql_fetch_row, etc. There something like fetch to array to but i don't master it so i will use fetch assoc, for this reply.
So once you have yoru result set, $stores & $staff in your case, you then call a while loop on your results to get th data as in:
while ($assoc = mysql_fetch_assoc($r)) {
//Varialbe = $assoc['colum_name'];
$stores->id=$assoc['id'];
$stores->name=$assoc['name'];
//and so on for each colum in your table.
array_push($stores, $assoc);
}
Then you can export it as you want.
in you case would be something like
foreach ($stores as $store) echo "<option value='$store->id'>$store->name</option>";
I storngly suggest you take alook at http://php.net/manual/en/function.mysql-fetch-array.php witch will do the same a fetch_assoc bu with an array with the columname as key.

multi tags using auto suggest jQuery plugins

I use Auto suggest jQuery plugins from this site:
http://code.drewwilson.com/entry/autosuggest-jquery-plugin
for making tags multiple as like giving in that site.
But my problem is...
While selecting from the autosuggest, it was displayed in my input box but I don't want to display selected autosuggest again as like in example given in the link....but I am unable to do such things...
please help me...
code used by me as follows:
<link rel="stylesheet" type="text/css" href="view/stylesheet/autoSuggest.css">
<script type="text/javascript" src="view/javascript/jquery/jquery.autoSuggest.js"></script>
<script type="text/javascript"><!--
$("#product_tag1").autoSuggest("http://test.com/ajax", {minChars: 2, matchCase: true,selectedItemProp: "tag", searchObjProps: "tag"});
//--></script>
Ajax file like
<?
$input = $_GET["q"];
$data = array();
$query = mysql_query("SELECT * FROM my_table WHERE my_field LIKE '%$input%'");
while ($row = mysql_fetch_assoc($query)) {
$json = array();
$json['tag_id'] = $row['id'];
$json['tag'] = $row['tag'];
$data[] = $json;
}
header("Content-type: application/json");
echo json_encode($data);
?>
May I suggest the Select 2 plugin as an alternative? It is in active development and has IMHO nicer features; for example showing the list of available tags when the control has focus and not allowing the same tag to be selected more than once.
It sounds like it will do exactly what you want, but please see the Tagging Example for a description of all of the options. I do not think it will be difficult to switch plugins, based on your example code.
By using following codes in document ready function of javascript
$(document).ready(function()
{
var data=null;
var data=;
$("#tag").autoSuggest("config->item('admin_folder').'/products/autosuggest');?>",{minChars: 2, matchCase: true,selectedItemProp: "name", searchObjProps: "name",selectedValuesProp:"value",preFill: data});
});

jquery-ui-1.8.14 Autocomplete with php and mysql

I'm not very much into js and programing in general, but I'm very stuck on something that really shouldn't be too difficult. Feel free to visit the test page:
[REMOVED LINK]
I have three autocomplete fields: Current club, nation and career stats.
Autocomplete works perfectly for the career stats where I can also add fields and the autocomplete also works for the added field.
But for the current club and nation fields, I get results while typing but when I click the correct output it doesn't show up in the input-field.
I can make it work using other js-libraries, but then it no longer work for the add-button career stats fields.
I use the following libraries:
<script type="text/javascript" src="js/jquery-1.6.3.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.14.custom.min.js"></script>
<script type="text/javascript" src="js/jq-ac-script.js"></script>
The current club html looks like:
<p>
Current club <label>:</label>
<input type="text" id="currentclub" />
</p>
In the custom made jq-ac-script.js (I originally found this somewhere online - don't remember where) the important part is:
$(document).ready(function(){
$( "#currentclub" ).autocomplete({
source: "get_club_list.php",
minLength: 1
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( item.currentclub )
.appendTo( ul );
};
});
The "get_club_list.php" looks like:
<?php
include ("dbsetup.php");
$return_arr = array();
$param = $_GET["term"];
$fetch = mysql_query("SELECT * FROM FootNews_CLUB
WHERE clubShortName LIKE '%$param%'");
/* Retrieve and store in array the results of the query.*/
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['currentclub'] = $row['clubShortName'];
array_push( $return_arr, $row_array );
}
/* Free connection resources. */
mysql_close($conn);
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
?>
Any ideas whereas to why the selected club doesn't show up when I click it would be appriciated!!
Wow, used my php code. Cool, glad I could help.
http://www.jensbits.com/2010/03/29/jquery-ui-autocomplete-widget-with-php-and-mysql/
Not sure why you are using the autocomplete code with _renderItem in it. I don't think you need it.
Change the php code to this:
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['currentclub'] = $row['clubShortName'];
$row_array['value'] = $row['clubShortName'];
array_push( $return_arr, $row_array );
}
And, the jquery to:
$( "#currentclub" ).autocomplete({
source: "get_club_list.php",
minLength: 1
});
You can read through my tutorial again but the autocomplete needs a label or value field returned. It then populates the select list and the corresponding input field with that value.
I left in $row_array['currentclub'] = $row['clubShortName']; because I don't know if you are grabbing that later on. If you are not, you don't need that line either.
Since you control the returned data and can specify a label and/or value field in the php, I don't understand why you are using the _renderItem for any of the autocompletes.
BTW, you should add mysql_real_escape_string to your php code for some sql injection protection: http://www.php.net/manual/en/function.mysql-real-escape-string.php

How to set an Array in Javascript dynamically?

I am working on an e-commerce website. There is an array "products" in javascript defined by the following code
<script type="text/javascript">
var products =
[
{"id":"1","title":"Apple iPhone 4"},
{"id":"2","title":"BlackBerry 9780 Bold"}
];
/*some other javascript code*/
</script>
I want this array to be updated dynamically according to the number of rows returned by querying the database.
For example, suppose I query the database and 5 rows are returned. I want this array to be updated with those 5 rows. Please help me getting this done. I am using PHP, MySQL, Apache on Windows machine.
You want the push function: http://www.w3schools.com/jsref/jsref_push.asp
var products =
[
{"id":"1","title":"Apple iPhone 4"},
{"id":"2","title":"BlackBerry 9780 Bold"}
];
// Let's add a new phone:
products.push({"id":"3","title":"HTC Evo"});
/*
products now equals:
[
{"id":"1","title":"Apple iPhone 4"},
{"id":"2","title":"BlackBerry 9780 Bold"},
{"id":"3","title":"HTC Evo"}
];
*/
To account for the possibility you may have an existing array and you'd like to update it via ajax, you can do this dynamically with PHP:
<script type="text/javascript">
<?php foreach($phones as $phone): ?>
products.push({"id":"<?=$phone['id']?>","title":"<?=$phone['name']?>"});
<?php endforeach; ?>
</script>
The top answer to the question JSON encode MySQL results could achive this for you:
$sth = mysql_query("SELECT ...");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
In your case, replacing the last line with
?>
var products = <?php echo json_encode($rows); ?>;
<?php
would initialize the JavaScript object with your query results. This would need to be done before the page is loaded, because the PHP runs on the server producing the JavaScript for the client. If you need to get the results after the client page is loaded you would need a more complicated solution, probably using AJAX.
I would make a server side script that makes the connection to the database, get's the products, and constructs the JSON for you, so that way all you have to do is make an AJAX request to the script from the client side and it will return everything for you for use on your webpage.
You can use PHP to output json directly into the page.
Assuming that $data is an array that contains the products you want to output.
In the template you would do something like this:
<script type="text/javascript">
var products = <?php echo json_encode($data) ?>;
</script>
products[products.length] = {..some data..};
products.push({..some data..});
Or you need something else?

Autocomplete form populated by a database?

I am currently working on a project in which I need to have an autocomplete form call its information from a db file. I have seen many tutorials on jquery autocomplete forms, but I do not know how to call a db file to populate the list.
I am working in PHP. Currently the code represents a simple drop down box that is calling on the db file for population.
<?php
global $wpdb;
$depts = $wpdb->get_results( "SELECT * FROM departments ORDER BY department_name ASC" );
echo '<select>';
foreach($depts as $row) {
echo '<option name="select_dept" value="'.$row->department_id.'">'.$row->department_name.'</option>';
}
echo '</select>';
?>
Any help would be awesome!
I recently have used this library for autocompletion - http://www.devbridge.com/projects/autocomplete/jquery/
So here is brief script based on yours:
<?php
$query = isset($_GET['query']) ? $_GET['query'] : FALSE;
if ($query) {
global $wpdb;
// escape values passed to db to avoid sql-injection
$depts = $wpdb->get_results( "SELECT * FROM departments WHERE department_name LIKE '".$query."%' ORDER BY department_name ASC" );
$suggestions = array();
$data = array();
foreach($depts as $row) {
$suggestions[] = $row->department_name;
$data[] = $row->department_id;
}
$response = array(
'query' => $query,
'suggestions' => $suggestions,
'data' => $data,
);
echo json_encode($response);
} else {
?>
<html>
<body>
<input type="text" name="" id="box" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script src="http://www.devbridge.com/projects/autocomplete/jquery/local/scripts/jquery.autocomplete.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#box').autocomplete({
serviceUrl:'/',
// callback function:
onSelect: function(value, data){ alert('You selected: ' + value + ', ' + data); },
});
});
</script>
</body>
<html>
<?}?>
Please follow this very well written tutorial
http://www.nodstrum.com/2007/09/19/autocompleter/
JQuery UI includes an autocomplete, although you still need to write a PHP script to return the information to be added to the control as its done via AJAX. If you know in PHP how to connect to a database, query it, and return a list of the results - then you will have no problems with this. JQuery makes AJAX extremely simple.
Depending on how complicated your field/data set is - and assuming its not millions upon millions of unindexed records, I would be content to autocomplete from a:
SELECT thing WHERE thing LIKE '".$query."%'
So if you were searching for, say, food... the query "CA" would pull out CArrot and CAbbage and CAuliflower. If you added a % to the beginning of the LIKE, you could get results that contained your query, as opposed to just beginning with it.
The page your user hits would contain the JQuery part which both sends the request and creates the autocomplete effect from the results, and a very simple, separate PHP script which the AJAX request hits would return the potential 'matches'.
Take a look at the Autocomplete demos on JQuery UI

Categories