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 .... :)
Related
I am trying to generate some invoices based on user's input (date selection). That is something like this:
The invoice.php file would let the user select a date from a form, and based on that selection the contents of the invoice (like amount, customer, etc.) on that same page would be updated through Ajax.
The ajaxInvoice.php would generate a MySQL query and in the end create an array with the corresponding table row based on date selection and merchant (unique row).
invoice.php
...
<body>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('field_1');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var date = document.getElementById('date').value;
var merchant = document.getElementById('merchant').value;
var queryString = "?date=" + date + "&merchant=" + merchant;
ajaxRequest.open("GET", "ajaxInvoice.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
...
<form name="invoiceDate">
<input type="hidden" id="merchant" value="<?php echo $merchant; ?>" />
Date: <select id="date">
<option>2013-07-23</option>
<option>2013-07-25</option>
</select>
<input type="button" onclick="ajaxFunction()" value="Select Date" />
</form>
...
<div id="field_1">FIELD 1</div>
...
<div id="field_2">FIELD 2</div>
...
<div id="field_3">FIELD 3</div>
...
ajaxInvoice.php
include_once('includes/db.php');
$merchant = $_GET['merchant'];
$date = $_GET['date'];
$merchant = mysql_real_escape_string($merchant);
$date = mysql_real_escape_string($date);
$query = "SELECT * FROM settlements WHERE datePayment = '$date' AND merchant = '$merchant'";
$result = mysql_query($query) or die(mysql_error());
$array = array();
while($row = mysql_fetch_assoc($result)) {
$array[] = $row;
}
I was wondering if I could have access to that array this way:
echo $array[0]['fieldName'];
and update selected elements on the page based on different row fields. Not sure if getElementById or getElementByName should be used.
My question would be how to actually access the php array within the script part and also within the rest of the page, so that I can update the various div elements with the corresponding data obtained from the DB query after the user selects the date from the form.
In fact, if only one div has to be updated, the code works just fine, but I don't know how to extend the logic to update more than one div.
Any help or hints on the syntax or code logic would be greatly appreciated.
Thank you very much in advance!
I usually use JSON:
PHP at the server: echo json_encode($array)
JavaScript on the client: var response = JSON.parse(ajaxRequest.responseText)
Implemented:
invoice.php
...
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var response = JSON.parse(ajaxRequest.responseText);
// Now you can use:
response[0]['fieldName'];
// Like this
var ajaxDisplay = document.getElementById('field_1');
ajaxDisplay.innerHTML = response[0]['field_1'];
}
}
...
ajaxInvoice.php
...
$array = array();
while($row = mysql_fetch_assoc($result)) {
$array[] = $row;
}
// Encode to JSON
echo json_encode($array);
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 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 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 />";
}
?>