sending checked box values to php script to process via jquery - php

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/

Related

Need help assigning a php variable based on which button I press

I have a table with 20 buttons. I want to assign a php variable the same value as the button I press, something I figured would be easy but it's been two hours now without success.
foreach ($soccerseason->getTeams() as $team) {
if (($i % $number_per_row) == 0) {
echo '<tr>';
}
?>
<td style="background-image:url(<?php echo $team->crestUrl ?>);background-position: 50% 50%;background-repeat:no-repeat;background-size:100px 100px; width: 110px; height: 110px;">
<form action="JavaScript: showQuiz()" method="post" value="<?php echo $team->name ?>">
<button class="tableButton" value="<?php echo $team->name ?>"style="width:110px; height:110px"></button>
</form>
</td>
<?php
if (($i % $number_per_row) == $number_per_row - 1) {
echo '</tr>';
}
$i = $i + 1;
}
Say I want to echo the value of the button I press - how would you proceed? The function of the javascript is currently to hide/show different divs, nothing else. Thanks
One solution is to make the button call a Javascript function, that uses JQuery's ajax request to do whatever you want to do in PHP, and have the PHP output the name, which the Javascript will receive back, and change the div, or span to. I think the code would look something like this(in the Javascript):
function ajaxRequest(buttonName){
var data = "name=" + buttonName;
$.ajax({
url: "showPHP.php",
type: "post",
data: data
}).done(function(data){
document.getElementById("currentButtonSelectedDiv").innerHtml = data;
});
}
I am pretty sure you might need some other flags, but that is the basics of the javascript. The PHP would look something like this:
<?php
// Your php stuff
echo $_POST['name'];
?>
You generally keep the name attribute on the buttons the same as you have done, but vary the value.
Without seeing the rest of the table, you could potentially wrap the whole table in the form tag also.
<form method="post" action="readValue.php">
...
<button type="submit" name="teamName" value="team1">team1</button>
<button type="submit" name="teamName" value="team2">team2</button>
<button type="submit" name="teamName" value="team3">team3</button>
...
</form>
When the data is posted back, read the teamName value from the $POST variable.
<?php
$teamName = $POST["teamName"];
It's not entirely clear what you are doing with the javascript, but you can attach event handlers when the buttons are clicked also.

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);
}
});

Editing a html table using jquery,php and saving records to mysql

