how to update and post the value of checkbox from ajax call - php

i retrieved data from mysql table into html page i.e
$query="select * from student";
$result=mysql_query($query)or die(mysql_error());
while($rs=mysql_fetch_array($result))
{
?>
<tr>
<td align="center"><?php echo $rs['st_id']; ?></td>
<td align="center"><?php echo $rs['name']"; ?></td>
<td align="center"><input type="checkbox" name="checked[]" <?php if($rs['checked']==1){echo "checked"; } ?> /></td>
<td align="center"><img src="images/delete_icon.png" alt="Delete" /></td>
<td align="center"><img src="images/update.png" alt="Update" /></td>
this is gives me the output
assume that checkbox of id 1 is checked and retrieved from mysql table.
Now what i want to do is that when i checked the remaing two checkbox into this table and a function is called to ajax which goes to php page and update the value of checked field according to the given id (i.e 2 and 3 in this case). Not refreshing the whole page nor updating the whole record just the value of check box. i am new to ajax so
any help would be greatly appreciated.

Yes, exploring jqGrid isn't a waste of time at all. However, since you want to update only on change of checkbox value. Here's what you can do..
<input type="checkbox" name="check1" />
And..
$().ready(function(){
var st_id = <?php echo $rs['st_id']; ?>;
//Or you could use a hidden field in the form
$(':checkbox').click(function(){
var chkName = $(this).attr('name');
var checkVal = $(':checkbox[name='+chkName+']').attr('checked');//true or false
$.ajax({
url: 'MyApp/update.php?checboxName=' + checkVal,//Do update on server-side
success: function(data) {
alert('Updated successful.');
}
});
});
});
Also, you can do a $('formID').serialize() wihch returns name=value pairs of all form elements that can then be appended in the call to your php script.

Related

reload multiple table cells with jQuery

I have many forms in a page, each form with several inputs. When you click Submit on a form (say Form0), inputs are send to Reassign.php,that perform a search in a DB according to user inputs, and then a cell with div id="Cell0" in a table of the page is reloaded with data echoed by Reassign.php.
<script type="text/javascript">
$(document).ready(function(){
$("#Form0").submit(function(){
var MyVariables = $(this).serialize();
$('#Cell00').load('Reassign.php?MyVariables=' + MyVariables);
return false;
});
});
$(document).ready(function(){
$("#Form1").submit(function(){
var MyVariables = $(this).serialize();
$('#Cell10').load('Reassign.php?MyVariables=' + MyVariables);
return false;
});
});
</script>
A stripped down version of the table:
<table>
<tr>
<td><div id="Cell00"><img src="Image0.jpg"/></div></td>
<td><div id="Cell01">Text1</div></td>
<td><div id="Cell02">Price1</div></td>
<td><div>
<form name="Form0" id="Form0">
<input type="hidden" name="Qst" value="0">
<input type="image" src="ReloadRed.gif" alt="Submit"/>
<select name="cmb1"><option>cmb1Option1</option><option>cmb1Option2</option></select>
<select name="cmb2"><option>cmb2Option1</option><option>cmb2Option1</option></select>
</form>
</div>
</td>
</tr>
<tr>
<td><div id="Cell10"><img src="Image0.jpg"/></div></td>
<td><div id="Cell11">Text1</div></td>
<td><div id="Cell12">Price1</div></td>
<td><div>
<form name="Form1" id="Form1">
<input type="hidden" name="Qst" value="0">
<input type="image" src="ReloadRed.gif" alt="Submit"/>
<select name="cmb1"><option>cmb1Option1</option><option>cmb1Option2</option></select>
<select name="cmb2"><option>cmb2Option1</option><option>cmb2Option1</option></select>
</form>
</div>
</td>
</tr>
</table>
A sample Reassign.php:
<?php
session_start();
$MyVariables = $_GET['MyVariables '];
$cmb1 = $_GET['cmb1'];
$cmb2 = $_GET['cmb2'];
$cmb3 = $_GET['cmb3'];
parse_str($MyVariables);
$Preg=$MyVariables;
$link = mysql_connect("localhost", usr, pswrd) or die(mysql_error());
#mysql_select_db("MyDB") or die( "Unable to select database");
mysql_query ("SET NAMES 'utf8'");
$query = "SELECT Img FROM MyTable WHERE Column1=$cmb1 AND Column2=cmb2";
if($success = mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$image="../ImageFolder/".$row[0].".png";
}
}
echo "<img src=\"".$image."\" />";
?>
This is OK.
Now I want other cells in the table to change as well, but with different (and related) data. Indeed, in the DB seach by Reassign.php, $row[0] is echoed (and thus loaded) in Cell00, and I want $row[1] to be send to Cell01, $row[2] to Cell02 and so on.
My problem is that right now I'm loading Cell0 echoing their content. I think i could do the job calling different php (Reassign0.php to echo data to Cell00, Reassign1.php to echo data to Cell01) but seems rather odd. Any ideas?
Here is a better approach... You can echo JSON instead of HTML from you PHP script, with all fields of the row. (Other code must be put in place for this to work for you, I'll let you research it on your own)
echo json_encode($row);
In your JS, get that json with $.getJSON(url, callback) or $.get(url, callback) depending on your server configuration
Then, loop through the cells and inject the data in your callback
$.getJSON('Reassign.php?MyVariables='+MyVariables, function(row){
for(i=0;i<row.length;i++){
$("#Cell0"+i).html(row[i]);
}
});
EDIT: if you data is not already formatted as HTML (like for images), be sure to do it in your callback. For example, if the first element is always an image URL and the rest is plain data, you can do :
$.getJSON('Reassign.php?MyVariables='+MyVariables, function(row){
for(i=0;i<row.length;i++){
var content = ( i == 0 ) ? '<img src="'+row[i]+'" alt="" />' : row[i];
$("#Cell0"+i).html(content);
}
});

sending checked box values to php script to process via jquery

I have a table with four columns with a checkbox at the end of each row. I would like to know if there is a way of writing a jquery function that will select all the values of each row when the check box has been ticked and the submit button has been clicked.. and then pass the values to .php file to process/display. The reason i want to use the .php file is because i want to run a query to show all registered users on my system and then send the checked rows (id and name) to those users.
Sounds very complicated but i really need some help. thanks in advance.
here is the html code:
<div class="valuesOfObs">
<table>
<thead><tr><th>Valuation Name</th><th>Valuation Goal</th><th>Valuation Description</th><th>Options</th><th>Invite</th></tr></thead>
<tbody>
<?php
$sql = 'SELECT * FROM valuation';
$results = $db->query($sql);
$rows = $results->fetchAll();
foreach ($rows as $row) {
echo '<tr id="'.$row['ValuationID'].'">';
echo '<td class="crsDesc">'.$row['ValuationName'].'</td>
<td >'.$row['ValuationGoal'].'</td>
<td >'.$row['ValuationDescription'].'</td>
<td ><a href =values.php?action=invite&id=aValue> xValue </a></td>
<td > <input type="checkbox" name="selectValue">
</td>';
echo '</tr>';
}?>
</tbody>
</table>
</div>
<input type="button" name="addrow" id="addrow" value="Add row">
<input type="button" name="inviteObs" id="inviteObs" value="Invite Obstacle";>
Here is what I have written for the jquery so far.. I am trying to spilt the values so i can choose specifically which ones to process and then later on user the .join() method. Please help out if on the wrong track
$("input[type=checkbox], input[type=button]").on("click", function () {
$( ":checked" ).map(function() {
return $(this).closest("tr").text();
}).split("</td><td>");
var compName = $("#id").val();
$.ajax({
url : "inviteObstacles.php",
type : "POST",
data : {"compID" : compName},
success : function (n){
//do something
}
})
});
Use .map() function to pass each element in the current matched set through a function, which will produce new jQuery object containing the return values.
Here is a code:
$("input[type=checkbox]").on("click", function () {
$( ":checked" ).map(function() { return $(this).closest("tr").text();
}).get().join(); //Use join to split the fetched row using separator "," on server-side
});
Demo: http://jsfiddle.net/tSeau/1/

How to stop my jquery to listen to all rows of data?

I'm trying to make a dropdown when the reject checkbox is ticked. I have done this simply with Jquery but however because I need the function on all of the data that is pulled in, it copies the classes to the next row and so on, so when i check the reject button it opens all the dropdown text areas to input a reason. I was wondering how i would go about making this for an unlimited amount of data????? so it only ever opens one dropdown textarea.
I have read online that I can do this with php parenting? As my PHP skills are weak to say the least is there any simpler ways of going about this?
HTML
Name
Username
Email
Verify
Reject
if ($supplier['Id'] != '3') { ?>
<tr class="unverifiedSuppliers">
<td width="150"><?php echo $supplier['Name']; ?></td>
<td width="150"><?php echo $supplier['Username']; ?></td>
<td width="250"><?php echo $supplier['Email']; ?></td>
<td width="40"><input type='checkbox' name='verifySupplier[]' value='<?php echo $supplier['Id']; ?>' /></td>
<td width="40"><input class="checked" type='checkbox' name='rejectSupplier[]' value='<?php echo $supplier['Id']; ?>' /></td>
</tr>
<tr class="dropdown" style="display: none;">
<td colspan="5">
<label>Reason:</label>
<textarea name="rejectReason[<?php echo $supplier['Id']; ?>]"></textarea>
</td>
</tr>
<?php } } ?>
</table>
Jquery
$(function() {
$('.checked').change(function() {
$('.dropdown').toggle();
});
});
Try :
$('.checked').change(function() {
$(this).closest('tr').next('.dropdown').toggle();
});
$(this) is the DOM element you changed.
.closest('tr') is looking for the closest parent with the jQuery selector 'tr', wich mean the closest <tr></tr>.
.next('.dropdown') is looking for the immediate next sibling with the jQuery selector '.dropdown'.
Side note - using the selector here is facultative, it will just return an empty element if the next element doesnt have the class dropdown.

