Auto-change drop down menu, html - php

I have to 2 drop down menu which look like this :
a drop down http://img401.imageshack.us/img401/3786/90550627.jpg
The Item menu have two value which is "Server" and "Switch". Meanwhile, the value in Model menu depend on the value in the Item menu. The value in Model menu is called from the database. What I want to do is when "Server" is selected, it will call data from server table into the Model menu and when "Switch" is selected, it will call data from switch table. How can I do that?

Lets take an easy example, I'm using this for the same purpose that you want and it works perfectly fine.
I'm using this for populating city dropdown according to selection in country dropdown, HERE YOU CAN TAKE COUNTRY AS ITEM AND CITY AS MODEL
This is the country dropdown:
<?php
$countrylist=mysql_query("SELECT * FROM country ORDER BY name ASC");
echo "<select name='country' id='country' onchange=\"reload(this.form)\" title='Country e:g; United Kingdom,Pakistan'><option value='0'>Select Country</option>";
while($clist=mysql_fetch_array($countrylist))
{
echo "<option value='$clist[Name]'>$clist[Name]</option>"."<br/>";
}
echo "</select>";
?>
This is the region dropdown:
<select name="region" id="region" ></select>
Now make a seperate file named crlist.js and include it in the page having above code like this:
<script type="text/javascript" src="crlist.js"> </script>
code for crlist.js:
var request = false;
/*#cc_on #*/
/*#if (#_jscript_version >= 5)
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
request = false;
}
}
#end #*/
function fillSelect(country,path) {
var url = path+"crlist.php?country=" + country;
request.open("GET", url, true);
request.onreadystatechange = go;
request.send(null);
}
function go() {
if (request.readyState == 4) {
//if (request.status == 200) {
var response = request.responseText;
var list=document.getElementById("region");
for (i = list.length - 1; i>=0; i--) {
list.remove(i);
}
var records=response.split('|');
for (i=1; i<records.length; i++) {
//alert("rcord="+records[i]);
var record=records[i].split('*');
var region=record[0];
//alert("region="+region);
var regionid=record[1];
//alert("regionid="+regionid);
var x=document.createElement('option');
//var y=document.createTextNode(region);
x.text=region;
//x.value=region;
//alert(x.text);
//x.appendChild(y);
//list.appendChild(x);
list.options.add(x);
}
//}
}
}
function initCs(path) {
if (!request && typeof XMLHttpRequest != 'undefined') {
request = new XMLHttpRequest();
}
var country=document.getElementById('country');
country.onchange=function() {
if(this.value!="Select") {
var list=document.getElementById("region");
for (i = list.length - 1; i>=0; i--) {
list.remove(i);
}
//while (list.childNodes[0]) {
//list.removeChild(list.childNodes[0]);
//}
}
fillSelect(this.value,path);
//alert(this.value);
}
//fillSelect(country.value);
}
Now make a seperate file named crlist.php.
Code for crlist.php:
<?php
require_once 'yourconfigfile.php';
$cname = $_GET['country'];
$query="select ID,Name from city where CountryCode=(select code from country where name='$cname') Order By Name ASC";
$res = mysql_query($query) or die(mysql_error());
while($region = mysql_fetch_array($res)){
echo "<option value='".$region['Name']."'>".$region['Name']."</option>";
}
?>
Now add following script on the page having dropdowns:
<script type="text/javascript" src="crlist.js"> </script>
<script>
$(document).ready(function() {
initCs("");
});
</script>
This is my own script, and i've assumed that you have created country and region tables. But you need to tweak the queries and above code according to your db structure.
Reference to my answer: Cascade Dropdown List using jQuery/PHP
Hope this helps.

You should have an ajax call to update the select box.
JavaScript function on Item select box to call ajax.
For your reference : http://remysharp.com/2007/01/20/auto-populating-select-boxes-using-jquery-ajax/

Related

Get index value from dropdown form

