I have no idea where to begin, so if there is already an answer out there to a question like mine I would appreciate it! Basically the question says it all, Here is what I would like:
There is a drop down menu, simple drop down menu, nothing fancy. When a selection is made in that drop down menu, a php mysql query is ran where the database will be updated with that value. I have all the pieces, all I need is the code that would be able to kick it all off.
For instance when you hit submit on a form you would typically type out:
if (isset($_POST['submit']))
{
//grab information and insert into db
}
How would I do this for a drop down selection without having to click the submit button.
As has been said in the comments, you listen to the onchange event of the selectbox and either submit a form or use AJAX. This is not my point.
From a usability POV I recommend you reevaluate this proposition, if it really leads to a database update: Ever used the mouse wheel to scroll, while accidently having the focus on a selectbox? Jackpot! You just changed your DB settings without being aware of it.
So using onchange on a selectbox to kick off something, that is immediately visible is IMHO a good thing - you'll know, when you triggered it. Changing a DB setting with no feedback other than the select box changing value is IMHO a bad thing. Or an accident waiting to happen.
you should be looking for something like this
<form id="testform">
<select id="yourselect" name="yourselect" onChange="updateDb()">
<option value="somevalue">Please select</option>
<option value="somevalue1">Something</option>
</select>
</form>
you Javascript function will look like this
function updateDb() {
// I am using jquery for ajax
$.post("yourserverhandle.php", $("#testform").serialize());
}
and this is how your "yourserverhandle.php" looks like
<?php
$query = "update yourtable set something='".mysql_escape_string($_POST["yourselect"])."' where id='something'";
.... mysql connect, execute
?>
$("#DDL_ID").change(function(){
$.ajax({
url:'/some.php',
type:'POST',
data:{submit:$(this).val()},
success:function(data){
//do something here if the server return anything
},
error:function(){
console.log("something bad happened");
}
});
});
on the php side
if (isset($_POST['submit']))
{
//grab information and insert into db
}
P.S. always sanitize the input see mysql_real_escape_string
Related
I have a Jscript Query.
I have done a bit of reading and found out that AJAX is just a side server for a lfash script that can be used on Linux with php. (please correct me if I have interperated that wrong)
I have no knowledge on how scripts work so this is new, I have tried a couple of different tries but no luck.
I have one drop down box (Box1) (populated from Database)
I have another box (Box2) for a calculation to insert into my database for other uses on ohter parts of hte site.
I need the Box2 to change the figure when someone changes Box1 dropdown before hitting the submit button.
I think because I have the calcualtion this is getting me stuck... Code is as below... Can someone please help me figure out (I think I need some form of Script to do this.) the answer...
Box1
<td><p>selection 1</p>
<select id="t1_type" name="t1_type">
<?php $result = mysql_query("SELECT * FROM `t2` ORDER BY t2_value");
while($valuerow = mysql_fetch_array($result)){
echo '<option value="'.$valuerow['t2_name'].'">'.$valuerow['t2_name'].'</option>'; } ?>
Box2
<input name="t1_value" id="t1_value" value="
<?php
$var1 = $row_value['t2_value'];
$var2 = $row_dropdown['t1_number'];
$total = round ($var2 * $var1);
echo "" . $total . "";
?>" />
I hope this is all the code you need, (Let me know if more required)
What it needs to do is show new calculation whenever someone changes the box1 option BEFORE the submit button is clicked, so it submits the correct calculation to the database for future use.
I think it would need pretty much "t2_value" from box2 to change when ever "t2_name changed from box1.
And once again the best link to learn about the solution. (Learnt about Joins now from my last question!! Almost a intermediate user. ;-) )
Edit :
I saw that your second box was a textbox I believe, if thats the problem then you should do something like this
<select id="t1_type" name="t1_type" onchange="change(this);">
<?php
$result = mysql_query("SELECT * FROM `t2` ORDER BY t2_value");
while($valuerow = mysql_fetch_array($result))
{
echo '<option value="'.$valuerow['t2_name'].'">'.$valuerow['t2_name'].'</option>';
}
?>
</select>
This defines your <select> box like you did in your question.
Add an onChange event into your first <select> and then create a function to handle to onChange event. An onChange event fires whenever the user changes the item in the <select> element.
Javascript :
( put this part of the code above the </head> )
<script language="javascript" type="text/javascript">
function change(element)
{
// do here whatever you want
// you can change the value of the <input> box with :
// document.getElementById(element.id).value = your_value
// If you want to see if this part works, then try adding this :
// alert("It works!");
// If you want to get the text of the item which has been selected in Box1 use :
// $("#t1_type option:selected").text();
}
</script>
Note: because PHP is server side, you can't update your Box2 dynamically without a page refresh, Javascript however is Client Side and CAN do this.
Note : the $("#t1_type option:selected").text(); code requires you to include the jQuery library into your script. Be sure to convert this variable to a float, int or double if you want to calculate with it, else the outcome will give NaN (Not a Number)
Tutorial on including jQuery Libary :
http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery
If you're new to JavaScript, you should try some tutorials. The ones at w3Schools.com helpt me alot, but some people say they're not always correct, but anyhow, read some stuff about Javascript to actually know what you are doing, instead of copypasting code :)
Ok... First off, I know this isn't a new question.
But, for some reason none of the suggestions Google has found for me (dating back to the begining of time even) are working. So, please bear with me.
Let's say, I have a script structured something like this:
<?php
try {
print "<table><form id='menu' action='index.php' method='POST'><tr>";
print "<td>Select A Fruit</td><td><select name=fruit>
<option value=''></option>
<option value='apple'>Apple</option>
<option value='orange'>Orange</option>
<option value='pear'>Pear</option></select></td></tr>";
print "<tr><td><input type='submit' name='submit' value='Submit'></td></tr></form></table>";
if (isset($_POST['submit'])){
if (!empty($_POST['fruit'])){
//Do whatever the form is supposed to trigger.
}
else {
//Nothing selected; handle however makes sense.
}
}
}
catch(Exception $e) {die( print_r( $e->getMessage() ) );}
?>
And instead of using the button, I want it to submit the form as soon as an option is selected.
Based on my searches, the textbook answer appears to be to modify the Select tag with an onchange attribute calling a JavaScript method like so:
<select name='fruit' onchange='document.getElementById('menu').submit()'>
or the short form:
<select name='fruit' onchange='this.form.submit()'>
But here is where I'm stuck...
None of the posts I found explain where you tell the browser/interpreter to drop out to JavaScript to make that work. So, this change does nothing for me.
What am I missing here?
I would get away from the dom level 0 handler and set the select's onchange handler to a function that grabs your form, and calls submit on it.
document.getElementById("yourSelectId").onchange = function() {
document.forms["formsId"].submit();
};
I'm showing you a more robust way of adding event handlers to dom elements. Instead of saying onchange="blah()" you can set up a body onload function that'll run when your dom is ready, then you can use JavaScript to add your handlers:
<body onload="init()">
function init() {
document.getElementById("yourSelectId").onchange = function() {
document.forms["formsId"].submit();
};
}
Or, you can skit the ugly <body onload="init()"> altogether and just put the code
document.getElementById("yourSelectId").onchange = function() {
document.forms["formsId"].submit();
};
in a regular script block at the bottom of your body
Your markup isn't valid, a table-element cannot have a form as child-element(wrap the form around the table)
Choose another name for the submit-button, otherwise you will receive an error in IE when calling submit()
I would suggest using an event listener rather than adding the attribute to your code. Also, it is recommended to have the static page display the submit button, and simply remove it via javascript after the page loads.
element.addEventListener Example
<script type="text/javascript">
document.getElementById("yourSelectId").addEventListener("change", function(){document.forms["yourFormId"].submit();});
</script>
To read more about element.addEventListener (esp. to see why it's important to use it), check out the article on element.addEventListener at MDN.
How javascript works in onchange attribute
But here is where I'm stuck... None of the posts I found explain where you tell the browser/interpreter to drop out to JavaScript to make that work. So, this change does nothing for me.
Attributes such as onchange, onclick, etc (notice "on" at the beginning) parse the value as javascript. Ergo, that is where you are telling the browser to use javascript to make it work :)
I have two select box and the second select box value is dependent on the first select box. So basically what I am trying to do is that after a user makes a selection on the first select box, it will then store this value of the first select box as a variable. Then it will query my database to populate the second select box, based on the first selected value. Question is, how do I pass in the var I have in the first select box to PHP? I've read other post and people said it's impossible, but if it is then how do people do this? AJAX?
If I understand correctly, then yes, using AJAX is really your only choice.
Indeed, you can, with AJAX, call something like 'getSelectionData.php?data=' + select1.value, which returns a JSON array of data based on the selection in the first select box. You then parse the data and enter it into the second select box.
Add a onchange event listener to the first select box:
document.getElementById("select1").addEventListener("change", function(ev){
var yourstoredvariable = this.value;
someFunctionThatCallsAjax(yourstoredvariable);
}, true);
I assume that you have a Country/City dropdowns, You can do it in two ways, the good AJAX way and the bad way (refresh page on change), I'm gonna describe the good way in jQuery, or at least what I see it good.
this is the client-side (i.e. client) code:
<select id="country">
<option value="1">Canada</option>
<option value="2">UK</option>
</select>
<select id="city" disabled="disabled"></select>
<script type="text/javascript">
$('#country').change(function(){
$('#city').load('/ajax-city.php', {id: $(this).val()});
});
</script>
This is the ajax-city.php code (server):
<?php
$countryId = $_REQUEST['id'];
$cities = array(); // Get it from db, using mysql_query or anything you want to use
foreach($cities as $city) {
echo "<option id=\"{$city['id']}\">{$city['name']}</option>";
}
PS. you would need to include jQuery in your html code, and of course put the two files in the same directory (or change the $.load path).
This particular code is not tested, I've just written it. But it usually works fine to me this way.
You will have an onchange event on the first <select> that will query the server using Ajax with the value of the selected <option> that will return the <option> elements with which to populate the 2nd <select> element.
Question is, how do I pass in the var I have in the first select box to PHP?
I see no problem here.
Just usual, an ordinary html form using GET method.
What's so big about it?
If I see correct you're using Jquery. So you can do this like this:
$('#idOfSelectBox1').change(function(){
jQuery.ajax({
type: "GET",
url:"yourdomain.com/script.php",
data:"selectBox:'"+$('#idOfSelectBox1').val()+"'",
success:function(result){
//do smth with the returned data
}
});
});
in the script.php do your magic and echo what you want to pass back to js
How do you live update the content of drop down 2 based on the selection made in drop down 1 in a PHP based web form?
Would appreciate any code examples to work from.
Many thanks!
You are going to have to use AJAX, I would recommend jQuery's abstraction.
e.g.
<select id="sel1">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select id="sel2">
</select>
<script type="text/javascript">
$('#sel1').change(funciton(){
$.ajax({url: 'fetchSel2.php',
data:{sel1:$('#sel1').val()},
success:function(data){
$('#sel2').html(data);
}
});
});
</script>
This presumes there is a 'fetchSel2.php' that is ready to serve the options for the second select.
e.g.
function getSecondOptions($sel1){
$r=mysql_query(RELEVANT_QUERY);
$opts='';
if($r && mysql_num_rows($r)>0){
while(list($label,$val)=mysql_fetch_row($r)){
$opts.='<option value="'.$val.'">'.$label.'</option>';
}
}
return $opts;
}
if(isset($_GET['sel1'])){
echo getSecondOptions($_GET['sel1']);
}
exit;
For live update, you need to use AJAX and require JS enabled browser. If the user-browser don't support JS or JS is disabled, the only option is to submit the form and reload the whole page with the updated option in the 2nd dropdown. If you want the JS code to perform AJAX, can you kindly tell me the JS library you want to use, so I can provide the code accordingly.
What you are looking for is a cascading dropdown list. This is done using AJAX triggered in sequence by each dropdown. Here is an example via Google (http://codestips.com/php-ajax-cascading-dropdown-using-mysql/), note I'm not endorsing this link, it's just the first reasonable result.
I recently did this with jQuery http://jsfiddle.net/tBrXt/1/
You have these options:
Use AJAX if you don't want the form to refresh and update parts of
the form.
If you don't want to use ajax and can bear with refreshing the whole
form, you can capture the onChange event of the drop down using
javascript.
If the user does not have javascript enabled, the above 2 methods
will fail. Therefore, it is best to include a button users can click,
which will ask the PHP side to rerender the form.
My personal preference is to use the last method as a fall back for those who do not have javascript enabled. Then use the first method (AJAX) to progressively enhance the form for those that have javascript.
I used the code below to remove a selected item from drop down, but when I remove one, the other item pops up. For example, if these are my options: "guns, cars, money", as I select and delete guns, cars and money remains. However, if I select cars and delete it, the deleted guns options pops up again. It is frustrating.
<?php
$opts = array("guns","knives","ammo");
$selected = array($_POST['selectMenu']);
$revisedOpts = array_diff($opts,$selected);
?>
<form method="post">
<select name='selectMenu'><?php
foreach($revisedOpts as $v) {
echo "<option>".$v."</option>";
}
?></select>
<input onclick="array_diff()" name="Collect" type="submit" value="submit" />
</form>
PHP only acts when the page is loaded, and you load the same code over and over. In order for previously deleted options to stay deleted, you need some kind of data persistence (like a database). Otherwise, you can use javascript to manipulate the select options on the client side browser. Here is a good discussion
If you must bind the action to onclick() and receive the event on the server side, then you will need to use an AJAX call. The onclick calls a separate PHP script which deletes the option and returns some kind of success message.
you want to have a look at some js code to do this. look at something like that http://www.mredkj.com/tutorials/tutorial_mixed2b.html
use jquery
jquery auto suggestion