I have a html table(grid) which displays a few records for me.I want it to be editable, i.e user can edit the values and save them on pressing enter.
My table is something like this.I display records dynamically using php.
<a class="grayBucketBtn noMargin none" id="unpublish" href="#.">Unpublish</a>
<a class="grayBucketBtn" id="publish" href="#.">Publish</a>
<a class="grayBucketBtn" id="delete" href="#.">Delete</a>
<a class="grayBucketBtn" id="modify" href="#.">Modify</a>
<?php while ()//loop through ?>
<tr>
<td class="tableRadioBtn"><input type="checkbox" class="checkRowBody" id="checkRowBody" name="check"/></td>
<td class="tableShape">Round</td>
<td class="tableCarst">0.30</td>
<td class="tableColor">j</td>
<td class="tableClarity">SI1</td>
<td class="tableDimension">4.35x4.33x2.62mm</td>
<td class="tableDeptd">60.3%</td>
<td class="tableTablePer">60.3%</td>
<td class="tablePolish">Excellent</td>
<td class="tableSymmetry">Excellent</td>
<td class="tableCut">Very Good</td>
</tr>
<?php } ?>
Each row(tr) has a check box associated.If I check the check box,I get a edit button.When I click on the edit button,the selected row will turn into editable.So I want a function on the edit button,
$("#modify").click(function(){
//check if only one check box is selected.
//make it editable.
//save the content on pressing enter of the edited row.
});
I went through some questions but did not get a solution as most suggest some plugins which don't meet my requirements.So,some help would be useful.
Thanks for the time
This should cover turning them from text to inputs and back to text
$('#modify').click(function(){
$.each($(".checkRowBody:checked"),function(){
$.each($(this).parent('td').parent('tr').children('td:not(.tableRadioBtn)'),function() {
$(this).html('<input type="text" value="'+$(this).text()+'">');
});
});
});​​​​​​​​​
$('input[type="text"]').live('keyup',function(event) {
if(event.keyCode == '13') {
// do $.post() here
$.each($('input[type="text"]'),function(){
$(this).parent('td').html($(this).val());
});
}
});
​
​
When using checkboxes the user assumes more than one can be selected, if you want only one each time then just use radio buttons
I can't give you a complete solution but I can give you a direction:
First change the markup like this:
<tr>
<td class="tableRadioBtn"><input type="checkbox" class="checkRowBody" id="checkRowBody" name="check"/></td>
<td class="tableShape">Round<input class="hidden" value="Round" name="shape"/></td>
<td class="tableCarst">0.30 <input class="hidden" value="0.30" name="tableCarst"/></td>
...
//Do the same for all the columns
</tr>
Define the hidden class to display:none so all the inputs are hidden.
Once the user clicks a row, you remove the text of all the td elements and remove the hidden class from all the inputs:
$(".tableRadioBtn").click(function(){
//find the parent tr, then find all td's under it, empty the text and remove hidden class
$(this).closest('tr').addClass('editable').find('td').each(function(){
$(this).text('').removeClass('hidden');
});
});
//set a keypress event to detect enter
$(document).keypress(function(){
//if enter was pressed , hide input and set text
if(e.which == 13) {
var $editable = $('.editable');
$editable.find('input').addClass('hidden');
$editable.find('td').each(function(){
//set the text back
$(this).text($(this).find('input').val());
});
//post data via ajax.
}
}
Please note that i haven't tested this code so there might be some mistakes there, but this is a possible solution.
UPDATE:
In order to detect if more than one checkbox is checked use this:
if ($(':checked').length > 1){//do something}
So you want to make your selections and then invoke an action on the checked rows?
$('#delete').click(function() {
$.each($('.checkRowBody:checked').parent('td').parent('tr'),function() {
// probably want to carry out a $.post() here to delete each row using an identifier for the rows related record.
//I suggest applying an id or other attribute to the tr element and using that to pass a value with your $.post() data.
$(this).hide();
});
});

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

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.

Pop up php table value to normal window combobox not working using javascript

I'm having problem in getting the value from a pop up window frame to a normal window combobox. In the pop up window i've tried to get the value from a php table using a link. I dont no if its the frame which is causing problem or the code... can u help me plz..
The combobox where the value will be input after onClick
Select
search page
function getScriptPage(div_id,content_id,get_count)
{
subject_id = div_id;
content = document.getElementById(content_id).value;
http.open("GET", "script_page.php?content=" + escape(content)+"&count="+get_count, true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
}
$('#select .coursetable a.principal').click(function(e){
var text = $(this).parent().prev().prev().prev().prev().prev().text();
$('ui-autocomplete-input').val(text);
});
<span class="textb">Enter Search Keyword here :</span>
<input type="text" id="text_content" size="30" onKeyUp="getScriptPage('count_display','text_content','1')">
<input type="button" class="login" value="Search" onMouseUp="getScriptPage('output_div','text_content','0')">
<div id="count_display">
</div>
<div id="output_div">
</div>
</form>
script page
include('config.php');
$strlen = strlen($_GET['content']);
$display_count = $_GET['count'];
$select = "select * from course where course_name like '%".$_GET['content']."%' or course_type like '%".$_GET['content']."%' or duration like '%".$_GET['content']."%' or step_id like '%".$_GET['content']."%'";
$res = mysql_query($select);
$rec_count = mysql_num_rows($res);
if($display_count)
{
echo "There are <font color='red' size='3'>".$rec_count."</font> matching records found.Click Search to view result.";
}
else
{
?>
Search Result
name
course type
description
duration
step_id
if($rec_count > 0)
{
while($data=mysql_fetch_array($res))
{
echo "<tbody>
<tr>
<td class='principal'>".$data['course_name']."</td>
<td class='principal'>".$data['course_type']."</td>
<td class='principal'>".$data['description']."</td>
<td class='principal'>".$data['duration']."</td>
<td class='principal'>".$data['step_id']."</td>
<td>" .'<a href="" id="select" class="lien2" name="select" value="'.$data['course_name'].'" >Select</a>' ."
</tr>
</tbody>";
}
}
else
echo '<td colspan="5" align="center"><FONT SIZE="2" COLOR="red">No matching records found....!</FONT></td>';
}
?>
i've tried the following javascript code in the search page, but still not working
$('#output_div .coursetable a.principal').click(function(e){
var text = $(this).parent().prev().prev().prev().prev().prev().text();
$('ui-autocomplete-input').val(text);
});
or
$('#select .coursetable a').bind('click', function(event) {
var text = $(this).parent().prev().prev().prev().prev().prev().text();
$('ui-autocomplete-input').val(text);
});
can you help me plz...
Thx
regards
My honest opinion is not to use a pop up window, but to use something that is better for the user and easier to maintain, no one likes to see .prev() multiple times.
You can use a plug in for jQuery like Boxy which can load a page via Ajax, or it can simply load a predefined form into the lightbox window. This form can then be sumbitted via convention means, or via Ajax.
Boxy provides functions for various events, e.g. what happens when the window is closed, forcing the window to close etc.
Once the form is submitted via Ajax you can then force the window to close if the Ajax response was successful.
Hope that helps.

Categories