populate values of a row from the id selected

I'm using PHP to populate names into an option list based on values from a database.
Once a name is selected I want to populate the values of a row based on whatever name has been selected.
I had no problem populating the option list with the name values, but once I select a name the records of that row will not display in the input boxes.
Here is the code I'm working with:
$query = "SELECT name, id
FROM artists
ORDER BY name";
$mysql_stuff = mysql_query($query, $mysql_link);
while($row = mysql_fetch_row($mysql_stuff)) {
$artists_name = htmlspecialchars(stripslashes($row[0]));
$artists_id = stripslashes($row[1]);
// we compare the id of the record returned and the one we have selected
if ($artists_id) {
$selected = $artists_id;
} else {
$selected = "";
}
print("<option value=\"$artists_id\">$artists_name</option>
");
}
print("</select>
<input type=\"Submit\" name=\"submit\" value=\"Update\">
<input type=\"Submit\" name=\"delete\" value=\"Delete\">
<br >
<br />
Edit Biography:
</td>
</tr>
");
if (isset($_POST['submit'])) {
print("<tr valign=\"top\">
<td valign=\"top\" width=\"150\">Name</td>
<td valign=\"top\">Artist Biography</td>
</tr>
");
print("<tr valign=\"top\" bgcolor=\"$colour\">
<td valign=\"top\">
<input type=\"text\" name=\"artists_name[$selected]\" value=\"$artists_name\" size=\"40\" />
</td>
<td valign=\"top\">
<textarea name=\"artists_Biography[$selected]\" cols=\"40\" rows=\"10\">$artists_Biography</textarea>
</td>
</tr>
");
}
print("</table>
</form>
");
Can I please get some assistance with populating the values of the selected name into the input boxes.
So your submitting artist ID to the post. The post would then refresh or change the page. Assuming the action is that page you have the ID in your post. How do you get Artist Name from the ID? Do you run another sql query on the id to find the name? Might need some clarification on the order of your code to help. Thanks
I'm not sure how to interpret this code. Use Ajax. Use Jquery on change() method to take the value of the select and send it via ajax() to a php script that gets the info from the DB and returns what you want. Then use the Success part of the .ajax() method to put that data into you input on the form.
$(function(){
$("select#artist").change(function()
{
var artist = $("select#artist").val();
$.ajax({
type: "POST",
url: "ajax-find-artist.php",
data: "artistID=" + artist,
cache: false,
success: function(html){
var newElems = html;
$("input#artistRestult").html(newElems);
}
});
});
});

calculate value of selected checkboxes

I have a PHP page displaying the results of a MySQL query. It adds checkboxes to each row. The selected rows are then inserted into another table on submit.
My application is a Transport planning platform. I am looking for a way to display the total weight of the selected rows in real time, a box at the top of the page dispalying the current sum of the selected rows.
Can anybody guide me on how to add this functionality to my existing page.
My code currently is shown below:
<?php
mysql_connect("localhost", "username", "password")or die("cannot connect");
mysql_select_db("databasename")or die("cannot select DB");
$sql="SELECT `crtd dept`,`customer`,`case no`,`gross mass` from despgoods_alldetails where transporttypename= 'localpmb'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
?>
<table border=1>
<tr>
<td>
<form name="form1" method="post">
<table>
<tr>
<td>#</td>
<td>Dispatch Area</td>
<td>Customer</td>
<td>Case Number</td>
<td>Weight</td>
</tr>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td><input type="checkbox" name=check[] value="<?php echo $rows['case no']; ?>"></td>
<td><?php echo $rows['crtd dept']; ?></td>
<td><?php echo $rows['customer']; ?></td>
<td><?php echo $rows['case no']; ?></td>
<td><?php echo $rows['gross mass']; ?></td>
</tr>
<?php
}
?>
<tr>
<td colspan=3><input name="Next" type="submit" id="Next" value="Next"></td>
</tr>
<?php
$check=$_POST['check'];
if($_REQUEST['Next']=='Next'){
{
$sql="INSERT INTO loaddetails (dispatcharea,Customer, casenumber, weight,LOCStatus)
SELECT `crtd dept`,Customer,`case no`,`gross mass`,'in Load Creation'
FROM despgoods_alldetails WHERE `Case No` = '$val'";
foreach($check as $key=>$value)
{
$sql="INSERT INTO loaddetails (dispatcharea,Customer, casenumber, weight,LOCStatus)
SELECT `crtd dept`,Customer,`case no`,`gross mass`,'in Load Creation'
FROM despgoods_alldetails WHERE `Case No` = '$value'";
$final=mysql_query($sql);
if($final)
{
echo "<meta http-equiv=\"refresh\" content=\"0;URL=planlocalpmbstep2.php\">";
} }
}
}
// Check if delete button active, start this
// if successful redirect to php.php
mysql_close();
?>
</table>
</form>
</td>
</tr>
</table>
The output of the above code is shown below:
As the others have said, you'll have to do this in Javascript, since it'll be on the client side. I'll assume that you're not using a library such as jQuery or Prototype on this page, and if this is all you're doing, it'd be massive overkill to use one of them.
First, add a HTML element which will contain your total:
<div>Total: <span id="total">0</span></div>
The bit of information you really need to know however, is the weight which corresponds to each checkbox. The simplest method would be to store it on the checkbox element itself. Add an attribute called data-weight. eg:
<input type="checkbox" name="check[]" value="12" data-weight="1234" />
Then, add some javascript:
<script>
(function () {
var totalEl = document.getElementById('total'),
total = 0,
checkboxes = document.form1['check[]'],
handleClick = function () {
total += parseInt(this['data-weight'], 10) * (this.checked ? 1 : -1);
totalEl.innerHTML = total;
},
i, l
;
for (i = 0, l = checkboxes.length; i < l; ++i) {
checkboxes[i].onclick = handleClick;
}
}());
</script>
Aaaannd here's a working demo for you! http://jsbin.com/ipeduf
Assuming you don't want to have to refresh the page every time the user changes a selection, you need to do this in the browser, in Javascript, not in PHP.
I think that you can use a javascript function.
Add an onClick attribute to every checkbox (if you don't want a submit button):
<INPUT TYPE="checkbox" NAME="switchBox" onclick="myfunction(this)">
Then myfunction should calculate the value with something like that:
<script language="javascript">
var total;
myfunction(checkboxId){
total = total + checkboxId.value;
}
</script>
Please notice that this is an unchecked example, only to give you an idea about a solution.
To avoid the need to submit and reaload the page on changes, I would use javascript / jQuery.
What I would do is:
attach all individual weight values to the table rows (or checkboxes...) using the html5 data attribute: <tr data-weight="1604"> for your first row;
on a checkbox value change, loop through all rows that have a selected checkbox to get and generate your sum. That would be something like:
$("input").change(function(){
var total_sum = 0;
$('input').is(':checked').each(function(){
total_sum += $(this).parents("tr").data("weight");
});
});
(can't get the formatting right...)
display the sum in the box you want.

Categories