I have a dropdown that is filled by a database and everything works well. However I want to pass a parameter to php based on the value of the dropdown which I can do. If I force the var to have a particular number it gets the corresponding item in the database. I'm having a problem to get the value of a dropdown. I've tried all the suggestions here in the forum and nothing works in this particular area of my code. I have it working on another piece of my code but not on this particular one and I don't know why. Here is my code:
<select id="servicos" onChange="return selectServ();">
<option value="item" class="itemoption">Serviço</option>
This is the code that is not working:
function selectServ() {
var e = document.getElementById("servicos");
var idserv = e.options[e.selectedIndex].value;
$.getJSON("http://ib.esy.es/gestao/_php/servicos_threadingpreco.php", { serv: idserv }, null).then(function(data) {
console.log(data);
var tr = data
for (var i = 0; i < data.length; i++) {
var tr = $('<tr/>');
// Indexing into data.report for each td element
$(tr).append("<td>" + data[i].preco + "</td>");
$('.table1').append(tr);
}
});
}
If I put
var idserv = "1"
It is working, however this:
var e = document.getElementById("servicos");
var idserv = e.options[e.selectedIndex].value;
Is not getting a value. The console log gives:
selectdynamicpreco.html:76 Uncaught TypeError: $(...).value is not a function
You should consider using jQuery to get the value of the dropdown:
$('#dropdown').val() will give you the selected value of the drop down element. Use this to get the selected options text.
$("#dropdown option:selected").text();
Should get you the text value of the dropdown.
This is working on another piece of the code
<script>
function selectCat(){
$('#servicos').change(function() {
$('#demo').text($(this).find(":selected").text());
});
//for textbox use $('#txtEntry2').val($(this).find(":selected").text());
var e = document.getElementById("categoria");
var servSelected = e.options[e.selectedIndex].value;
var url = "";
var items="";
if(servSelected === "1"){
url = "http://ib.esy.es/gestao/_php/servicos_threading.php";
}
if(servSelected === "2"){
url = "http://ib.esy.es/gestao/_php/servicos_sobrancelhas.php";
}
if(servSelected === "3"){
url = "http://ib.esy.es/gestao/_php/servicos_manicure.php";
}
$.getJSON(url,function(data){
$.each(data,function(index,item)
{
items+="<option value='"+item.ID+"'>"+item.servico+"</option>";
});
$("#servicos").html(items);
});
};
</script>

PHP & MySql and Ajax auto-suggest issue

