loop list of input checkbox and get values - javascript

I am trying to get a table of names checked,
and send this array to a PHP page.
But I dont know how, I began by this code:
$(".ok").click(function(){
$("input[type='checkbox']:checked").each(function() {
var tt = $(this).val();
alert(tt);
});
});
echo "<table>";
foreach ($result as $data) {
echo "<tr>";
echo "<td><input type='checkbox' value='$data[0]' /></td><td>$data[0]</td>";
echo "</tr>";
}
echo "</table>";

Try..
$(".ok").click(function(){
//check if any are checked and if so redirect..
if($("input[type='checkbox']:checked").length > 0)
window.location.href = 'page.php?'+$("input[type='checkbox']:checked").serialize();
});
then in page.php..
$result = $_GET;
if(count($result)){
foreach($result as $data){
echo "<tr>";
echo "<td><input type='checkbox' value='$data' /></td><td>$data</td>";
echo "</tr>";
}
}

Related

value of $_POST is always the last value of my <tr>

I have a problem in which I cannot solve. I have a simple page where I query all Users and list them in a table. When a user clicks on one of the table rows, it should be taken to another page where the user can edit information of the that they picked. The problem is that in my script, the $_POST value is always the value of the last
CODE
<?php
include "conn.php";
$pquery = "SELECT * FROM Patient NATURAL JOIN User ORDER BY LastName;";
$patientQuery = $conn->query($pquery);
if (mysqli_num_rows($patientQuery) == 0)
echo "<p>No patients found.</p>";
else{
while($assoc = $patientQuery->fetch_assoc()){
echo "<tr onclick = 'sub();'>";
echo "<td>";
echo $assoc['UserID'];
echo "<input type = 'hidden' name = 'UserID' value = '". $assoc['UserID'] ."' />";
echo "</td>";
echo "<td>";
echo $assoc['FirstName'];
echo "</td>";
echo "<td>";
echo $assoc['LastName'];
echo "</td>";
echo "</tr>";
}
}
?>
<script>
function sub(){
document.getElementById("edit").submit();
return false;
}
</script>
I've slightly modified your code - this should work:
<?php
include "conn.php";
$pquery = "SELECT * FROM Patient NATURAL JOIN User ORDER BY LastName;";
$patientQuery = $conn->query($pquery);
if (mysqli_num_rows($patientQuery) == 0)
echo "<p>No patients found.</p>";
else{
while($assoc = $patientQuery->fetch_assoc()){
echo "<tr onclick = 'sub(". $assoc['UserID'] .");'>";
echo "<td>";
echo $assoc['UserID'];
echo "</td>";
echo "<td>";
echo $assoc['FirstName'];
echo "</td>";
echo "<td>";
echo $assoc['LastName'];
echo "</td>";
echo "</tr>";
}
}
?>
<script>
function sub(UserID){
document.location.href = 'http://www.yourdomain.com/something.php?UserID='+UserID;
return false;
}
</script>

javascript alert on checkbox value

I have checkboxes whose value attribute is coming from database.I want the user to always check the checkboxes having same value if he does not then alert using javascript.I tried to do this using the following javascript code but no use
<script>
function ck()
{
var x,item,f;
list=document.getElementById("yo");
f=list[0].value;
for(index=1;index<list.length;++index)
{
item=list[index];
x=item.value;
if(x!=f)
{
alert("Wrong type checkboxes selected!");
break;
}
}
}
</script>
Below is the PHP code for checkbboxes
<?php
$flag1=-1;
$conn = mysqli_connect("localhost", "root","","discvr");
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
for($i = 0; $i < 150; $i++) {
echo "<tr>";
$cur_date=date("Y-m-d");
echo "<td>Noida Sector ".($i+1)."</td>";
$location="Noida Sector ".($i+1);
for($j=1;$j<=8;$j++)
{
$time_id=$j;
$sql="select status from final where location = '$location' AND date='".$cur_date."' AND time_id=$time_id";
$query=mysqli_query($conn,$sql);
if(!$query)
{
$status=0;
echo "Hi";
}
else
{
if($row=mysqli_fetch_array($query))
{
//echo "hi";
$status=$row['status'];
}
else
$status=0;
//echo $time_id;
}
if($i==0)
echo "<td><input type='checkbox' id='yo' name=time[] value=".$j." value='".$status."' onclick='ck()' > $status </td>";
else
echo "<td><input type='checkbox' id='yo' name=time".$i."[] value=".$j." value='".$status."' onclick='ck()' >$status</td>";
}
echo "</tr>";
}
?>
give unique id's to each checkbox even you are not using them.
Note: on your page id's should be unique.
try like this:
use your connection and other this ,it is for demo.
<?php
for($i = 0; $i < 150; $i++) {
echo "<tr>";
$cur_date=date("Y-m-d");
echo "<td>Noida Sector ".($i+1)."</td>";
$location="Noida Sector ".($i+1);
for($j=1;$j<=8;$j++)
{
if($i==0)
echo "<td><input type='checkbox' id='yo$i' name=time[] value=".$j." value='".$status."' onclick='ck(this.value)' > $status </td>";
else
echo "<td><input type='checkbox' id='yo$i' name=time".$i."[] value=".$j." value='".$status."' onclick='ck(this.value)' >$status</td>";
}
echo "</tr>";
}
?>
javascript:
<script>
function ck(value)
{
var x,item,f;
list= document.getElementsByTagName("input");
f=value;
console.log(f);
for(i=1;i<list.length;++i)//change your logic here don't know what you are trying here
{
item=list[i];
x=item.value;
if(x!=f)
{
alert("Wrong type checkboxes selected!");
break;
}
}
}
</script>

