I would like to know if it would be possible to run an update query when an item is selected from a drop down list. The user makes a choice, a function is then called to update a particular field in a database. This will be achieved using a select box to store the options. Thanks.
echo '<td>';
echo '<select name="order_status[]" onChange = "update()">';
echo '<option value = "1" class ="pending">Pending</option>';
echo '<option value = "2" class = "approved">Approved</option>';
echo '<option value = "3" class ="disapproved">Disapproved</option>';
echo '</select>';
echo '</td>';
echo '</tr>';
Yes, it's possible. If you want the query to be run seamlessly (that is, without a submit button being pressed and the page refreshing), then you'll need to use Ajax to send the request asynchronously to your PHP script.
EDIT: The easiest thing to do is simply use jQuery's $.get() functionality in your onchange event. That way, each time someone chooses an option, jQuery will send the request to your PHP script with that option's value. The PHP script will run, and return the new data back to your jQuery, which will then use its DOM functionality to insert that data into your page.
You can do the same thing with a button. Just stick $.get() in the button's onclick event rather than in the select element's onchange event.
The jQuery site's documentation will give you relevant code examples.
EDIT 2: Okay, here's a very canned example.
First, let's think about the actual process you want to have happen on the back end. In the simplest terms, you want to take an id from user input and use that to run in a query. Pretty straight forward (using PDO for the database work):
// in a real app, you'd need to sanitize and validate the incoming id
$id = $_GET['id'];
$stmt = $dbh->prepare("SELECT * FROM table_name WHERE id = :id");
$stmt->bindParam(":id", $id);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
echo json_encode($row); // makes it jQuery friendly
Okay, so the back end is pretty simple. Now, for the font end, where the magic happens. Here's how I'd approach using both a select element and a button in order to pass the id back to the PHP script, and then handle the results:
<!-- Your HTML up to where the select and button are on your page -->
<select id="id" name="id">
<option value="1">Something</option>
<option value="2">Something Else</option>
<option value="3">Yet Another Thing</option>
</select>
<button id="btn" />
<!-- In your jQuery -->
$("#btn").click(function() {
$.get("path/to/your/back/end/script.php", { "id" : $("#id").value }, function(data) {
/* the data will be the json_encode($row) that was echoed from the PHP script.
* so, you'll need to drill into it, take the data you want, and use
* jQuery's/JavaScript's DOM manipulation tools to insert the data on your
* page
*/
}) // close $.get()
}); // close .click()
None of this is tested, and it's admittedly incomplete, but that should be more than enough to get started. Really, all you'll need to figure out is how to drill into the returned data (it's a JSON object, so it shouldn't be too bad... use a browser's web development tools to see how the data is actually formed) and insert it where you want. That, and any dumb errors I may have made above.
Hope this helps!
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 :)
I wish to update MYSQL data using text instead of using submit button.
Admin will choose option from combobox and then click at save to update the MYSQL records.
How to do this using AJAX or jquery?
My coding:
<?php
include('config.php');
$per_page = 9;
if($_GET)
{
$page=$_GET['page'];
}
//get table contents
$start = ($page-1)*$per_page;
$sql = "SELECT bookingID,eventinfo.eventTitle,boothAlias,testbook.bstatus,date, testbook.username, customer.companyName, customer.contactName from eventinfo, testbook, customer where testbook.username=customer.username AND testbook.eventID=eventinfo.eventID order by date desc limit $start,$per_page";
$rsd = mysql_query($sql);
?>
<form method="post" name="form">
<table width="800px">
<?php
//Print the contents
while($row = mysql_fetch_array($rsd))
{
$id=$row['companyName'];
$contactName=$row['contactName'];
$eventTitle=$row['eventTitle'];
//$phone=$row['phone'];
$date=$row['date'];
$status=$row['bstatus'];
$booth=$row['boothAlias']
?>
<tr><td style="color:#B2b2b2; padding-left:4px"><?php echo $id; ?></td><td><?php echo $contactName; ?></td>
<td><?php echo $eventTitle; ?></td><td><?php echo $booth; ?></td><td><?php echo $date; ?></td><td><select name='status' id='status'>
<option value='-1'>--Select--</option>
<option value='0'>Approve</option>
<option value='1'>Reject</option>
<option value='2'>Pending</option>
</select></td><td><a href=#>save</a></td>
</tr>
<?php
} //while
?>
</table>
</form>
image
This is actually really simple using jQuery. First, you have to create another PHP script that will actually run the UPDATE code. I'm not sure how much you know about AJAX requests, but you can essentially think of them as your browser opening a new tab in the background, sending the request and returning/parsing the response with JavaScript.
So, I'd write a PHP script that you can request (maybe "update_field.php" or "update_field_ajax.php") which does the actual updating. Write this script as you would if a form were being submitted from another page (ie it'll have POST and GET variables, validations, etc). There will be two main differences. First, you'll pass in the POST params with jQuery and second you won't return HTML (you can return HTML if you want - but if you're doing a simple update you really only need some sort of success or fail/error message response). I'd consider JSON for the response type. So, the PHP script is up to you to write, you'll write it just as you normally.
Next, you'll use jQuery to grab the data (GET/POST params) from the page and make a request to the PHP script you created. This isn't all that bad either. I'm not sure what you mean by "using text instead of a submit button" other than you don't want to use a submit button so I'll explain this in a somewhat abstract way. In order to get the AJAX call to run you must have something trigger it. This will be an event on the page, and that event will call a function that fires the AJAX request. Google around for information on jQuery events, but essentially when an event is fired it calls a function that you define. When that function is called we can use jQuery's post() method to create an AJAX post request. This method call will look something like:
jQuery.post('url of your script', {postVarOne: jQuery('some elt').val()}, function () {success function}, 'json');
The details of jQuery.post can be found at http://api.jquery.com/jQuery.post/
So basically write a PHP script as you normally would that returns something other than HTML signifying success/fail or a response message(unless you need to inject HTML right into the page) and then use jQuery.post (or jQuery more generic jQuery.ajax method) to have your browser request that script with the GET/POST vars you define and parse the response.
Finally, check out these tutorials for more information/code examples.
http://www.devirtuoso.com/2009/07/beginners-guide-to-using-ajax-with-jquery/
http://www.php4every1.com/tutorials/jquery-ajax-tutorial/
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
I do not know if it makes sense but i am trying to echo a hidden field in select box but does not work. How can i echo
echo "<input name='testt' type='hidden' id='testt' value='".$ver["cats_fee"]."'>";
in here:
<select size="1" name="parentcat">
<option value='0'>---- Top Category ----</option>
<?
$al=mysql_query("select * from cats where cats_parentid='0' order by cats_id desc");
while($ver=mysql_fetch_array($al))
{
echo "<option value='".$ver["cats_id"]."'>".$ver["cats_name"]."</option>";
$al2=mysql_query("select * from cats where cats_parentid='".$ver["cats_id"]."' order by cats_id desc");
while($ver2=mysql_fetch_array($al2))
{
echo "<option value='".$ver2["cats_id"]."'> > ".$ver2["cats_name"]."</option>";
}
}
?>
</select>
It looks like you're trying to send multiple pieces of data based on a user-selection. It's easier just to send the unique id (as you are already doing) then lookup the 'fee', along with any other data you need' in the script that the form sends to.
As an aside, it also looks like you are making many database calls to, effectively, get all cats back. If that's true, it's probably more efficient to just get them all with a single call and handle the hierarchy in your script.
Because both the select box, ancd an input field are form elements, you can't nest them. But because you only use hidden input fields for storing data on your page, out of sight for the user, it doesn't really matter where you place it, as long as it's inside the form.
You can't see which option the user is selecting on the client side when you are at the server side. The solution is using javascript - which is a client side language, search like this or this would help alot I think.
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