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.
Related
I have a radio button that has an array as value like this,
$sql = "SELECT * FROM os";
$result = mysqli_query($con,$sql);
while ($row = mysqli_fetch_array($result)) {
$row['client'];
//Radio button code
echo "<li><div class = 'list'><a href = 'searchos.php'><div class = 'toggle-btn-grp cssonly'>
<div><form><input type = 'radio' name = 'os' value = " . $row['client'] . " id = 'myRadio1 onchange='showUser(this.value)' >
<label class='toggle-btn'>" . $row['client'] . "</label></form></div></div><div></a></li>";
}
The radio button is working, but for some reason it keeps ignoring the space between the strings in the array. And it only gives me the value of the first string.
When I hard code the a string with space in the value i.e "Production Cost", it gives me the correct output, so the issue must be with the array then, any ideas on how I Could solve this?
Here is the ajax function for getting the value
function showUser(str)
{
var xmlhttp;
if (str == "")
{
document.getElementById("txtHint").innerHTML = "";
return;
}
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("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "getUser.php?q=" + str, true);
xmlhttp.send();
}
I want to make a form in which an user enters a name to create a new record and want check simultaneously, if the record exists or not, so the user can't insert 2 records with same name (but this is not primary key ) .
i am using following code right now but this reload page every time i need to check for value entered
<html>
<?php
require_once('../php/classes/class.add_album.php');
$file_name='';
$file_not_found="NULL";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$file_name = test_input($_POST["file_name"]);
echo $file_name; //for testing
//make new object
$objfile = new add_album();
//call object methid with post method value we got and save result in result
$file_not_found=$objfile->find_album($file_name);
echo $file_not_found; //for testing
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if($file_not_found){
echo '<form>';
echo '<label>File Name </label>';
echo '<input type="text" value='.$file_not_found.' >';
} else {
echo '<form method="POST" action="temp.php">';
echo '<label>File Name</label>';
echo "<input type=text name='file_name' placeholder='New file name plz' >";
echo"<input type=submit name=submit value=submit>";
}
?>
</form>
`
Follow javascript ajax and same php file as above that i had mentioned.
Refere this link for ajax http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
function validateUser()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200){
//alert(xmlhttp.responseText);
// do somting here..
document.getElementById("captcha_validation").value=xmlhttp.responseText;
}
}
xmlhttp.open("POST","yourfile.php",true);
xmlhttp.send("username=abc&password=xyz");
}
user ajax to send form data to class .
Below is ajax function
$.ajax({
url :"yourfile.php",
type :"POST",
data :$("#formid").serialize(),
success : function(response)
{
// do someting here.
}
Your PHP File (yourfile.php)
$obj = new db();
$yourdata = $_POST;
$res = $obj->validateUser($yourdata) ;
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('&');
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 .... :)
I have implemented a dynamic creation of a HTML table using AJAX.
Here's what I've created:
index.php
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="ContactController.js">
</script>
</head>
<body>
<div class="main-wrapper">
<div id="menu">
<a href="javascript:void(0)" onclick="getAllContacts()">
Go to contacts
</a>
</div>
<div id="main-content">
</div>
</div>
</body>
</html>
ContactsController.js
function getAllContacts() {
// Manage new XmlHttpObject creation
xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert ("Your browser is out of date. Please upgrade.");
return;
}
var url = "getAllContacts.php";
// Workaround for page caching
url = url + "?sid=" + Math.round(Math.random() * 1000000000);
xmlHttp.open("POST", url, true);
// Manage XmlHttpObject state change
xmlHttp.onreadystatechange = stateChanged;
xmlHttp.send(null);
}
function stateChanged() {
// Check if the XmlHttp request is complete
if (xmlHttp.readyState == 4) {
// Set the XmlHttp response in the contacts div
document.getElementById("main-content").innerHTML = xmlHttp.responseText;
}
}
// Creates a new XmlHttpObject
function GetXmlHttpObject() {
var xmlHttp = null;
try {
// XmlHttpObject constructor for Chrome, Firefox, Opera, Safari
xmlHttp = new XMLHttpRequest();
} catch (e) {
// XmlHttpObject constructor for Internet Explorer > v6.0
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
// XmlHttpObject constructor for Internet Explorer > v5.5
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
getAllContacts.php
<?php
include 'connectToMySQL.php';
$command = "SELECT * FROM contact";
$result = mysql_query($command);
echo "<table id='contactsTable' border='1'>";
// Table headers
echo "<tr>
<th>Name</th>
</tr>";
// Print all contacts
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>
<a href='#'
onclick=\"getContact('" . $row['DisplayName'] . "')\">"
. $row['DisplayName'] .
"</a>
</td>";
echo "</tr>";
}
echo "</table>";
mysql_close();
?>
So, clicking on a Go to contacts link activates a getAllContacts javascript function. That function calls getAllContacts php function which retrieves the data from MySQL database and places it in the contactsTable table.
What I need is to tell the function to place that table in the main-content div located in the index.php page. How do I achieve this? Thanks.
ok, so going from your comment about wanting two different possible target divs, just define your onreadystatechanged event inline and use a local variable to refer to the div...
function getAllContacts() {
// Manage new XmlHttpObject creation
var xmlHttp = GetXmlHttpObject(); // MAKE THIS LOCAL INSTEAD OF GLOBAL!
if (xmlHttp == null) {
alert ("Your browser is out of date. Please upgrade.");
return;
}
var url = "getAllContacts.php";
// Workaround for page caching
url = url + "?sid=" + Math.round(Math.random() * 1000000000);
xmlHttp.open("POST", url, true);
var targetDiv = document.getElementById(whateverIdYouWant);
// Manage XmlHttpObject state change
xmlHttp.onreadystatechange = function(){
// Check if the XmlHttp request is complete
if (xmlHttp.readyState == 4) {
// Set the XmlHttp response in the contacts div
targetDiv.innerHTML = xmlHttp.responseText;
}
}
xmlHttp.send(null);
}