I'm using bootstrap for website. I include Ajax, css and PHP to show Auto Suggestions for mp3 search. Everything is working fine but an issue happened. I tried with different way but the issue is still there.
The Issue
When type keyword it show suggestion. (OK)
When you click on keyword from suggestion it works. (OK)
But when we erase keyword and click on anywhere at page then page content reload and shown as u can see in picture.
Url of website is http://www.4songs.pk
Code in header
<script src="http://www.4songs.pk/js/jquery-1.10.2.js"></script>
<script>
$(function(){
$(document).on( 'scroll', function(){
if ($(window).scrollTop() > 100) {
$('.scroll-top-wrapper').addClass('show');
} else {
$('.scroll-top-wrapper').removeClass('show');
}
});
$('.scroll-top-wrapper').on('click', scrollToTop);
});
function scrollToTop() {
verticalOffset = typeof(verticalOffset) != 'undefined' ? verticalOffset : 0;
element = $('body');
offset = element.offset();
offsetTop = offset.top;
$('html, body').animate({scrollTop: offsetTop}, 500, 'linear');
}
</script>
<script type="text/javascript">
var myAjax = ajax();
function ajax() {
var ajax = null;
if (window.XMLHttpRequest) {
try {
ajax = new XMLHttpRequest();
}
catch(e) {}
}
else if (window.ActiveXObject) {
try {
ajax = new ActiveXObject("Msxm12.XMLHTTP");
}
catch (e){
try{
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
return ajax;
}
function request(str) {
//Don't forget to modify the path according to your theme
myAjax.open("POST", "/suggestions", true);
myAjax.onreadystatechange = result;
myAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myAjax.setRequestHeader("Content-length", str .length);
myAjax.setRequestHeader("Connection", "close");
myAjax.send("search="+str);
}
function result() {
if (myAjax.readyState == 4) {
var liste = myAjax.responseText;
var cible = document.getElementById('tag_update').innerHTML = liste;
document.getElementById('tag_update').style.display = "block";
}
}
function selected(choice){
var cible = document.getElementById('s');
cible.value = choice;
document.getElementById('tag_update').style.display = "none";
}
</script>
The 2nd issue
When auto suggestions load it also include some empty tags as you can see in picture
I take this picture as doing Inspect Elements
PHP Code are clean
<?php
include('config.php');
if(isset($_POST['search']))
{
$q = $_POST['search'];
$sql_res=mysql_query("SELECT * FROM dump_songs WHERE (song_name LIKE '%$q%') OR (CONCAT(song_name) LIKE '%$q%') LIMIT 10");
while($row=mysql_fetch_array($sql_res))
{?>
<li><a href="javascript:void(0);" onclick="selected(this.innerHTML);"><?=$row['song_name'];?></li>
<?php
}
}?>
In the function request(str) put an if statement to check if str length is greater than zero.
function request(str) {
if(str.length > 0)
{
// Your existing code
}
else
{
document.getElementById('tag_update').innerHTML = '';
}
}
In short words the problem you are describing is happping because the str parameter in the data that you send to /suggestions is empty. The server returns 304 error which causes a redirect to the root page. Your js script places the returned html into the suggestion container. And thats why you are seeing this strange view.
-UPDATE 1-
Added the following code after user request in comments
else
{
document.getElementById('tag_update').innerHTML = '';
}
-UPDATE 2- (16/07/2014)
In order to handle the second issue (after the user updated his question)
Υou forgot to close the a tag in this line of code
<li><a href="javascript:void(0);" onclick="selected(this.innerHTML);"><?=$row['song_name'];?></li>

Populating a third dropdown with a query result

I have three dropdowns. Based on the option selected in first dropdown i am populating the second dropdown using javascript.
First dropdown
<select id="continent" onchange="secondMenu(this,'country')" >
<option value="1">Asia</option>
<option value="2">Europe</option
</select>
Second dropdown
<select id="country" >
</select>
Third dropdown
<select id="population" >
</select>
My script
<script>
function secondMenu(ddl1,ddl2){
var as=new Array('Japan','China');
var eu=new Array('Germany','France');
switch (ddl1.value) {
case 1:
document.getElementById(ddl2).options.length = 0;
for (i = 0; i < as.length; i++) {
createOption(document.getElementById(ddl2), as[i], as[i]);
}
break;
case 2:
document.getElementById(ddl2).options.length = 0;
for (i = 0; i < eu.length; i++) {
createOption(document.getElementById(ddl2), eu[i], eu[i]);
}
break;
}
function createOption(ddl, text, value) {
var opt = document.createElement('option');
opt.value = value;
opt.text = text;
ddl.options.add(opt);
}
</script>
Now based on the option selected in second dropdown i want to run a mysql query and populate the third dropdown. Any help on how to go about populating the third dropdown.
Use AJAX to send a request to your server and run mysql query. Assuming, you are not using JQuery, pure AJAX looks something like this:
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var data = xmlhttp.responseText;
//populating your select
}
}
xmlhttp.open("GET", "yourmethodpath", true);
xmlhttp.send();
}
Use Ajax, I do something very similar in one of my projects, so heres an example:
$('#product_series_text', $('#product_form')).change(function() {
var $series = $(this).val();
// Ajax request to get an updated list of product models
$.getJSON(
"<?php echo url::site('product/get_model_like_series'); ?>",
{ series: $series },
function(data) {
$("#product_model",
$('#product_form')).form_utils('replaceOptions', data);
});
});
Theres a lot of jQuery there, but the idea is to have an eventlistener for a change in one dropdown, then fire off an Ajax query (which polls the database and sends back a Json list of results), which then create a dropdown list for us (just the options are changed as the dropdown list already exists)

Loading a jquery function on form submit instead on change event

I have a jQuery script that dynamically changes select menus. The script uses the function populate() everytime a change event occurs in one of the menus. I would like the same script to run after a form submit. To have an idea this is what the script looks like...
$(document).ready(function(){
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
function populate() {
if ($('#STATEID').val() == 'AK' || $('#OB_USTATEID').val() == 'DC') {
// Alaska and District Columbia have no counties
$('#county_drop_down3').hide();
$('#no_county_drop_down3').show();
}
else {
fetch.doPost('../../getCounties2c.php');
}
}
$('#STATEID').change(populate);
var fetch = function() {
var counties = $('#countyid');
return {
doPost: function(src) {
$('#loading_county_drop_down3').show(); // Show the Loading...
$('#county_drop_down3').hide(); // Hide the drop down
$('#no_county_drop_down3').hide(); // Hide the "no counties" message (if it's the case)
if (src)
$.post(src, { state_code3: $('#STATEID').val() }, this.getCounties);
else
throw new Error('No SRC was passed to getCounties!');
},
getCounties: function(results) {
if (!results)
return;
var allCities = $("<option value=\"All\">All Counties</option>");
counties.html(results);
counties.prepend(allCities);
var first = getUrlVars()["countyid"];
if (first) {
counties.val(first).attr('selected',true);
}
else {
counties.val("All").attr('selected',true);
}
$('#loading_county_drop_down3').hide(); // Hide the Loading...
$('#county_drop_down3').show(); // Show the drop down
}
}
}();
populate();
});
How can I accomplish that? Any suggestions will be highly appreciated!
Use $(element).submit(function (e) {} ); to catch a submit event. You can even fire it off, by calling $(element).submit().
jQuery docs : http://api.jquery.com/submit/

JQuery Validation not working on Ajax Control....!

Hi there I have Problem with my Code I just want to validate States which is generated from Ajax response.text
Here is the JQuery for State Field:
$(document).ready(function () {
var form = $("#addStudentfrm");
var state = $("#state");
var stateInfo = $("#stateInfo");
state.blur(validateStates);
state.keyup(validateStates);
function validateStates() {
if (state.val() == '') {
state.addClass("error");
stateInfo.text("Please Select/Enter State");
stateInfo.addClass("error5");
return false;
} else {
state.removeClass("error");
stateInfo.text("");
stateInfo.removeClass("error5");
return true;
}
}
});
Here PHP Function for Get All States in Respected Country:
public function getAllCountryStates($post){
$que = "Select * from ".WMX_COUNTRY." where code = '".$post[value1]."'";
$cRes = $this->executeQry($que);
$cResult = $this->getResultRow($cRes);
$cId = $cResult['id'];
$stateObj = new Admin;
$rdat = $post['opr'];
$rdtar = explode('.', $rdat);
$res = #mysql_fetch_row(mysql_query("Select * from ".$rdtar['1']." where id = ".$rdtar['0']));
$usts = $res['state'];
$result = $stateObj->selectQry(WMX_STATE,"country_id=$cId",'','');
$number = $stateObj->getTotalRow($result);
if($number > 0){
$getSelect ="<select name='state' id='state' class='textboxcss'>";
while($stateVal = $stateObj->getResultRow($result)){
$getSelect.="<option value='".$stateVal[state]."'>$stateVal[state]</option>";
}
$getSelect.="</select>";
}else{
if($usts!=''){
$getSelect = "<input type='text' name='state' id='state'class='textboxcss' value='$admnState'/>";
} else {
$getSelect = "<input type='text' name='state' id='state' class='textboxcss'/>";
}
}
echo $getSelect; }
In the Initial State Text box getting validate
but when the control comes with the Ajax Response Jquery wont validate it for Blank Entries
my Ajax Function:
function DataByPost(url,objId,postData,div_id){
var selId = objId.split('|');
var passData = postData;
var AJAX = null;
if (window.XMLHttpRequest) {
AJAX=new XMLHttpRequest();
} else {
AJAX=new ActiveXObject("Microsoft.XMLHTTP");
}
if (AJAX==null) {
alert("Your browser doesn't supportAJAX.");
return false
} else {
AJAX.open("POST",url,true);
AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
AJAX.onreadystatechange = function() {
if (AJAX.readyState==4 || AJAX.readyState=="complete"){
alert(AJAX.responseText);
var msg=AJAX.responseText;
var idary = new Array();
document.getElementById(selId).value = msg;
document.getElementById(selId).innerHTML = msg;
}
}
AJAX.send(passData);
}
}
//First Function
function showContent(url,arg,opr,sel_id,div_id)
{
var postData='';
var formVal=arg.split('|');
if(document.getElementById(div_id))
document.getElementById(div_id).style.display='';
if(document.getElementById(sel_id))
document.getElementById(sel_id).style.display='';
for(i=1;i<=formVal.length;i++)
var postData =postData + 'value'+i+'='+escape(formVal[i-1])+'&';
postData=postData + 'opr='+opr;
DataByPost(url,sel_id,postData,div_id);
}
I don't know exactly what is going on here without seeing the actual page, but a few things you might try:
Use jQuery to do your ajax since you're already using it. It is bug-free and cross platform, and that way you can be sure there are no bugs in the ajax part.
I would move the lines "var state = $("#state"); var stateInfo = $("#stateInfo");" inside of the function then declare the function outside of your document.ready block. That way you can be sure that every time the function gets called, it has access to the variables.
If your ajax call is replacing the input you're validating, you'll need to re-bind the events each time your ajax call finishes. With jQuery you can do this using the callback parameter.
I'm assuming number 3 is your problem, so try it first.

Categories