I am generating a table using the result of mysql query with checkboxes and radio buttons in each row like:
while($row4 = mysql_fetch_array($q4))
{
$pids = $row4['pid'];
echo "<tr>";
echo "<td><input type='checkbox' name='pids[]' class='persistentChecks' style='display:inline-block;cursor:pointer;' value=".$pids."></td>";
echo "<td style='text-align:center;font-size:12px;'>".$counter17."</td>";
echo "<td style='text-align:center;font-size:12px;'>".$row4['cname']."</td>";
echo "<td style='text-align:center;font-size:12px;'>".$semester."</td>";
echo "<td style='font-size:12px;'><input type='radio' value='1'>Expert<input type='radio' value='2'>Normal";
echo "<td style='text-align:center;font-size:12px;'>".$row4['pname']."</td>";
echo "</tr>";
$counter17 = $counter17 + 1;
}
Its a batch processing problem. I want to send the values of the rows checked along with the radio button value of that checked row through ajax to a PHP page for insertion in MYSQL.
I know how to send only checked checkbox values with push and join functions of JS but am stuck on the way to send the associated radio button values of the checked rows along.
the JS i'm using is:
data = [];
for (i = 0; i < elements.length; i++){
if (elements[i].checked){
data.push('pids[]='+encodeURIComponent(elements[i].value));
}
}
params= "teacher="+encodeURIComponent(teacher)+"&course="+encodeURIComponent(course)+"&semester="+encodeURIComponent(semester)+"&flag="+encodeURIComponent(1)+"&"+data.join('&');
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
result = xmlhttp.responseText;
alert(result);
}
}
xmlhttp.open("POST","tpaper.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(params);
Now on the PHP page, i am looping through the pids sent through JS above using a foreach loop.
How am i supposed to send the radio button values of the checked checkboxes as well? Do i need to run a nested loop in JS and then in PHP foreach as well?
Please help...
Collect the radio values in another array at the same time as you collect the checkboxes.
data = [];
radio_data = [];
for (i = 0; i < elements.length; i++){
if (elements[i].checked){
var pid = elements[i].value;
data.push('pids[]='+encodeURIComponent(pid));
var radios_elements = document.getElementsByName('radio'+pid);
for (var j = 0; j < radio_elements.length; j++) {
if (radio_elements[j].checked) {
radio_data.push('radios[]='+encodeURIComponent(radio_elements[j].value));
break;
}
}
}
}
And add them to the query string:
params= "teacher="+encodeURIComponent(teacher)+"&course="+encodeURIComponent(course)+"&semester="+encodeURIComponent(semester)+"&flag="+encodeURIComponent(1)+"&"+data.join('&')+&+radio_data.join('&');
Related
I want to access the values of dynamically created check boxes.
# $db = mysql_connect("abc", "abc", "");
mysql_select_db("abc");
$strSQL = "SELECT * FROM student";
$rs = mysql_query($strSQL);
$num_rows = mysql_num_rows($rs);
echo "<i style='color:#fff'> Number of Students = ".$num_rows."</i>";
$i=1;
while($r = mysql_fetch_array($rs)){
echo "<tr>";
echo "<td class='promotetabledata'>".$r[7]."</td>";
echo "<td class='promotetabledata'>".$r[6]."</td>";
echo "<td class='promotetabledata'><input type='checkbox' class='pr' value='".$r[7]."'/></td>"; /*dynamically created check boxes*/
echo "</tr>";
$i++;
}
The results are displayed in a promoteresults div using AJAX
<form id="promotionform" action="promotestudents.php" method="POST">
<div id="promoteresults">The results will show up here..!!
</div>
<div style=" position:relative; margin-top:10px; padding-left:44%;">
<button type="submit" class="button black">Promoted</a>
</div>
</form>
When the promoted button is clicked I want to get the selected records and update their value. To update the records, I need PHP. I can access the selected records in Javascript using
var selected = document.getElementsByClassName('pr').checked;
But how do I get the checked records in the HTML form and their values in PHP
The AJAX call with Javascript
function getpromotestudents()
{
//alert("hi");
var xmlhttp;
var select1 = document.getElementById('promotefacultyselect1');
var facutlyselect = select1.options[select1.selectedIndex].value;
var select2 = document.getElementById('promotedepartmentselect1');
var deptselect = select2.options[select2.selectedIndex].value;
var select3 = document.getElementById('promotecourseselect1');
var courseselect = select3.options[select3.selectedIndex].value;
var select4 = document.getElementById('promoteyearselect1');
var yearselect = select4.options[select4.selectedIndex].value;
var select5 = document.getElementById('promotesemselect1');
var semselect = select5.options[select5.selectedIndex].value;
var the_data = 'faculty='+facutlyselect+' &dept='+deptselect+' &course='+courseselect+' &year='+yearselect+' &sem='+semselect;
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("searchresults").innerHTML=xmlhttp.responseText;
}
}*/
xmlhttp.open("POST", "getpromotestudents.php", true); // set the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // adds a header to tell the PHP script to recognize the data as is sent via POST
xmlhttp.send(the_data); // calls the send() method with datas as parameter
// Check request status
// If the response is received completely, will be transferred to the HTML tag with tagID
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
document.getElementById("promoteresults").innerHTML = xmlhttp.responseText;
}
}
}
<td class='promotetabledata'><input type='checkbox' name='pr[]' value='".$r[7]."'/></td>
This is the PHP code I finally wrote to access all the checkboxes, and perform the required operations on the selected ones.
<?php
$checkbox = $_POST['pr'];
foreach($checkbox as $value){
if(isset($checkbox)){
echo '<script>alert("'.$value.'")</script>';
}
}
?>
Give each of the checkbox name property like this
<input type='checkbox' class='pr' value='8' name='chk[]'/>
Than in the php you can get them as follows
<?php
$chkbox = $_POST['chk'];
foreach($chkbox as $a => $b){
echo $chkbox[$a];
}
?>
Set each check box's name property to pr[], as in:
echo "<input type='checkbox' class='pr' name='pr[]' value='".$r[7]."'/>";
Then, the first checkbox will be at $_POST['pr'][0], the second at $_POST['pr'][1] and so on.
I need to know what is wrong. The PHP doesn't return anything. I think the variables don't get on the PHP file. Please help me to find out what goes wrong.
<?php
defined('_JEXEC') or die;
$db = JFactory::getDbo();
$an=$_POST['an'];
$fac=$_POST['fac'];
$uni=$_POST['uni'];
$result1 = mysql_query("SELECT * FROM drv_uni_$uni WHERE an='$an'");
while($row = mysql_fetch_array($result1)){
$display_string = "<option value=\"".$row['materie']."\">". $row['materie'] ."</option>";
}
echo $display_string;
?>
Javascript
function getValFromDb() {
var valoare_selectata_uni = document.getElementById('category').value;
var valoare_selectata_fac = document.getElementById('subcategory').value;
var valoare_selectata_an = document.getElementById('an').value;
var url = "modules/mod_data/tmpl/script.php";
var params = 'uni=' + valoare_selectata_uni +
'&fac=' + valoare_selectata_fac +
'&an=' + valoare_selectata_an;
if (window.XMLHttpRequest) {
AJAX=new XMLHttpRequest();
} else {
AJAX=new ActiveXObject("Microsoft.XMLHTTP");
}
if (AJAX) {
AJAX.open("POST", url, false);
AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
AJAX.onreadystatechange = function() {
if(AJAX.readyState == 4 && AJAX.status == 200) {
var answer = AJAX.responseText;
document.getElementById('materie').innerHTML = answer;
}
};
AJAX.send(params);
}
}
You can debug the code using below few methods.
You can 1st print_r($result1) and see whether your SQL returns the results you want. If not try working on the query.
$display_string = "<option value=\"".$row['materie']."\">". $row['materie'] ."</option>"; is wrong you should have a it like below. $display_string .= "<option value=\"".$row['materie']."\">". $row['materie'] ."</option>";. You are missing .=
if had static variables and included on the main it shows good. Rather than using $_POST use Joomla's way of retrieving POST data JRequest::getVar('an');. Read more
let me know the results I might be able to help you.
I am trying to pass values from a multiple select listbox through Ajax to PHP. I saw some examples in Jquery and JSON, however I am trying to accomplish this just in plain old javascript (Ajax). Here is what I have so far (simplified):
Ajax:
function chooseMultiEmps(str)
{
var mEmpList2 = document.getElementById('mEmpList'); //values from the multi listbox
for (var i = 0; i < mEmpList2.options.length; i++) //loop through the values
var mEmpList = mEmpList2.options[i].value; //create a variable to pass in string
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
//specific selection text
document.getElementById('info').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "myPage.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var queryString = "&mEmpList=" + mEmpList; //query string should have multiple values
xmlhttp.send(queryString);
}
I can run an alert(mEmpList) and get each value in individual message boxes, however when I retrieve and echo the $_POST['mEmpList'], I get only the first value. Also, when I alert(queryString), I get only one value.
I think I need to create a comma delimited array, and then pass that through the query string. From there, I can use the PHP implode/explode feature to separate the values. Any assistance would be greatly appreciated.
here:
for (var i = 0; i < mEmpList2.options.length; i++) //loop through the values
var mEmpList = mEmpList2.options[i].value; //create a variable to pass in string
you are redefining your mEmpList over and over again, that means only the last value is send
You could do:
var mEmpList = '';
for (var i = 0; i < mEmpList2.options.length; i++) { //loop through the values
mEmpList = mEmpList +','+ mEmpList2.options[i].value; //create a variable to pass in string
}
Also your queryString is not ok, no need for &
var queryString = "mEmpList=" + mEmpList;
That way at the end you will have all values delimite by comma ,
In PHP you can use explode to loop each value:
<?php
$string = explode(',' $_GET['mEmpList']);
for($i=1; $i<count($string); $i++){
echo $string[$i]."<br />";
}
?>
I actually converted the html checkboxes into images(below is the code), now the checkboxes have 3 states one for checked, one for unchecked and one for null,
now i want to add a DRAG feature to it like if we select unchecked and drag on other checkboxes, the other checkboxes should get this value, i meam the image must be changed.
Here is an example on this link http://cross-browser.com/x/examples/clickndrag_checkboxes.php , this example is without images but i want the same thing to happen with images.
Any help will really make my day, Thanks!
here is the code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
var inputs;
var checked = 'checked.jpg';
var unchecked = 'unchecked.jpg';
var na = 'na.jpg';
function replaceChecks()
{
//get all the input fields on the funky_set inside of the funky_form
inputs = document.funky_form.getElementsByTagName('input');
//cycle trough the input fields
for(var i=0; i < inputs.length; i++)
{
//check if the input is a funky_box
if(inputs[i].className == 'funky_box')
{
//create a new image
var img = document.createElement('img');
//check if the checkbox is checked
if(inputs[i].value == 0 )
{
img.src = unchecked;
inputs[i].checked = false;
}
else if(inputs[i].value = 1 )
{
img.src = checked;
inputs[i].checked = true;
}
else if(inputs[i].value = 2 )
{
img.src = na;
inputs[i].checked = true;
}
//set image ID and onclick action
img.id = 'checkImage'+i;
//set name
img.name = 'checkImage'+i;
//set image
img.onclick = new Function('checkChange('+i+')');
//place image in front of the checkbox
inputs[i].parentNode.insertBefore(img, inputs[i]);
//hide the checkbox
inputs[i].style.display='none';
}
}
}
//change the checkbox status and the replacement image
function checkChange(i)
{
if(inputs[i].value==0)
{
inputs[i].checked = true;
inputs[i].value = 2;
document.getElementById('checkImage'+i).src=na;
}
else if(inputs[i].value==1)
{
inputs[i].checked = false;
inputs[i].value = 0;
document.getElementById('checkImage'+i).src=unchecked;
}
else if(inputs[i].value==2)
{
inputs[i].checked = true;
inputs[i].value = 1;
document.getElementById('checkImage'+i).src=checked;
}
}
setTimeout(function(){replaceChecks();}, 0);
</script>
</head>
<form name="funky_form" action='checkkkkkkkkkkkkkkkkkkkkkkkkk.php' method='POST'>
<table id="table1" border=1px cellpadding=1px cellspacing=1px>
<tr>
<th>D/T</th>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
<th>6</th>
<th>7</th>
<th>8</th>
<th>9</th>
<th>10</th>
<th>11</th>
<th>12</th>
<th>13</th>
<th>14</th>
<th>15</th>
<th>16</th>
<th>17</th>
<th>18</th>
<th>19</th>
<th>20</th>
<th>21</th>
<th>22</th>
<th>23</th>
<th>24</th>
</tr>
<?php
$days = array('SUN');
foreach($days as $key=>$val)
{
print "<tr>";
print"<th>$val</th>";
for($i=0; $i<24; $i++){
print "<td>";
print " <input type=\"checkbox\" id=\"${val}${i}\" name=\"sun${i}\"
class=\"funky_box\" />";
print "</td>";
}
print "</tr>";
}
$days = array('MON');
foreach($days as $key=>$val)
{
print "<tr>";
print"<th>$val</th>";
for($i=0; $i<24; $i++){
print "<td>";
print " <input type=\"checkbox\" id=\"${val}${i}\" name=\"mon${i}\"
class=\"funky_box\" />";
print "</td>";
}
print "</tr>";
}
?>
</table>
</form>
It really is quite simple, bind an event to mousedown and not click, set a variable to indicate that the button is held down and at the same time check/uncheck the current checkbox etc.
Set another event to the mouseenter event of any checkbox, then check it the mousebutton is held down, and set the state to the same as the first checkbox where the mousebutton was first pressed down.
var state = false, mouse=false;
$('checkbox').on({
click: function(e) {
e.preventDefault();
},
mousedown: function(e) {
this.checked = !this.checked;
state = this.checked;
if(e.which === 1) mouse = true;
},
mouseup: function(e) {
if(e.which === 1) mouse = false;
},
mouseenter: function(e) {
if (mouse) this.checked = state;
}
});
Here's a fiddle to show how : FIDDLE
This will still have some bugs in it, and will need some additional checks etc. but it's basically how it's done.
I'm not going to go through all your code with bits of PHP and javascript sprinkled in it, you should probably have set up a fiddle with the HTML and some images if that is what you wanted, so you'll have to figure out how and where to switch the images yourself, but that should be pretty straight forward
There are several ways to add event listeners. The following concept can also be used using jQuery (and personally what I prefer).
object = document.getElementById("objectName");
$(object).bind('dragstart', eventStartDrag);
$(object).bind('dragover', eventStartDrag);
$(object).bind('drag', eventDragging);
$(object).bind('dragend', eventStopDrag);
And there are jQuery shortcuts such as:
$(object).mousedown(eventMouseDown);
$(object) is the object you want to listen for the event. Not all browsers support event capturing (Internet Explorer doesn't) but all do support event bubbling, so I believe the most compatible code is adding the event listener without jQuery.
object.addEventListener('mousedown', eventStartDrag, false);
According to this post, the preferred way of binding an event listener to a document in jQuery is using .on() rather than .bind(), but I have not tested this yet.
Hope this helps.
I guess that jQuery Draggable and Droppable could help you.
SAMPLE CODE
One more SAMPLE without drag and drop that is more similar to your example with regular checkboxes.
I have a situation in which i need to do insert queries for every check box selected through an ajax request sent to a php script which would do the insert in mysql.
i know how to do it without an ajax call via the simple form submission with a variable like groups[] as an array and running the foreach loop in php for every value in the array.
How do i send the array a via post ajax request?
a sample code:
<input type='checkbox' name='groups[]' value='1'>Group A
<input type='checkbox' name='groups[]' value='2'>Group B
<input type='checkbox' name='groups[]' value='3'>Group C
Please help, i know this might be easy but i am just not getting it. and guys, please don't give any example of jquery or the likes as i want pure html, javascript and php solution.
Thanks community...
Here's the Javascript function:
<script type='text/javascript'>
function addResp(tid){
a = encodeURIComponent(document.getElementById('course_add_resp').value);
b = encodeURIComponent(document.getElementById('term_add_resp').value);
c = encodeURIComponent(document.getElementById('paper_add_resp').value);
var elements = document.getElementsByName('groups[]');
var data = [];
for (var i = 0; i < elements.length; i++){
if (elements[i].checked){
data.push('groups[]='+elements[i].value);
}
}
params = "tid="+tid+"&course="+a+"&sem="+b+"&paper="+c+"&grp="+data;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.body.removeChild(document.getElementById('respBackground'));
document.body.removeChild(document.getElementById('respBox'));
contents = xmlhttp.responseText;
if(contents == "done"){
window.location = "teachers.php";
} else{
document.getElementById("studentBox").innerHTML = "There was a problem serving the request.";
}
}
}
xmlhttp.open("POST","assignresp.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(params);
}
</script>
and the php script:
<?php
$tid = mysql_real_escape_string($_POST['tid']);
$cid = mysql_real_escape_string($_POST['course']);
$sem = mysql_real_escape_string($_POST['sem']);
$paper = mysql_real_escape_string($_POST['paper']);
$session = 12;
$type = 1;
$groups = $_POST['grp'];
foreach ($groups as $value ) {
$q1 = "insert into iars(sessionid,teacherid,courseid,semester,paperid,groupid,type) values('$session','$tid','$cid','$sem','$paper','$value','$type')";
$r1 = mysql_query($q1) or die(mysql_error());
if(mysql_affected_rows() > 0){
echo "done";
}
else{
echo "fail";
}
}
?>
var elements = document.getElementsByName('groups[]');
var data = [];
for (var i = 0; i < elements.length; i++){
if (elements[i].checked){
data.push('groups[]='+elements[i].value);
}
}
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(data.join('&'));
//for get
//xmlhttp.open("GET",url+"?"+data.join('&'),true);
//xmlhttp.send();
EDIT
Change these two lines.
params = "tid="+tid+"&course="+a+"&sem="+b+"&paper="+c+"&"+data.join('&');
$groups = $_POST['groups'];
you can do this with two way,
you can use the post type ajax call
You can get the all selected checkbox values with JavaScript make comma separated string and just pass it in one variable
that's all you can do .... :)