I am using php to insert into Microsoft SQL table and the below is my code:
$server = "**/**,1433";
$connectionInfo = array( "Database"=>"***", "UID"=>"**", "PWD"=>"******" );
$conn = sqlsrv_connect( $server, $connectionInfo );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
if(!empty($_POST['check_list'])) {
foreach($_POST['check_list'] as $check) {
$sql = "SELECT Item.HQID, Item.ItemLookupCode, Item.Description, Item.ExtendedDescription, Item.SalePrice, Item.Price, Item.CategoryID FROM Item WHERE Item.HQID = '$check'";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$html_table = '<table border="1" cellspacing="0" cellpadding="2">';
$html_table .= '<form method="post" action="upload.php"><tr><td width="350" align ="center">' .$row['Description']. '</td><td width="350" align ="center">' .$row['ExtendedDescription']. '</td><td width="130" align="center">'
.$row['ItemLookupCode']. '<td width="100" align="center">' .$row['SalePrice']. '</td><td width="100" align="center">' .$row['Price']. '</td><td width="200" align="center"><input
type="text" size="24" name="stitle"></td><td width="100" align="center"><input type="text" size="8" name="wprice"></td><td width="120" align="center"><input type="text" size="10" name="scategory"></td><td width="220" align="center"><input
type="text" size="28" name="sbody"></td></tr>';
$html_table .= '</table>';
echo $html_table;
}
}
}
}
?>
<input type="submit" value="Upload this page" ></form>
I have an <input> with name="stitle" and I want the PHP code to take values from each <input> but currently it picks up the value just from the first <input>. How do I fix this?
Your post is horrible formatted, but I think you're looking for the array notation.
You can make something like that:
<input type="text" size="24" name="stitle[]">
The $_POST array field stitle is an array with all values after submitting the form.
OK, a simple example of the form, ignoring all extra syntactical mark-up
<pre>
<?php print_r($_POST); ?>
</pre>
<form method="POST" action="">
<input type="text" size="24" name="stitle[]" />
<input type="text" size="24" name="stitle[]" />
<input type="text" size="24" name="stitle[]" />
</form>
Now, anything you enter into those three text boxes will all be returned, and be accessible in the "$_POST" variable.
If you do not want to use the array style inputs [] and you have control over the qty of fields then you can also do the following:
for($f=0; $f < 5; $f++){
echo '<input type="text" name="foo_'.$f.'">';
}
/*-----------server-side------------*/
for($f=0; $f < 5; $f++){
if(isset($_POST['foo_'.$f])){
//do something
}
}
You can use this simple code for multiple simple input
$stitle=$_POST['stitle'];
for($j=0;$j<count($stitle);$j++)
{
echo $stitle[$j]."<br>";
}
Related
I don't have much experience with php that's why I hope someone can help me to solve the problem.
I am trying to extend my database with new files. I need to be able to type in four different values in my form and save the form with the typed in values. If I only use the first input-tag #inschriftennummer1, it works. My saved form shows me what I've typed in. But I need three more inputs in order to tag the document with 4 values. If I use the code like that, no input value is shown when I save the form.
Maybe someone has a solution :)
<body>
<form name="Formular" method="post" action="">
<table style="width: 100%;">
<tr>
<td style="width: 0%;">
</td>
<td style="width: 85%;">
<?php
if (isset($_GET["change"]))
{
$xml = simplexml_load_file("Inschriften/".$_GET["change"].".xml");
echo '<input type="hidden" name="inschriftennummerAlt" value="'.$xml- >Inschriftennummer.'"/>';
echo '<input type="hidden" name="change"/>';
}
else
{
$xml = simplexml_load_file("Inschriften/Null.xml");
}
/*Gibt zu einem String die jeweilige Hexadezimalform zurück*/
function strToHex($string)
{
$hex='';
for ($i=0; $i < strlen($string); $i++)
{
$hex .= dechex(ord($string[$i]));
}
return str_replace("da", "", $hex);
}
/*Gibt zu einer Hexadezimalform den jeweiligen String zurück*/
function hexToStr($hex)
{
$string='';
for ($i=0; $i <strlen($hex)-1; $i+=2)
{
$string .= chr(hexdec($hex[$i].$hex[$i+1]));
}
return $string;
}
?>
<div class="main">
<div class="meta">
<table>
<tbody>
<tr>
<td colspan="2">
<?php
if (strlen($_GET["inschriftennummer"] == 0))
{
// echo "Bitte Inschriftennummer überprüfen.";
}
?>
</td>
</tr>
<tr>
<td class="I"><span class="label">Inschriftennummer</span>:</td>
<?php echo '<input type="hidden" name="inschriftvorher" value="'.$xml- >Inschriftennummer.'">'; ?>
<td class="II">
<input name="inschriftennummer1" type="text" size="7" value="<?php echo str_replace("_", " ", $xml->Inschriftennummer);?>"/>
<input name="inschriftennummer2" type="text" size="7" value="<?php echo str_replace("_", " ", $xml->Inschriftennummer);?>"/>
<input name="inschriftennummer3" type="text" size="7" value="<?php echo str_replace("_", " ", $xml->Inschriftennummer);?>"/>
<input name="inschriftennummer4" type="text" size="7" value="<?php echo str_replace("_", " ", $xml->Inschriftennummer);?>"/>
</td>
I have tried out some code for dynamic insertion of data using array but the issue am facing is in a single row same data is been inserted and even if check box are left un-checked data value is inserted ignoring the checked value inside a "while-loop"..I am new to this array concept please help me out.
.php
<form id="form" name ="form" method = "POST" action="move_ppl.php" class="wizard-big" autocomplete = "off" enctype="multipart/form-data">
<div class="col-md-12">
<?php
$con = mysqli_connect("localhost","***","***","***");
$query = ("SELECT * FROM profile");
$result = mysqli_query($con, $query);
while ($row = $result->fetch_assoc())
{
echo '
<tr>
<td align="left">' . $row['via'] . '<input type="hidden" name="type[]" value="' . $row['via'] . '"></td>
<td align="left"> <input type="checkbox" name="type[]" value="macro"/> Macro </td>
<td align="left"> <input type="checkbox" name="type[]" value="micro"/> Micro </td>
<td align="left"> <input type="checkbox" name="type[]" value="nano"/> Nano </td>
</tr>';
}
?>
<input style="width: 100%;" type="submit" name = "submit" id = "submit" value="Move" class="btn btn-info"><br><br>
</form>
DB.php
<?php
session_start();
define('HOST','localhost');
define('USER','***');
define('PASS','***');
define('DB','***');
$response = array();
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
if(isset($_POST["submit"]) && isset($_POST["type"])){
//receiving post parameters
$types = $_POST["type"];
if(sizeof($types) > 0 ){
foreach($types as $type){
// create a new user profile
$sql = "INSERT INTO ppl_tbl (vault_no, via, gname, ppl, macro, micro, nano, created_at) VALUES ('".$_SESSION['via']."', '".$_SESSION['vault_no']."', '".$_SESSION['gname']."', '".$type."','".$type."','".$type."','".$type."', NOW())";
if(mysqli_query($con,$sql)){
header('Location: macro_ppl.php');
}else{
$response["error"] = true;
$response["error_msg"] = "INSERT operation failed";
echo json_encode($response);
}
}
}
}
?>
First of all checkbox values will not be present in the post if they are not set.
Second of all you add many results cause you call insert sql in the loop.
You can use:
var_dump($_POST['type']);
so you will see how the structure actually look like.
There are many ways to make this work one could be:
//setting the variables first
$ppl = 0;
$macro = 0;
$micro = 0;
$nano = 0;
//then run the loop to set them
foreach($types as $type){
if(in_array($type,['ppl','macro','micro','nano'])) //just to be sure nobody pass something else so we will not override other variables
$$type = 1;
}
//then write the query
$sql = "INSERT INTO ppl_tbl (vault_no, via, gname, ppl, macro, micro, nano, created_at) VALUES ('".$_SESSION['via']."', '".$_SESSION['vault_no']."', '".$_SESSION['gname']."', '".$ppl."','".$macro."','".$micro."','".$nano."', NOW())";
You are doing it wrong, just submit a form with data array
Form
<form id="form" name ="form" method = "POST" action="someForm.php">
<tr>
<td align="left"> <input type="checkbox" name="type[]" value="macro"/> Macro </td>
<td align="left"> <input type="checkbox" name="type[]" value="micro"/> Micro </td>
<td align="left"> <input type="checkbox" name="type[]" value="nano"/> Nano </td>
</tr>
</form>
someForm.php
if (isset($_POST['type'])) {
foreach ($_POST['type'] as $myType) {
echo $myType
}
}
Your Form
<form id="form" name ="form" method = "POST" action="move_ppl.php" class="wizard-big" autocomplete = "off" enctype="multipart/form-data">
<?php
$con = mysqli_connect("localhost","***","***","***");
$query = ("SELECT * FROM profile");
$result = mysqli_query($con, $query);
while ($row = $result->fetch_assoc())
{
?>
<tr>
<td align="left"><?php echo $row['via'] ?><input type="hidden" name="type[]" value="<?php echo $row['via'] ?>"></td>
<td align="left"> <input type="checkbox" name="type[]" value="macro"/> Macro </td>
<td align="left"> <input type="checkbox" name="type[]" value="micro"/> Micro </td>
<td align="left"> <input type="checkbox" name="type[]" value="nano"/> Nano </td>
</tr>
<?php
}
?>
<input style="width: 100%;" type="submit" name = "submit" id = "submit" value="Move" class="btn btn-info"><br><br>
</form>
In PHP file
if (isset($_POST['submit'])) {
if(isset($_POST['type'])) {
foreach ($_POST['type'] as $value) {
echo $value;
/*add this in the query, this will return the value of checkbox which are checked*/
}
}
}
I am having trouble with my current code below. I am trying to retain the user entered information that is input into the a and b data boxes using PHP_SELF but this does not happen. I think I may have to have some kind of POST statement made in the HTML code, but I'm not sure. Also, I am trying to use isset() to determine if BOTH fields are being entered, and it doesnt seem to be working as die() is being called every time.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<html>
<body>
<form method="post" action="<?php echo $PHP_SELF;?>">
<table align="center" border="0">
<tr>
<td>a:</td>
<td ><input type="text" VALUE="<?php $a ?>" name="a" size="6" maxlength="6"></td>
</tr>
<tr>
<td>b:</td>
<td ><input type="text" VALUE="<?php $b ?>" name="b" size="10" maxlength="10"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Submit Order"></td>
</tr>
</table>
</form>
<?php
if(isset($_POST['a']) && isset($_POST['b'])){
$a = $_POST['a'];
$b = $_POST['b'];
$query = "SELECT * FROM DATA WHERE $a = DATA1 $b = DATA2";
$name= mysql_query($query) or die();
echo '<table border = 1>';
while($row = mysql_fetch_assoc($name))
{
echo '<tr>';
foreach($row as $cvalue) {
print '<td>'.$cvalue.'</td>';
}
echo '</tr>';
}
echo '</table>';
}
?>
I'll go through your code and see what I find. No promises. I might not find the problem, but I might help in other ways.
<tr>
<td>a:</td>
<td ><input type="text" VALUE="<?php $a ?>" name="a" size="6" maxlength="6" /></td>
</tr>
<tr>
<td>b:</td>
<td ><input type="text" VALUE="<?php $b ?>" name="b" size="10" maxlength="10" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Submit Order" /></td>
</tr>
You should self close your input tags (brings you closer to XHTML standards). Also, the PHP in the <input> controls is malformed. The statements should read something like this:
<td ><input type="text" VALUE="<?php echo Sa; ?>" name="a" size="6" maxlength="6" /></td> // echo() statements!
<td ><input type="text" VALUE="<?php echo Sb; ?>" name="a" size="6" maxlength="6" /></td>
<td ><input type="text" VALUE="<?php echo Sc; ?>" name="a" size="6" maxlength="6" /></td>
<?php if(isset($_POST['a']) && isset($_POST['b'])){
Or, if you only want to make one call to isset()
<?php
if(isset($_POST['a'], $_POST['b'])){
PHP Manual: isset()
$query = "SELECT *
FROM DATA
WHERE $a = 'DATA1' AND $b = 'DATA2'";
Make sure your query string is quoted properly if fields $a and $b refer to string values.
However, since $a and $b are what the user entered, I believe your is a bit backwards.
$query = "SELECT *
FROM DATA
WHERE DATA1 = '$a'
AND DATA2 = '$b'";
Ah, now that makes more sense. If the DATA1 and DATA2 fields refer to integers (int values), the query would look like this
$query = "SELECT *
FROM DATA
WHERE DATA1 = $a
AND DATA2 = $b";
As for the following code snippet ... you are not using $cvalue as an associative array.
PHP Manual: mysql_fetch_assoc()
If you only want the values (and not the keys and values), you might use mysql_fetch_array()
while($row = mysql_fetch_assoc($name))
{
echo '<tr>';
foreach($row as $cvalue)
{
print '<td>'.$cvalue.'</td>';
}
}
echo '</tr>';
}
... this might work a bit better for you.
while($row = mysql_fetch_array($name))
{
echo '<tr>';
foreach($row as $cvalue) //Now you are cooking with gas.
{
echo '<td>'.$cvalue.'</td>';
}
echo '</tr>';
}
Give mysqli functions a chance if you have time to change your code. PHP Manual: MySQLi
Hope that was not too brutal. Just trying to help. :-)
thank you for your answer meanwhile i got this code for inserting the multiple data, and it really works but my problem is it adds the fisrt column then after finished then it executes the second column i want them to excecute insert f1 then f2 then f1 then f2 again:
just imagine i have 4 input with same name f1 and f2
Inserting multiple entries into table from the same form please refer on this post
Your are missing names in all of your form fields
/*PHP code where the form submit, and repeat the same for other fields like descriptionField*/
<?php
for($i = 0; $i <= count ( $_POST ['dateField'] ); $i ++) {
// Do what ever you want with data
var_dump ( $_POST ['dateField'] [$i] );
}
?>
HTML Code, names added
<tr class="item-row">
<td class="item-name"><div class="delete-wpr">
<textarea>Date</textarea>
<a class="delete" href="javascript:;" title="Remove row">X</a>
</div></td>
<td class="description"><textarea name="descritpionField[]">Description</textarea></td>
<td><textarea name="dateField[]" style="text-align: center;"
class="asd">0</textarea></td>
<td><textarea name="dateField[]" style="text-align: center;"
class="qty">0</textarea></td>
<td><textarea name="dateField[]" style="text-align: center;"
class="cost">0</textarea></td>
<td style="text-align: center;"><span class="price">0</span></td>
</tr>
If i understand correctly
If this fields in form, then set 'name' attr to fields like name="user[]"
When u'll submit the form, all values of "user[]" fields will in array. Just do print_r() and you will see, what i try to explain
Also u can do it in javascript. . .
Just grab all values in array. . .
User "Noor" already post example for you
Please try this code,
<?php
echo "<pre>";
if(isset($_POST['submit'])){
print_r($_POST['data']);//RESULT WILL GET AN ARRAY
}
?>
<form action="" method="post">
<table>
<?php
//$items = // DATA FROM DB
//$items_count = count($items);
$items_count = 5;
for($i=0;$i<$items_count;$i++) {
?>
<tr class="item-row-<?php echo $i;?>">
<td class="item-name"><div class="delete-wpr"><textarea name="data[<?php echo $i;?>]['date']">Date</textarea><a class="delete" href="javascript:;" title="Remove row">X</a></div></td>
<td class="description"><textarea name="data[<?php echo $i;?>]['description']">Description</textarea></td>
<td><textarea name="data[<?php echo $i;?>]['age']" style="text-align:center;" class="asd">0</textarea></td>
<td><textarea name="data[<?php echo $i;?>]['dob']" style="text-align:center;" class="qty">0</textarea></td>
<td><textarea name="data[<?php echo $i;?>]['status']" style="text-align:center;" class="cost">0</textarea></td>
<td style="text-align:center;" ><span class="price">0</span></td>
</tr>
<?php } ?>
<table>
<input type="submit" class="button" name="submit" value="submit" />
</form>
Answer fo the post (Trouble with $_POST [duplicate])
I don't know if I understand your concern.
I think you are trying to create a quiz. And so the user must validate several attempts. your problem is that you can not accumulate the different answers following a table. so here is a solution.
<?php
$good_answers = array(
"easy1" => array("4","3","5","2","6","9","7","8","1" ),
"easy2" => array("6","8","2","5","7","1","4","9","3" ),
"easy3" => array("1","9","7","8","3","4","5","6","2" ),
"easy4" => array("8","2","6","1","9","5","3","4","7" ),
"easy5" => array("3","7","4","6","8","2","9","1","5" ),
"easy6" => array("9","5","1","7","4","3","6","2","8" ),
"easy7" => array("5","1","9","3","2","6","8","7","4" ),
"easy8" => array("2","4","8","9","5","7","1","3","6" ),
"easy9" => array("7","6","3","4","1","8","2","5","9" )
);
if(isset($_POST['row'])){
$easy = false;
$client_responses = $_POST['row']; // EX: [" "," "," " ,"2","6"," " ,"7"," " ,"1"]
$old = json_decode($_POST['old']);
$old[] = $client_responses;
// Or make array_push($old,$client_responses); if you prefere
foreach ($good_answers as $easy => $responses) {
if($client_responses === $responses){
$easy = $responses;
break;
}
}
// generating table for HTML of client responses
echo '<table>';
// saving old responses
echo '<input type="hidden" value="'. json_encode($old) .'" name="old">';
foreach ($old as $number => $row) {
echo '<tr id="row'. $number .'">';
for ($i=0; $i < count($row); $i++) {
echo '<td class="cellTop">';
echo '<input type="text" maxlength="1" name="row" value="'. $row[$i].'"/>';
echo '</td>';
}
echo '</tr>';
}
echo '</table>';
}
I need some js/ajax/jquery script saving data to database dynamically when I check the check-box.
the checkboxes at the moment or loaded in next to records and change the variable in the database depending if its checked or not.but i have to reload the page after i select one to save it to the database. i can do everything else but understand how to implement the ajax to this so i don't have to submit the query and refresh the page every time. any help is greatly appreciated.
<form name="form1aa" method="post" action="process.php?fn=<? echo $rows['first']; ?>&class=<?php echo $rows['class']; ?>&last=<?php echo $rows['last']; ?>
&model=<?php echo $rows['model']; ?>&cas=<?php echo $rows['cases']; ?>&upid=<?php echo $id; ?>&group=1" id="form1a" >
<select name="type" onchange=" fill_damage (document.form1aa.type.selectedIndex); ">
<option value="Hardware">Hardware</option>
<option value="Software">Software</option>
</select>
<select name="damage">
</select>
<input type=text name="comment" placeholder="Comments Box">
<input type=text name="cost" placeholder="Cost">
<input type="submit" value="Save" name="Save">
</form>
<?php
//Job Status
if(isset($_POST['checkbox'])){$checkbox = $_POST['checkbox'];
if(isset($_POST['activate'])?$activate = $_POST["activate"]:$deactivate = $_POST["deactivate"])
$id = "('" . implode( "','", $checkbox ) . "');" ;
$sql="UPDATE repairs SET status = '".(isset($activate)?'Completed':'In Progress')."' WHERE id=$id" ;
$result = mysql_query($sql) or die(mysql_error());
}
//End Job Status
//Payment Status
if(isset($_POST['paycheck'])){$paycheck = $_POST['paycheck'];
if(isset($_POST['paid'])?$paid = $_POST["paid"]:$unpaid = $_POST["unpaid"])
$id = "('" . implode( "','", $paycheck ) . "');" ;
$sql="UPDATE repairs SET paid = '".(isset($paid)?'Paid':'Unpaid')."' WHERE id=$id" ;
$result = mysql_query($sql) or die(mysql_error());
}
//End Payment Status
//Return Status
if(isset($_POST['retcheck'])){$retcheck = $_POST['retcheck'];
if(isset($_POST['ret'])?$ret = $_POST["ret"]:$unret = $_POST["unret"])
$id = "('" . implode( "','", $retcheck ) . "');" ;
$sql="UPDATE repairs SET ret = '".(isset($ret)?'Retuned':'In Office')."' WHERE id=$id" ;
$result = mysql_query($sql) or die(mysql_error());
}
//End Return Status
$sql="SELECT * FROM $tbl_name";
if(isset($_POST['all'])){
$sql="SELECT * FROM $tbl_name";
}
if(isset($_POST['tpc'])){
$sql="select * from $tbl_name WHERE class LIKE '1%'";
}
if(isset($_POST['drc'])){
$sql="select * from $tbl_name WHERE class LIKE 'D%'";
}
if(isset($_POST['bsc'])){
$sql="select * from $tbl_name WHERE class LIKE 'B%'";
}
$result=mysql_query($sql);
?>
<form name="frmactive" method="post" action="">
<input name="activate" type="submit" id="activate" value="Complete Job" />
<input name="paid" type="submit" id="Payment" value="Payment Status" />
<input name="ret" type="submit" id="ret" value="Returned 2 Student" />
<br />
<a id="displayText" href="javascript:toggle();">Show Extra</a>
<div id="toggleText" style="display: none">
<br />
<input name="unret" type="submit" id="unret" value="In Office" />
<input name="unpaid" type="submit" id="unpaid" value="Not Paid" />
<input name="deactivate" type="submit" id="deactivate" value="In Progress" /></div>
<table width="1000" border="0" cellpadding="3" cellspacing="1">
<thead>
<th width="67" align="center"><strong>Start Date</strong></th>
<th width="50" align="center"><strong>Cases</strong></th>
<th width="34" align="center"><strong>Type</strong></th>
<th width="120" align="center"><strong>Damage</strong></th>
<th width="31" align="center"><strong>Comment</strong></th>
<th width="31" align="center"><strong>Cost</strong></th>
<th width="90" align="center"><strong>Payment Status</strong></th>
<th width="100" align="center"><strong>Returned 2 Student</strong></th>
<th width="100" align="center"><strong>Job Status</strong></th>
</thead>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td><? echo $rows['start']; ?></td>
<td><? echo $rows['cases']; ?></td>
<td><? echo $rows['type']; ?></td>
<td width="70"><? echo $rows['damage']; ?></td>
<td width="70"><? echo $rows['comment']; ?></td>
<td><? echo "$"; echo $rows['cost']; ?></td>
<!--Payment Display(Start)-->
<?php
if($rows['paid']=="Paid")
{
?>
<td><input name="paycheck[]" type="checkbox" id="paycheck[]" value="<? echo $rows['id']; ?>">
<? echo $rows['paid'];?>
</td>
<?
}
if($rows['paid']=="Unpaid")
{
?>
<td width="21"><input name="paycheck[]" type="checkbox" id="paycheck[]" value="<? echo $rows['id']; ?>">
<? echo $rows['paid']; ?>
</td>
<?
}
if($rows['ret']==""){
?>
<td width="50">No Data</td>
<?
}
?>
Do it with jQuery, a simple example could be:
HTML:
<input type="checkbox" name="option1" value="Milk">
<input type="checkbox" name="option2" value="Sugar">
<input type="checkbox" name="option3" value="Chocolate">
JS:
$("input[type='checkbox']").on('click', function(){
var checked = $(this).attr('checked');
if(checked){
var value = $(this).val();
$.post('file.php', { value:value }, function(data){
// data = 0 - means that there was an error
// data = 1 - means that everything is ok
if(data == 1){
// Do something or do nothing :-)
alert('Data was saved in db!');
}
});
}
});
PHP: file.php
<?php
if ($_POST && isset($_POST['value'])) {
// db connection
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
// error happened
print(0);
}
mysql_select_db('mydb');
// sanitize the value
$value = mysql_real_escape_string($_POST['value']);
// start the query
$sql = "INSERT INTO table (value) VALUES ('$value')";
// check if the query was executed
if(mysql_query($sql, $link)){
// everything is Ok, the data was inserted
print(1);
} else {
// error happened
print(0);
}
}
?>
Simple put...
$('input:checkbox').click( function() {
clicked = $(this).attr('checked');
if (clicked) {
/* AJAX the server to tell them it was clicked. */ }
else {
/* AJAX the server to tell them it was unclicked. */ } } );
I can make this even simpler. first, you need to ad a checkbox!!
<form name="form1aa" method="post" action="process.php?fn=<? echo $rows['frist']; ?>&class=<?php echo $rows['class']; ?>&last=<?php echo $rows['last']; ?>
&model=<?php echo $rows['model']; ?>&cas=<?php echo $rows['cases']; ?>&upid=<?php echo $id; ?>&group=1" id="form1a" >
<select name="type" onchange="fill_damage(document.form1aa.type.selectedIndex);">
<option value="Hardware">Hardware</option>
<option value="Software">Software</option>
</select>
<select name="damage">
</select>
<input type="text" name="comment" placeholder="Comments Box">
<input type="text" name="cost" placeholder="Cost">
<input type="checkbox" name="somecheck" onchange="if(this.checked)document.form1aa.submit()">Check this to Save.
<input type="submit" value="Save" name="Save">
</form>
<script type="javascript>
//another function that works for onchange="dosubmit(this)"
//IF you put it after the form.
function dosubmit(el) {
if (el.checked) {
document.form1aa.submit();
}
}
</script>
get rid of the spaces in your onchange events where possible.
If you have dynamic checkbox list and you want to dynamically save the clicked one to database or inserting the unchecked one, here how to do that:
Html/PHP
<?php
// $checklists are models that I am getting from db
$checklists = CheckList::getCheckLists(3);
echo '<ul>';
foreach ($checklists as $checklist) {
$isChecked = $checklist->getAnswer($requestID, $checklist->primaryKey);
$checked = $isChecked ? "checked" : "";
echo '<li>';
echo "<input id='{$checklist->primaryKey}'
name='{$checklist->primaryKey}' type='checkbox' {$checked}
value='{$isChecked}' data-request-id='{$requestID}'>
$checklist->check_list_text";
echo '</li>';
}
echo '</ul>';
?>
Jquery
<script>
$("input[type='checkbox']").on('click', function(){
var checkbox = $(this);
var checked = checkbox.prop('checked');
var checklistId = checkbox.attr("id");
$.ajax({
url:"<?= Url::to(['default/add-checklist-answer']) ?>",
// I don't need to write the type here because I am using Yii Framework
// type: 'post',
data: {
checklistId: checklistId,
requestId: checkbox.data('request-id'),
checked: checked
},
success: function(data) {
//alert(data);
console.log(data.firstMessage)
},
error: function(data) {
// alert(data);
}
});
});
</script>
I hope it will work for MVC users.