Validating a form created via php with javascript

I have a PHP form.
The form elements are created based off the user's selection which is in a dropdown menu.
What I am trying to accomplish is loop through that form and validate the values of two elements with the id's of "action" and "amt".
Now, I should mention the form which I am trying to validate can have x amount of elements because it needs to be based on the users needs. When I call my validate function it does check the id's and alerts the value, however, it alerts the value of the first input element with the id "amt" three/multiple times.
This is bad as because I need to perform some computation and the duplicate entries would cause an error in the the computation.
Here is my script
<script type="text/javascript">
function validate(){
var i;
var passtest = 0;
var test = "";
var form = document.getElementById("myForm");
alert("Enter function");
for( i = 0; i < form.elements.length; i++){
if(form.elements[i].id === "action" && form.elements[i].value === "Debit" || form.elements[i].value === "Credit"){
test = form.elements[i].value;
// Alerts action
alert(test);
if(document.getElementById("amt").value !=""){
// Get the value from the input element id amt
test = document.getElementById("amt").value;
// Alerts value from id amt
alert(test);
//passtest = 1;
}
else{
document.getElementById("amtTD").innerHTML = "Check Amounts";
return false;
}
alert("End of if stmt");
}
else{
// If it is not id action or id amt just Alert value if any
test = form.elements[i].value;
alert(test);
}
}
///****** END OF FOR LOOP ****** ///
if(passtest === 1){
return true;
}
else{
alert("Submission failed");
return false;
}
}
</script>
Here Is the php code that which displays the form
<form name='transaction' id="myForm" onsubmit="return validate()" action='' method='post'>
<?php
if (isset($_POST['add'])) {
if (isset($_POST['acctN'])) {
echo "<table class='table' id='myRow'' style=''>";
echo "<thead>";
echo "<tr>";
echo "<th>Account Name</th>";
echo "<th>Action</th>";
echo "<th>Amount</th>";
echo "</tr>";
echo "</thead>";
foreach ($_POST['acctN'] as $name) {
$query = "SELECT * FROM ChartOfAccounts WHERE AccountName = '$name'";
$results = mysqli_query($cxn, $query) or die(mysqli_error($cxn));
$row = mysqli_fetch_assoc($results);
echo "<tbody>";
echo "<tr>";
echo "<td class ='col-md-6'><select name='account[]' class='form-control' style=''><option>" . $row['AccountName'] . "</option></select></td>";
echo "<td class ='col-md-2'><select name='debOrCred[]' id='action' class='form-control' style=''>
<option value='Debit'>Debit</option>
<option value='Credit'>Credit</option>
</select></td>";
echo "<td class ='col-md-2'> <input type='text' name='amount[]' class='form-control' id='amt' style=''/> <span id ='amtTD' style='color:red;'> </span></td>";
echo "<td class ='col-sm-2'>$</td>";
echo "<td class ='col-sm-2'><button type='button' onclick='removeCell()' class='btn btn-danger'value='Remove' name='".$row['AccountName']."'>Remove</button></td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
}
echo "<label style='margin-left:7px;'>Documentation</label>";
echo "<textarea name='src-doc' class='form-control' rows ='4' cols='50' placeholder='Description' style='max-width:575px; margin-left:8px;' ></textarea>";
echo "<div style='padding:10px;'>";
echo "<label>Source</label>";
echo "<input type='file' name='fileToUpload' id='fileToUpload'>";
echo "</div>";
echo "<input type='submit' class='btn btn-primary' value='Submit' name='subTrans' style='margin-top:7px; margin-left:8px; '/>";
}
?>
</form>
Thank you all that help and provide input.

update_multiple_rows using ajax and php

please in need help in updating multiple rows based on dynamic data fetched from mysql database. I have implemented this using $_Post to udate.php file, but how can i do this using ajax.
//THIS SCRIPT FETCH FROM DATABASE
<body>
<?php
mysql_connect("localhost","root","");
mysql_select_db("student") or die("Unable to select database");
$sql = "SELECT * FROM students ORDER BY id";
$result = mysql_query($sql) or die($sql."<br/><br/>".mysql_error());
$i = 0;
echo '<table width="50%">';
echo '<tr>';
echo '<td>ID</td>';
echo '<td>Name</td>';
echo '<td>Address</td>';
echo '</tr>';
echo "<form name='form_update' method='post' action='update.php'>\n";
while ($students = mysql_fetch_array($result)) {
echo '<tr>';
echo "<td>{$students['id']}<input type='hidden' name='id[$i]'value='{$students['id']}' /></td>";
echo "<td>{$students['name']}</td>";
echo "<td><input type='text' size='40' name='address[$i]' value='{$students['address']}' /></td>";
echo '</tr>';
++$i;
}
echo '<tr>';
echo "<td><input type='submit' value='submit' /></td>";
echo '</tr>';
echo "</form>";
echo '</table>';
echo $i; ?>
</body>
// HERE IS THE UPDATE SCRIPT
// On clicking submit all rows are updated but i still cant achieve dis with ajax.
UPDATE.PHP
$size = count($_POST['address']);
$i = 0;
while ($i < $size) {
$address= $_POST['address'][$i];
$id = $_POST['id'][$i];
$query = "UPDATE students SET address = '$address' WHERE id = '$id' LIMIT 1";
mysql_query($query) or die ("Error in query: $query");
echo "$address<br /><br /><em>Updated!</em><br /><br />";
++$i;
}
?>
HERE IS WHAT I HAVE TRIED ON AJAX
function update(){
var j=0;
while(j< <?php echo $i ; ?>){
var id=$("#id" + j);
var address=$("#address" + j);
$.ajax(
{
url:"update.php",
type:"post",
data:{id:id.val(),address:address.val()},
success:function(response)
{
}
});
}
ANY HELP WILL BE APPRECIATED
You shouldn't need to loop and execute multiple POSTs. Simply serialize the form data and send it to the script, e.g.:
$.ajax({
url: 'update.php',
type: 'post',
data: $('#your-form-id').serialize(),
success:function(response){
// do something
}
});
Also, you should consider revising your PHP to prevent SQL injection: How can I prevent SQL injection in PHP?

How to add select box field dynamically after clicking add button by using php or javascript and store selected value in selected box in database

if (isset($_POST['dept']) && isset($_POST['batch']) && isset($_POST['Month']) && isset($_POST['Year']) && isset($_POST['semester'])) // based on these values selected from database
{
$dept = $_POST['dept'];
$batch = $_POST['batch'];
$month = $_POST['Month'];
$year = $_POST['Year'];
$semester = $_POST['semester'];
$query = db_select('student_master');
$query->fields('student_master', array('reg_no','name','dob','dept_code','degree','batch_year'));
$query->condition('dept_code',$dept,'=') AND $query->condition('batch_year',$batch,'=');
$results = $query->execute();
echo "<table>";
echo "<tr>";
echo "<td><label for='reg_no'> Registration Number </label></td>";
echo "<td>";
echo "<select name='reg_no'>";
foreach($results as $student_result)
{
echo "<option value ='$student_result->reg_no'> $student_result->reg_no</option>";
}
echo "</select>";
echo "</td>";
echo "</tr>";
$query = db_select('subject');
$query->fields('subject', array('subject_name','credits','subject_code'));
$query->condition('dept_code',$dept,'=') AND $query->condition('semester_appear',$semester,'=') ;
$subject_results = $query->execute();
echo "<tr>";
echo "<td><label for='Subject'>Subject Name</label></td>";
echo "<td>";
echo "<select name = 'sub_name' id = 'sub_name'>";
foreach($subject_results as $subjects_result)
{
echo "<option value ='$subjects_result->subject_code'> $subjects_result->subject_name</option>";
}
echo "</select>";
echo "</td>";
echo "</tr>";
echo "<tr>";
echo "<td><label for='Subject'>Subject Serial Number</label></td>";
echo "<td>";
echo "<select name='subject_serial' id = 'sub_name'>";
if ($semester == "SEMESTER-I")
{
for($i=101; $i<=110; $i++ )
{
echo "<option value ='$i'>$i</option>";
}
}
elseif ($semester == "SEMESTER-II")
{
for($i=201; $i<=210; $i++ )
{
echo "<option value ='$i'>$i</option>";
}
}
elseif ($semester == "SEMESTER-III")
{
for($i=301; $i<=310; $i++ )
{
echo "<option value ='$i'>$i</option>";
}
}
elseif ($semester == "SEMESTER-IV")
{
for($i=401; $i<=410; $i++ )
{
echo "<option value ='$i'>$i</option>";
}
}
echo "</select>" ;
echo "</td>";
echo "</tr>";
echo "</table>";
}
else
{
return "please check the your input";
}
How to add select box field dynamically after clicking add button (the selected box contain the datas from database after clicking the add button, and same selected value store in database) by using php or javascript and store selected value in selected box to database
Create a PHP page that returns the required HTML string only
And then on client side using jquery you can append that html to desired element
e.g.
$("#btnAddnew").click(function(){
$.get('ajax/test.php?id=1', function(data) {
$('#divDropdown').html(data);
});
});
Then in post you can pass the selected dropdown's value using javascript
e.g. If it is like
then $("#drpRegNum").val() would give you the selected value

Categories

Resources