JavaScript - Prepopulating Two Dropdownmenus From Mysql
Hi,
I'm using MySQL/PHP on the server side and I have a database with customers and customer specific products. I have a form where i would like to have a dropdown menu for both customers and products. Customer menu is prepopulated from DB and depending on that selection a new SQL-query will be made with that customers name and ultimately populate the next menu with specific customers products. I am not familiar with JS so im kind of lost with it. I suppose i have to pass a queried customer array from PHP/HTML to JS and so forth. Or is JS a proper tool for this problem in the first place? Below is some simple code I have. Code: . .. ... while ($row=mysql_fetch_array($result)) { $customer=$row["customername"]; $options.="<OPTION VALUE=\"$customer\">".$customer.'</option>'; } echo("<SELECT NAME=customername><OPTION VALUE=0><?=$options?>< /SELECT>"); ... .. . Cheers, Bigfinn Similar TutorialsHi all, I'm trying to make a digital order sheet for my brother. I made him a database in phpmyadmin, that has 2 tables, called Dishes and Cables. 2 different PHP sites call those tables, and pull the information. I then have an HTML page set to display that information. Here's what it looks like. <html> <head> <script type="text/javascript" > var data = null; var data2 = null; function GETSTUFF(stuff) { function buildList() { function showQuantity() { var supplier = document.getElementById('materials').options[document.getElementById('materials').selectedIndex].value; var amount = 0; for (var i=0;i<data.length;i++) { if (data[i]['Supplier'] == supplier) { amount = (data[i]['Quantity']); } } document.getElementById('quantity').innerHTML = 'Quantity : '+amount; var type = document.getElementById('materials').options[document.getElementById('materials').selectedIndex].value; var amount2 = 0; for (var i2=0;i2<data2.length;i2++) { if (data2[i2]['Type'] == type) { amount2 = (data2[i2]['Quantity (Boxes)']); } } document.getElementById('quantity').innerHTML = 'Quantity (Boxes) : '+amount2; } </script> </head> <body onload="setTimeout('buildList()' ,100)"/> <center> <img src="images.jpg" width=125px height=125px/> <br> <font size="8" color="grey" face="purisa">Home </font> <font size="8" color="red" face="purisa"> Communications</font> <br> <font size="5" color="grey" face="purisa">Order </font> <font size="5" color="red" face="purisa"> Sheet</font> <br> <table border="3" width="100%"> <tr> <th>Material:</th> <th>Quantity in stock:</th> <th>Quantity needed:</th> </tr> <tr> <td> <select id="materials" onchange = "showQuantity()"> <option disabled>Select</option> </select> </td> <td id="quantity"/> <td> <form> <input type = "quantityNeeded" /> </form> </td> </tr> </table> <br> <input type = "button" value="Submit"/> </center> </body> </html> My idea is that if the stuff from Dishes is selected, then display the quantity for that, and if the stuff from Cables is selected, display the quantity for that. This obviously involves an if statement, but nothing I can think of makes it work. I'd really appreciate help on this I have been following a tutorial for an image gallery, i can upload images and use gd to create thumbnails that when clicked display the full sized image, but the full sized image is to big to fit in my design, i have managed to get the rel="lightbox" attached to the thumbnails as they are displayed but it wont load the full image, the loading ring just keeps going round, does anybody know how to fix this? is it even possible. BTW i am a complete beginner so please be gentle.
Hi! I'm using this javascript and php/MySQL: http://www.dynamicdrive.com/dynamici...ects/index.htm When I make a selection in all 3 lists I have a button that saves the selections in my MySQL database, like this: set1, Toyota, Cars, Camry Then I want to be able to select set1 in a list and press an "Edit" button that retrieves these 3 selections and auto selects them in the list. How is this possible? Thanks in advance Vigour Hi to all, i have a javascript on my websute that i want to hide from all users , i want put it on a database mysql and recall it, in order to hide the code, how I can make? you have some idea? please help me. Hi Guys, What i'm attempting to do is update a mysql database through a javascript function, so when i click on <a href='onclick="return myfunction();"'></a> PHP Code: function myfunction(affURL) { if (confirm('You will now be redirected to the purchase page, continue?')) { // Need a way to log things, update mysql with vars passed through var l = screen.availWidth / 2 - 450; var t = screen.availHeight / 2 - 320; var win = window.open(affURL, 'payPopupMain', 'width=900,height=650,left='+l+',top='+t+',scrollbars=1'); } else { // Send them back to the payment.php page window.location('payment.php'); } } The code above opens up a browser for the user, but i also want to update mysql without the user seeing any of it, so all they see if the browser popup, and behind the scenes the script updates mysql with a few variables any help on what i would need to do would be appeciated. thanks guys Graham Hello Im using javascript and cookies to send to another page in my site some variables In the other page i recieve them like that : Code: <script language="JavaScript"> if (widget_array != ""){ for (i=1; i < widget_array.length; i++){ document.write("<h3>" + widget_array[i] + "</h3>"); }//ends diplay FOR }//ends widget display if(ninja_array != ""){ for (i=1; i < ninja_array.length; i++){ document.write("<h3>" + ninja_array[i] + "</h3>"); }//ends FOR }//ends ninja display </script> Now my question is ....(and this is the php - sql question) how can i make the variable the i passed to stay a variable , e.g. variable page 1: id=123 *i entered the number 123 into the cookie variable page 2: now this page will show me ALL the array ( 123...134...156...etc...) but i dont want it to print it on the screen i just want to get variables that i can use php-mysql e.g. $id=123 in order to print the specific data from my data base hope u got it.... Danny Hello I'm trying to create a graph that will accept 1 or multiple data sets depending on what the user selects. How can I add get the data into the graph using a loop? I want it to add a line for each selection. Thanks // Graph Data ############################################## var graphData = [{ // Visits data : <?php echo '['.implode($data).'],'?> color: '#71c73e' }, { // Visits data : <?php echo '['.implode($data_1).'],'?> color: '#red' }, ]; Hi all, I'm having some issues with getting a html form to send data through to my MYSQL database. JS is the one part of the script that I'm least sure about, so I assume the issue lies there... All the data from the text fields in the form go through to the MySQL table fine, but the data from the drop down box and checkbox doesn't make it... So, the html dropdown and checkbox code from the form is: Code: <label for="lettertype" id="lettertype_label">I want my letter to be: </label><br> <select id="lettertype" name="lettertype"> <option value="0"></option> <option value="public">Public, though Anonymous</option> <option value="private">Private</option> </select><br> <label class="error" for="lettertype" id="lettertype_error">Would you like your letter to be public or private?</label> <br> <label for="terms" id="terms_label">I understand thde terms and agreements...</label><br> <input type="checkbox" name="terms" value="Yes" /><br> <label class="error" for="terms" id="terms_error">We know no one ever reads these things, but we need to you at least pretend...</label> When submit is clicked, it calls the following javascript: Code: $(function() { $('.error').hide(); $('input.text-input').css({backgroundColor:"#F6F6F6"}); $('input.text-input').focus(function(){ }); $('input.text-input').blur(function(){ $(this).css({backgroundColor:"#F6F6F6"}); }); $(".button").click(function() { // validate and process form // first hide any error messages $('.error').hide(); var letter = $("textarea#letter").val(); if (letter == "") { $("label#letter_error").show(); $("textarea#letter").focus(); return false; } var firstname = $("input#firstname").val(); if (firstname == "") { $("label#firstname_error").show(); $("input#firstname").focus(); return false; } var surname = $("input#surname").val(); if (surname == "") { $("label#surname_error").show(); $("input#surname").focus(); return false; } var email = $("input#email").val(); if (email == "") { $("label#email_error").show(); $("input#email").focus(); return false; } var lettertype = $("select#lettertype").val(); if (lettertype == "0") { $("label#lettertype_error").show(); $("select#lettertype").focus(); return false; } var terms = $("input#terms").val(); if (terms == "") { $("label#terms_error").show(); $("input#terms").focus(); return false; } var dataString = '&letter=' + letter + '&firstname='+ firstname + '&surname=' + surname + '&email=' + email + '&lettertype' + lettertype + '&terms' + terms; //alert (dataString);return false; $.ajax({ type: "POST", url: "../php/emailform.php", data: dataString, success: function() { $('#replace').html("<div id='message'></div>"); $('#message').html("<br>") .append("") .hide() .fadeIn(1500, function() { $('#message').append("<img id='mailconfirm' src='images/mailconfirm.png' /><br><br>"); }); } }); return false; }); }); runOnLoad(function(){ $("input#firstname").select().focus(); }); Then in terms of the PHP script, this is the excerpt: Code: $letter = $_POST['letter']; $firstname = $_POST['firstname']; $surname = $_POST['surname']; $email = $_POST['email']; $lettertype = $_POST['lettertype']; $terms = $_POST['terms']; $timestamp = date( 'Y-m-d'); $sql = "INSERT INTO ToBeEmailed (letter, firstname, surname, email, lettertype, terms, timestamp) VALUES ('$letter', '$firstname', '$surname', '$email', '$lettertype', '$terms', '$timestamp')"; If anyone could offer any advice that'd be great! Cheers in advance... I am currently trying to put together a AJAX search that searches a MySQL database using PHP. I have created the below scripts. I cannot get it to function properly. Essentially I want someone to type in a partial search term and click submit and see the results. The purpose of this is for it to become part of a mobile app. Any help would be appreciated. Thank you! HTML: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <style type="text/css"> body{font-family:'Lucida Grande', Verdana, sans-serif;; font-size:14px; color:#666666;} h2{color:#000000; margin-bottom:20px;} h3{color:#000000; font-size:14px;} input{font-size:16px; color:#444444;} a:link, a:visited, a:hover{color:#0033CC;} a:hover{text-decoration:none;} div.searchInput{padding:8px; background:#DEDEDE; clear:both;} div.footer{padding:6px; border-top:solid 1px #DEDEDE; font-size:10px;} #msg{background:#FFFFCC; margin-bottom:10px; padding:4px; display:none;} </style> <script type="text/javascript"> function showProducts(str) { if (str=="") * { * document.getElementById("search-result").innerHTML=""; * return; * } if (window.XMLHttpRequest) * {// code for IE7+, Firefox, Chrome, Opera, Safari * xmlhttp=new XMLHttpRequest(); * } else * {// code for IE6, IE5 * xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); * } xmlhttp.onreadystatechange=function() * { * if (xmlhttp.readyState==4 && xmlhttp.status==200) *** { *** document.getElementById("search-result").innerHTML=xmlhttp.responseText; *** } * } xmlhttp.open("GET","search.php?q="+str,true); xmlhttp.send(); } </script> </head> <body> <form id="searchForm" name="searchForm" method="post" action="javascript:searchNameq();"> <div class="searchInput"> <input name="searchq" type="text" id="searchq" size="30" onkeyup="javascript:showProducts()"/> <input type="button" name="submitSearch" id="submitSearch" value="Search" onclick="javascript:showProducts()"/> </div> </form> <h3>Search Results</h3> <div id="msg">Type something into the input field</div> <div id="search-result"></div> </body> </html> PHP: <?php $q=$_GET["q"]; //connect to the database mysql_connect("christianbrogers.db.5646816.hostedresource.com","christianbrogers","GHbn123"); mysql_select_db("christianbrogers"); //explode our search term into separate words $search_exploded = explode(" ",$search); foreach($search_exploded as $search_each) { //construct the query $x++; if ($x==1) $construct .= "name LIKE '%$search_each%'"; else $construct .= " OR name LIKE '%$search_each%'"; } //echo out the constructed query $construct = "SELECT * FROM products WHERE $construct"; $run = mysql_query($construct); $foundnum = mysql_num_rows($run); if ($foundnum==0) echo "No results found."; else { while ($runrows = mysql_fetch_assoc($run)) { //get data $name = $runrows['name']; echo $name; ?> From what I know, it's not possible. I am working on a site where a calculation has to be performed. The calculation is (exercise cal burned X current weight X time spent). The problem is that this information is stored in a database within phpmyadmin. So, my question is: is there a workaround for that? if so, what is it? if not, what is the best way for me to extract that information in the database to setup the calculation? I was thinking of using an array, but there are 30+ exercises listed, each with different values for the calories burned. What should I do?
I want to use a database query to grab all of a member's friends from a table in order to add the friend's email address to a form, to ready it for POSTing. I am using the jquery ui, so on my form.php page, I have the script and html: Code: <script> $(function() { $( "#friendsearch" ).autocomplete({ source: "search.php", minLength: 2, select: function( event, ui ) { log( ui.item ? "Selected: " + ui.item.id + " " + ui.item.value : "Nothing selected, input was " + this.value ); } }); }); </script> <form>... <input id="friendsearch" /> </form> And on my search.php I have: Code: //code to connect to database.... etc $query = " //this code goes through a table LEFT JOIN to grab a list of the logged-in member's friends' info (id, email, first name, last name) " $sql = mysql_query($query); while($row = mysql_fetch_array($sql)) { $fid = $row["id"]; $firstname = $row["firstname"]; $lastname = $row["lastname"]; $email = $row["email"]; echo $fid <br /> $f_firstname <br /> $f_lastname <br /> $email <br /> "; The "echo" above works. It lists out all the info perfectly, so I know my query is good. The problem, I am having, is with what comes next in the search.php: Code: $q = strtolower($_GET["term"]); // supposed to do something with $q here (not sure what!) $return = array(); while ($row = mysql_fetch_array($query)) { array_push($return,array('id'=>$row['firstname'],'value'=>$row['lastname'])); } echo(json_encode($return)); This is the part that's suppose to work with the jquery autocomplete. I know it's wrong, but I need to know how I can fix it to do the following: 1) when the user starts typing the first name or last name of the friend, auto-complete shows a drop-down list of firstname lastname. 2) once the friends' names are placed in the input box, on submit, i want to POST the friends' email addresses (not their name)! Complex, I know... Any help would be much appreciated! Thanks, June I wish to have a user list updated every 20 seconds or so with the users that are still online. I have the time(); stored in the database with their usernames, how do i get this uaing JavaScript. Ok so i am trying to make 3 dropdowns based off a mysql table. and the 3 dropdowns need to be based off of the previous dropdown. i.e Source, School, Sub. Select Source, and the schools in dropdown 2 are based off of the source they selected, and when they select a school, all the sub cats for that school are in the sub category dropdown. It seems like a simple concept, but i've google'd EVERYWHERE and notihng. I have the 3 dropdown's pulling from my database perfectly. i just cannot base the next dropdown on the previous selection! I know nothing of javascript..im a front end designer with little php/mysql. I've read that Ajax is the way to go, so here i am ! any tutotials, links or sample script layouts i can use would be amazing! Thank you! jt First off, I'd like to say that I do not know much javascript. I am building a rather intensive website for tutorial purposes, and so far it has required me to become quite familiar with html5, css, php, and mysql. However, I've avoided javascript like the plague due to how different it seems from the rest. Lets just say, I'm confused. I've scoured the net looking for a similar tutorial on how to create a pop-up window onclick for a link. This is what I currently have it doing: Firstly, I query and display the DB, referencing images based on an incremental variable. I really want to make it all automatic...in the sense, that when I update the database with a new "Structure" it will automatically apply itself to the page without me having to edit html/css/js/php/etc. It all seems to be working fine, except when I click on the second listing. It refers to the same div (Town Center), because, I assume, the divs are identically labeled, and it refers to the first. Here is my code: This is my Callstructures.php file. Code: <?php $query = "SELECT str_name, str_imageloc, str_infoloc FROM structures"; $result = mysql_query($query) or die ("Error in query: $query. ".mysql_error()); $i = 0; if (mysql_num_rows($result) > 0) { while(list($str_name, $str_imageloc, $str_infoloc) = mysql_fetch_row($result)) { echo "<li>"; echo "<a href='#' onClick='javascript: loadPopup()';>"; echo "<img src='$str_imageloc' title='$str_name' longdesc='$str_infoloc' alt='stralt text' class='image$i'>"; echo "</a>"; echo "</li>"; echo "<div id='popupContact'>"; include ($str_infoloc); echo "</div>"; $i++; } } ?> This is my main page: Structures.php Code: <body> <div id =allstr> <ul> <?php include 'gamephp/callstructures.php'; ?> </ul> <div id="backgroundPopup"></div> </div> </body> </div> </html> And here is the JavaScript I am using, popup.js: Code: /***************************/ //@Author: Adrian "yEnS" Mato Gondelle //@website: www.yensdesign.com //@email: yensamg@gmail.com //@license: Feel free to use it, but keep this credits please! /***************************/ //SETTING UP OUR POPUP //0 means disabled; 1 means enabled; var popupStatus = 0; //loading popup with jQuery magic! function loadPopup(){ //loads popup only if it is disabled if(popupStatus==0){ $("#backgroundPopup").css({ "opacity": "0.7" }); $("#backgroundPopup").fadeIn("slow"); $("#popupContact").fadeIn("slow"); popupStatus = 1; } } //disabling popup with jQuery magic! function disablePopup(){ //disables popup only if it is enabled if(popupStatus==1){ $("#backgroundPopup").fadeOut("slow"); $("#popupContact").fadeOut("slow"); popupStatus = 0; } } //centering popup function centerPopup(){ //request data for centering var windowWidth = document.documentElement.clientWidth; var windowHeight = document.documentElement.clientHeight; var popupHeight = $("#popupContact").height(); var popupWidth = $("#popupContact").width(); //centering $("#popupContact").css({ "position": "absolute", "top": windowHeight/2-popupHeight/2, "left": windowWidth/2-popupWidth/2 }); //only need force for IE6 $("#backgroundPopup").css({ "height": windowHeight }); } //CONTROLLING EVENTS IN jQuery $(document).ready(function(){ //LOADING POPUP //Click the button event! $("#button").click(function(){ centerPopup(); loadPopup(); }); //CLOSING POPUP //Click the x event! $("#popupContactClose").click(function(){ disablePopup(); }); //Click out event! $("#backgroundPopup").click(function(){ disablePopup(); }); //Press Escape event! $(document).keypress(function(e){ if(e.keyCode==27 && popupStatus==1){ disablePopup(); } }); }); And the CSS for the popup: Code: /* pop up css */ html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td { border:0pt none; font-family:inherit; font-size:100%; font-style:inherit; font-weight:inherit; margin:0pt; padding:0pt; vertical-align:baseline; } body{ background:#fff none repeat scroll 0%; line-height:1; font-size: 12px; font-family:arial,sans-serif; margin:0pt; height:100%; } table { border-collapse:separate; border-spacing:0pt; } caption, th, td { font-weight:normal; text-align:left; } blockquote:before, blockquote:after, q:before, q:after { content:""; } blockquote, q { quotes:"" ""; } a{ cursor: pointer; text-decoration:none; } br.both{ clear:both; } #backgroundPopup{ display:none; position:fixed; _position:absolute; /* hack for internet explorer 6*/ height:100%; width:100%; top:0; left:0; background:#000000; border:1px solid #cecece; z-index:1; } #popupContact{ display:none; position:fixed; _position:absolute; /* hack for internet explorer 6*/ height:384px; width:408px; background:#FFFFFF; border:2px solid #cecece; z-index:2; padding:12px; font-size:13px; } #popupContact h1{ text-align:left; color:#6FA5FD; font-size:22px; font-weight:700; border-bottom:1px dotted #D3D3D3; padding-bottom:2px; margin-bottom:20px; } #popupContactClose{ font-size:14px; line-height:14px; right:6px; top:4px; position:absolute; color:#6fa5fd; font-weight:700; display:block; } #button{ text-align:center; margin:100px; } Should I keep this code? Is there anyway to make it work? My thought process is to change "callstructures" to include a variable ($i is already there) that creates a bunch of unique div ids Code: echo "<div id='popupContact$i'>"; Then in the JS, somehow alter it so it recognizes the change. If not, are there any tips, or possible links to tutorials and info on how I can figure this out. With much appreciation, Thanks! Hi, I was going through this tutorial: http://www.electrictoolbox.com/json-...ery-php-mysql/ and I changed it round slightly, I would like the first select box to be Search by either Town or County - Having links would easier?! http://www.mypubspace.com/dashnew/ So, when a user selects Town, the PHP selects the Towns or if the user selects County, then show the Counties list I am currently getting the following error: $ is not defined [Break On This Error] $(document).ready(function() { here is my HTML Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Untitled Document</title> <script language="javascript" type="text/javascript"> function populateFruitVariety() { $.getJSON('search-by.php', {fruitName:$('#fruitName').val()}, function(data) { var select = $('#fruitVariety'); var options = select.attr('options'); $('option', select).remove(); $.each(data, function(index, array) { options[options.length] = new Option(array['variety']); }); }); } $(document).ready(function() { populateFruitVariety(); $('#fruitName').change(function() { populateFruitVariety(); }); }); </script> </head> <body> <form> Search by: <select name="name" id="fruitName"> <option>Please Select</option> <option id="Town">Town</option> <option id="County">County</option> </select> Variety: <select name="variety" id="fruitVariety"> </select> </form> </body> </html> PHP Code: <?PHP $dsn = "mysql:host=xxx;dbname=[xxx]"; $username = "[xxx]"; $password = "[xxx]"; $pdo = new PDO($dsn, $username, $password); $rows = array(); if(isset($_GET['Town'])) { $stmt = $pdo->prepare("SELECT rsTown FROM pubs WHERE name = ?"); $stmt->execute(array($_GET['rsTown'])); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); } if(isset($_GET['County'])) { $stmt = $pdo->prepare("SELECT rsCounty FROM pubs WHERE name = ?"); $stmt->execute(array($_GET['rsCounty'])); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); } echo json_encode($rows); ?> Please help I am trying to figure out a way to have a page redirect if the mysql connection fails. The issue is that the page is already loaded and the only time this would be needed is if the user tries to perform operations on a loaded page after the session runs out. So basically, I have a page that will allow you to search for an item using ajax, then select an item and press add which will place the item in another table displaying detailed information. Both operations connect to the database using SESSION variables to save the connection information. My goal is to use the "or die()" method to print something that will force a redirect because this could happen in a number of places in the site and I want to try and get them all in one swipe. Here is what seemed like it would be the most promising: Code: $conn = mysql_connect($_SESSION['host'], $_SESSION['username'], $_SESSION['password']) or die("<script>location.href= '../login.php'</script>"); Unfortunately the javascript never runs.... I tried putting alerts also and nothing, but with firebug I can see they are printed. Any idea how I can ensure that the javascript is executed? Thanks in advance. Hi, I am using the jQuery UI Datepicker - Event Search. as a booking-system. I want to automatically disable days from my MYSQL table in my booking-system (datePicker). So, here is the deal: In my website, there is booking-system, you can reserve a room from datePicker. I have successfully created a PHP, which sends the information (name, room, date etc.) to my MYSQL. Then I have successfully created a datesonly.php, which prints only a dates from my MYSQL. So now I have to make javascript (?) which reads dates from datesonly.php and draws a booked-note to my datePicker at website (so people can see which days are booked --> no double-books!). Booked-note should be something like that day in datePicker is red. Thank you! And sorry for my bad english, I'm from Finland. EDIT: Sorry, the title should be: Disabling days from datePicker via JavaScript Hi, I have the below code (in a smarty .tpl file), but would like to automate it with data from MySQL DB and PHP So for example if I was to add another gift_id radio box etc.. in MySQL it would add on to the end extending the if statement to make sure a radio box has been picked. if ((form.gift_id[0].checked == false) && (form.gift_id[1].checked == false) && (form.gift_id[2].checked == false)) { ErrorCount++; But the problem is I am not sure how to do this, any ideas? Thanks. ps. sorry if I posted this in the wrong forum, wasn't sure where to put it |