Sunteți pe pagina 1din 3

DYNAMICALLYGENERATEASELECTLISTWITHJQUERY,AJAX&PHP

09MARCH,2014BYTOMELLIOTT
Thispostrunsthroughthestepsneededtogeneratethevaluesofoneselectlistbasedonthechosen
valuefromanotherselect.WewillbeusingAJAX(AsynchronousJavaScriptandXML),asthisavoidsthe
needtorefreshthewholepage,givingasmootherexperiencetotheuserandavoidingunnecessary
callstotheserver.

TheAJAXcallwillsendtheselecteddropdownvaluetoaPHPscriptwhichwillreturnallmatching
valuesfromatableinaMySQLdatabase,whichwillthenbeusedtopopulateourseconddropdown.
WewillalsobeusingthejQueryframeworktomaketheAJAXcallandtodetecttheselectlistchange.
Theexamplebelowwillbeusinganimaginarytearotaselectionscenario,wherewewillselectnamesof
peoplebasedontheirfavouritebeverage.

THEPHP
LetsfirstlookatthePHPcodetoconnecttothedatabaseandselectthevaluesfromatablebasedona
GETparameter.Thefirstlineestablishesthedatabaseconnection,followedbyaselectquerytoreturn
thevaluesfromatable.Wewillbeusingthesevaluestopopulateoursecondselectlist.ThePHPthen
loopsthrougheachrowinthetable,echoingouttheHTMLfortheselectoptions.

<?php
$connection=mysqli_connect("localhost","dbusername","dbpassword","dbname");

$selectvalue=mysqli_real_escape_string($connection,$_GET['svalue']);

mysqli_select_db($connection,"dbname");
$result=mysqli_query($connection,"SELECTtbl_drinks.drink_nameFROMtbl_drinksWHEREtbl_drinks.drink_type='$selectvalue'");

echo'<optionvalue="">Pleaseselect...</option>';
while($row=mysqli_fetch_array($result))
{
echo'<optionvalue="'.$row['drink_name'].'">'.$row['drink_name']."</option>";
//echo$row['drink_type']."<br/>";
}

mysqli_free_result($result);
mysqli_close($connection);

?>

Youllobviouslyneedtoreplacethedatabaseconnectionvalueswithyourowndetailsalongwithyour
tableandfieldname(s)intheSQLstatement.Saveyourfile,e.g.ajaxgetvalues.phpandcheckthat

everythingisworkingbypassingtheGETparameterintheURL,i.e.ajaxgetvalues.php?svalue=coffee.
Youmightwanttousearegularechotooutputthevaluestotest.
Note,ifyouareusingnumericalvalues,youdontneedtheapostrophesaround '$selectvalue' inthe
SQLstatement

THEHTML
NowwellcreatethetwoselectlistsandassigntheIDsaslistselectandlisttargetinthisexample.
Ourfirstselectlistwillhaveabasicsetofoptionsandthesecondselecthasnooptionvalues,asthese
willbepopulatedbytheAJAX.

<selectname="listselect"id="listselect">
<optionvalue="">Pleaseselect..</option>
<optionvalue="tea">tea</option>
<optionvalue="coffee">coffee</option>
<optionvalue="water">water</option>
</select>

<selectname="listtarget"id="listtarget"></select>

THEJQUERY
Nowtobringitalltogether.HeresthejQuerythatlistensfortheselectlistchange,makestheAJAXcall
andpopulatesthetargetselect.

$(document).ready(function($){
varlist_target_id='listtarget';//firstselectlistID
varlist_select_id='listselect';//secondselectlistID
varinitial_target_html='<optionvalue="">Pleaseselectacolour...</option>';//Initialpromptfortargetselect

$('#'+list_target_id).html(initial_target_html);//Givethetargetselectthepromptoption

$('#'+list_select_id).change(function(e){
//Grabthechosenvalueonfirstselectlistchange
varselectvalue=$(this).val();

//Display'loading'statusinthetargetselectlist
$('#'+list_target_id).html('<optionvalue="">Loading...</option>');

if(selectvalue==""){
//Displayinitialpromptintargetselectifblankvalueselected
$('#'+list_target_id).html(initial_target_html);
}else{
//MakeAJAXrequest,usingtheselectedvalueastheGET
$.ajax({url:'ajaxgetvalues.php?svalue='+selectvalue,
success:function(output){
//alert(output);
$('#'+list_target_id).html(output);
},

error:function(xhr,ajaxOptions,thrownError){
alert(xhr.status+""+thrownError);
}});
}
});
});

WefirstsetupafewvariablesfortheselectlistIDs,alongwithaninitialoptionforourtargetselectthat
promptstheusertomakeaselectionfromtheinitialselect.

Thenwesetupaneventlistenertodetectwhenourfirstselectlistischangedandassigntheselected
valuetoaselectvaluevariable.Ifthefirstpleaseselectoptionischosen(withablankvalue)however,
thesecondselectlistwillreverttotheinitialprompt.Iftheselectedvalueisnotblankthenweexecute
theAJAXcall.

WealsosetthevalueofthetargetselecttoLoading..sotheuserknowssomethingishappening.This
mayonlyflashmomentarilysoyoumaywishtodisablethis.

TheAJAXcallrequestsourPHPscript,usingtheselectedvalueastheGETparameter.Onsuccessful
executionofthescript,itwillsettheHTMLofthetargetselectwiththeoptionvalueswereechoingout
withthePHP.Theresalsosomeerrorhandlingthrowninforgoodmeasurewhichmayhelpusidentify
anyissuessuchasconnectivityproblems.

S-ar putea să vă placă și