how to load a value from database in radio button? - javascript

I need to know if you can do this function ... I have a database that has a "boolean" field that accepts 0 or 1 values And I have an HTML page in which there is a radioButton with values Ok or No I must be able to load the boolean value in the radioButton so if in the database the boolean variable is 1 on the HTML page (after executing the SELECT) the radioButton will have OK value if in the database the boolean variable is 0 on the HTML page (after executing the SELECT) the radioButton will have NO value
this is the code of my attempts :
<?php
$servername = "localhost";
$username = "progettocantiere";
$password = "";
$dbname = "my_progettocantiere";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$idAffidataria = $_GET['idAffidataria'];
$sql1 = "SELECT * FROM Affidataria WHERE idAffidataria = '{$idAffidataria}'";
$result = $conn->query($sql1);
$details = $result->fetch_array();
$savedNomeCantiere = $details["nomeCantiere"];
$savedAddettoSicurezza = $details["addettoSicurezza"];
$savedMailAffidataria = $details["mailAffidataria"];
$savedContrattoDiAppalto = $details["contrattoDiAppalto"]; // <--- BOOLEAN <----
$result1 = $conn->query($sql1);
echo($nomeCantiere);
?>
<html>
<body>
<table>
<tr>
<td colspan="2" bgcolor="#CDECFD" style="font-weight: bold">Cantiere</td>
<td colspan="4" bgcolor="#CDECFD"><input type="text" class="form-control" style="width: 100%;" name="cantiereAffidataria" id="cantiereAffidataria" value="<?php echo $savedNomeCantiere; ?>"/> </td>
</tr>
<tr>
<td colspan="2" bgcolor="#CDECFD" style="font-weight: bold">ContrattoDiAppalto</td>
<td bgcolor="#B35556"><form action="">
OK <input type="radio" name="contrattoDiAppalto" id="contrattoDiAppalto" value="<?php echo $savedContrattoDiAppalto; ?>" onchange="color(this)" /> <BR>
NO <input type="radio" name="contrattoDiAppalto" id="contrattoDiAppalto" value="<?php echo $savedContrattoDiAppalto; ?>" onchange="color(this)" checked/>
</form></td>
</tr>
</table>
in other words I have to be able to change the radioButton according to the data provided by the SELECT on the database
I tried to give it the value through <?php echo $savedContrattoDiAppalto; ?>" but I doubt it's right .. I'm running out of ideas .. can someone help me?

Make an variable $checked = 'checked'
Then make an condition to check if it's 1 or 0
$checked = 'checked';
if($savedContrattoDiAppalto != 1){
$checked = ''; // Default is checked, if it isn't 1 then it's empty and will not check your radio.
}
And apply that variable to your input attributes.
<input type="radio" name="contrattoDiAppalto" id="contrattoDiAppalto"
value="<?php echo $savedContrattoDiAppalto; ?>" onchange="color(this)" $checked/>
Full code should be :
<?php
$servername = "localhost";
$username = "progettocantiere";
$password = "";
$dbname = "my_progettocantiere";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$idAffidataria = $_GET['idAffidataria'];
$sql1 = "SELECT * FROM Affidataria WHERE idAffidataria = '{$idAffidataria}'";
$result = $conn->query($sql1);
$details = $result->fetch_array();
$savedNomeCantiere = $details["nomeCantiere"];
$savedAddettoSicurezza = $details["addettoSicurezza"];
$savedMailAffidataria = $details["mailAffidataria"];
$savedContrattoDiAppalto = $details["contrattoDiAppalto"];
$checked = 'checked';
if($savedContrattoDiAppalto != true){
$checked = ''; // if not true then not checked
}
$result1 = $conn->query($sql1);
echo($nomeCantiere);
?>
<html>
<body>
<table>
<tr>
<td colspan="2" bgcolor="#CDECFD" style="font-weight: bold">Cantiere</td>
<td colspan="4" bgcolor="#CDECFD"><input type="text" class="form-control" style="width: 100%;" name="cantiereAffidataria" id="cantiereAffidataria" value="<?php echo $savedNomeCantiere; ?>"/> </td>
</tr>
<tr>
<td colspan="2" bgcolor="#CDECFD" style="font-weight: bold">ContrattoDiAppalto</td>
<td bgcolor="#B35556"><form action="">
OK <input type="radio" name="contrattoDiAppalto" id="contrattoDiAppalto" value="<?php echo $savedContrattoDiAppalto; ?>" onchange="color(this)" $checked/> <BR>
NO <input type="radio" name="contrattoDiAppalto" id="contrattoDiAppalto" value="<?php echo $savedContrattoDiAppalto; ?>" onchange="color(this)" $checked/>
</form></td>
</tr>
</table>

Related

I have to output my data from DataBase and also copy all inputs from form to send them to myself, including real-time multiplying weight*pcs [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I've got some code where I have to input my contact data from client, and output data from MySQL database which creates new rows in table
Also there's additional function which has to be inside the code - but I've no idea how to handle this problem. I have to count the amount of element pieces x their weight in real-time to show the client the total weight the order is going to have.
The problem is I don't know how to make the client see it whenever they change the value of Pieces in <input>.
Lastly, the data from the form and table has to be sent to employee via email.
PHP Code:
<html>
<head>
<meta charset="utf-8" />
<meta name="calculator" content="width=device-width, initial-scale=1"/>
<title>Test</title>
<link rel="stylesheet" href="style.css" >
</head>
<body>
<!-- including calc.php file which contains all variables -->
<?php include 'calc.php'; ?>
<!-- Printing the form -->
<form method="post" action="sendform.php"><br>
<center>
<h1>TEST</h1>
<input id="Name" type="text" placeholder="<?= $form['FIRMA']; ?>" class="form-contact" required><br>
<input id="Adres" type="text" placeholder="<?= $form['ADRES']; ?>" class="form-contact" required><br>
<input id="Email" type="email" placeholder="<?= $form['EMAIL']; ?>" class="form-contact" required><br>
<input id="Country" type="text" placeholder="<?= $form['COUNTRY']; ?>" class="form-contact" value="" size="1" pattern="[0-9]{2}" maxlength="2" required>
<input id="Phone" type="text" placeholder="<?= $form['PHONE']; ?>" class="form-contact" pattern="[0-9]{9}" maxlength="9" required>
<br>
<!-- Printing out the table -->
<table class="table-responsive" border="1">
<thead>
<tr>
<th><?= $form['PRODUCTS']; ?></th>
<th><?= $form['CATALOG']; ?></th>
<th><?= $form['DESC']; ?></th>
<th><?= $form['WEIGHT']; ?></th>
<th><?= $form['TWEIGHT']; ?></th>
<br>
</tr>
</thead>
<tbody>
<?php
# Database connection
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "1234";
$dbname = "data";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
#echo "Connection successfull!";
# Questions for Database
$sql = 'SELECT * FROM `elements`';
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0) {
//output data each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>".'<input class="pcs-input" min=0 maxlength="3" value=0 size="2px" style="background-color: white;" name="inputs[]">';
echo "</td><td>Nr. " . $row["pcode"] . "</td><td> " . $row["fullname"]. "</td><td> " . $row["weight"] . "kg</td><td><div id='sumWeight'></div></td></tr>";
}
} else {
echo "0 Results";
}
mysqli_close($connection);
?>
</tbody>
</table>
<!-- Counting all needed atributes -->
<div id="totalWeight">totalWeight</div>
<!-- Submit btn -->
<br><button name="submit" type="submit" value="Send" class="form-button">Send</button>
</center>
</form>
</body>
</html>
JavaScript Code
<script type="text/javascript">
document.addEventListener(function()
input.OnChange = calculateForm();
function calculateForm() {
var totalWeight = 0;
$(".pcs-input").each(function () {
var pcs = parseInt($(this).val());
if (pcs < 0) {
pcs = 0;
} else {
var weight = parseFloat($(this).data('weight'));
var sumWeight = pcs * weight;
totalWeight += sumWeight;
}
});
document.write(totalWeight.toFixed(2) + ' kg');
}
)};
</script>
Updated
Well it doesn't work again, no errors, just doesn't multiply
I think the problem might be with transporting data from table/database into the variable, any solution?
<?php
# Database connection
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "1234";
$dbname = "data";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
#echo "Connection successfull!";
# Questions for Database
$sql = 'SELECT * FROM `elements`';
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0) {
//output data each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>"."<input type='number' class='pcs-input' id='inputs' data-weight=".$row["weight"];
echo "></input>";
# echo "<tr><td>".$row["id"].'';
echo "</td><td>Nr. " . $row["pcode"] . "</td><td> " . $row["fullname"]. "</td><td> " . $row["weight"] . "kg</td><td><div id='sum-Weight2'></div></td></tr>";
}
} else {
echo "0 Results";
}
#Declaring JavaScript Code inside PHP
mysqli_close($connection);
?>
</tbody>
</table>
<script type="text/javascript">
function calculateForm() {
var totalWeight = 0;
$(".pcs-input").each(function () {
var pcs = parseInt($(this).val());
if (pcs < 0) {
pcs = 0;
} else {
var weight = parseFloat($(this).data('weight'));
var sumWeight = pcs * weight;
$(this).parent().parent().find('.sum-weight2').html(sumWeight.toFixed(2) + ' kg');
totalWeight += sumWeight;
};
$('.totalGewicht').html(totalWeight.toFixed(2) + ' kg');
}
)};
</script>
<!-- Counting all needed atributes -->
<div id="totalWeight"></div>
<!-- Submit btn -->
<br><button name="submit" type="submit" value="Send" class="form-button">Send</button>
</center>
</form>
Overall there are quite a few issues with your code, which can be summarised as problems with
invalid HTML (e.g. duplicate IDs, incorrectly written input element, un-closed table rows, un-closed data attributes)
over-complicated HTML
typing or case errors (e.g. W instead of w)
incorrect CSS selectors in the JavaScript
lack of initial default data (e.g. if there are no numbers in any one of the input boxes, the calculation will fail because trying to add a blank value to another number results in NaN (Not a Number)
calculation did not run when page loads, so data is missing until the user changes something (which is no use, if they want to see the current weight before changing any values)
This client-side demo demonstrates the HTML you need to get your PHP to produce, and the correct JavaScript / jQuery code in order to do the calculations and display the results:
$(function() {
$(".pcs-input").change(calculateForm); //set up the event handler
function calculateForm() {
var totalWeight = 0;
$(".pcs-input").each(function() {
var pcs = parseInt($(this).val());
if (pcs < 0) {
pcs = 0;
}
else {
var weight = parseFloat($(this).data('weight'));
var sumWeight = pcs * weight;
$(this).closest("tr").find('.sum-weight2').html(sumWeight.toFixed(2) + ' kg');
totalWeight += sumWeight;
};
$('#totalWeight').html(totalWeight.toFixed(2) + ' kg');
})
};
calculateForm(); //call it once when the page first loads too, to set up the initial data
});
table
{
border-collapse:collapse;
}
td
{
border: solid 1px black;
padding: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td><input type='number' class='pcs-input' data-weight='3' value='1' /></td>
<td>Nr. 14536</td>
<td>Test 1</td>
<td>3 kg</td>
<td class='sum-weight2'></td>
</tr>
<tr>
<td><input type='number' class='pcs-input' data-weight='15' value='1' /></td>
<td>Nr. 23431</td>
<td>Test 2</td>
<td>15 kg</td>
<td class='sum-weight2'></td>
</tr>
<tr>
<td><input type='number' class='pcs-input' data-weight='4' value='1' /></td>
<td>Nr. 33125</td>
<td>Test 3</td>
<td>4 kg</td>
<td class='sum-weight2'></td>
</tr>
</tbody>
</table>
Total Weight: <span id="totalWeight"></span>
Remember you need to move the focus from the textbox to another element (using mouse or tab key) before the "change" event will fire. (It will also run if you use the up/down buttons on the input box.)
So this means, as well as editing the JavaScript as I've shown, you need to alter the PHP so it outputs the HTML table rows with the structure and data I've demonstrated above.
This should work:
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>"."<input type='number' class='pcs-input' data-weight='".$row["weight"]."' value='1' /></td>";
echo "<td>Nr. ".$row["pcode"]."</td><td>".$row["fullname"]."</td><td>".$row["weight"]."kg</td><td class='sum-weight2'></td></tr>";
}
Resolution:
<body>
<!-- including calc.php file which contains all variables -->
<?php include 'calc.php'; ?>
<!-- Printing the form -->
<form method="post" action="sendform.php"><br>
<center>
<input id="Name" type="text" placeholder="<?= $form['FIRMA']; ?>" class="form-contact" required><br>
<input id="Adres" type="text" placeholder="<?= $form['ADRES']; ?>" class="form-contact" required><br>
<input id="Email" type="email" placeholder="Email" class="form-contact" required><br>
<input id="Country" type="text" placeholder="49" class="form-contact" value="" size="1" pattern="[0-9]{2}" maxlength="2" required>
<input id="Phone" type="text" placeholder="Tel" class="form-contact" pattern="[0-9]{9}" maxlength="9" required>
<br>
<!-- Printing out the table -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class=".table-responsive">
<thead>
<tr>
<th><?= $form['PRODUCTS']; ?></th>
<th><?= $form['CATALOG']; ?></th>
<th><?= $form['DESC']; ?></th>
<th><?= $form['WEIGHT']; ?></th>
<th><?= $form['TWEIGHT']; ?></th>
<br>
</tr>
</thead>
<tbody>
<?php
# Database connection
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "1234";
$dbname = "data";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
#echo "Connection successfull!";
# Questions for Database
$sql = 'SELECT * FROM `elements`';
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0) {
//output data each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>"."<input type='number' class='pcs-input' data-weight='".$row["weight"]."' value='0' min='0' /></td>";
echo "<td>Nr. ".$row["pcode"]."</td><td>".$row["fullname"]."</td><td>".$row["weight"]."kg</td><td class='sum-weight2'></td></tr>";
}
} else {
echo "0 Results";
}
#Declaring JavaScript Code inside PHP
mysqli_close($connection);
?>
</tbody>
</table>
<script type="text/javascript">
$(function() {
$(".pcs-input").change(calculateForm); //set up the event handler
function calculateForm() {
var totalWeight = 0;
$(".pcs-input").each(function() {
var pcs = parseInt($(this).val());
if (pcs < 0) {
pcs = 0;
}
else {
var weight = parseFloat($(this).data('weight'));
var sumWeight = pcs * weight;
$(this).closest("tr").find('.sum-weight2').html(sumWeight.toFixed(2) + ' kg');
totalWeight += sumWeight;
};
$('#totalWeight').html(totalWeight.toFixed(2) + ' kg');
})
};
calculateForm(); //call it once when the page first loads too, to set up the initial data
});
</script>
<!-- Counting all needed atributes -->
Total Weight: <span id="totalWeight"></span>
<!-- Submit btn -->
<br><button name="submit" type="submit" value="Send" class="form-button">Send</button>
</center>
</form>
</body>

How to use PHP loop variable in javascript?

I have run an SQL statement to get all the records I need to show in a HTML table.
I have then run a while loop to display the records from the database. (The code for this is below.)
<table class="projects-table">
<tr>
<th>Complete?</th>
<th>Paid?</th>
<th>Project Name</th>
<th>£ / hr</th>
<th>End Date</th>
<th>Hours Logged</th>
<th><i class="fa fa-trash"></i></th>
</tr>
<?php
$select_id_jobs = mysqli_query($mysqli, "SELECT id FROM users WHERE username='$login_user'");
while($row = mysqli_fetch_array($select_id_jobs)) {
$id_jobs = $row['id'];
}
$select_jobs_with_usrid = mysqli_query($mysqli, "SELECT * FROM jobs WHERE username_id = '$id_jobs';");
while($row = mysqli_fetch_array($select_jobs_with_usrid)) {
?>
<tr id="<?php echo $rowId; ?>">
<td>
<!-- Complete Checkbox -->
<input type="checkbox" id="<?php echo $completeCheck;?>" onclick="compTask();">
</td>
<td>
<!-- Paid checkbox -->
<input type="checkbox" onclick="paidTask()">
</td>
<td>
<?php echo $row['project_title']; ?>
</td>
<td>
<?php echo $row['cost_hour']; ?>
</td>
<td>
<?php echo $row['completion_date']; ?>
</td>
<td>
<?php echo $row['time_spent']; ?>
</td>
<td>
<div class="delete-btn"><a onclick="deleteTask()">DELETE</a></div>
</td>
</tr>
<?php } ?>
</table>
As you can see from the checkbox for completing a task. What I want to do is use javascript so that when the checkbox is checked the text from the other records turns green.
I have included the javascript I am trying to use below. I don't know why but I can't access the inputs ID in order to change the css.
<script>
function compTask() {
if (document.getElementById("<?php echo 'complete-' . $row['id'] ?>").checked == true) {
document.getElementById("<?php echo 'tr' . $row['id']; ?>").style.color = "green";
alert("hello");
} else {
document.getElementById("<?php echo 'tr' . $row['id']; ?>").style.color = "black";
}
}
Okay easy way to do that is to print id as parameter in js function
something like that:
<input type="checkbox" id="<?php echo $completeCheck;?>"
onclick="compTask( '<?php echo $row['id'];?>' );">
and in js function deal with id from parameter:
function compTask(id) {
if (document.getElementById('complete-' + id).checked == true) {
document.getElementById('tr' + id).style.color = "green";
alert("hello");
}
}
Hy,
You need to add id in onclick="deleteTask('<?php echo $row['id']; ?>')">
Now in you function have id:
function deleteTask(id) { console.log(id) }

Updating quantity in cart table

I want that update button should be in that field which I choose.But it appears only in first row and is updating for first row quantity field.
<form action="cart.php?action=update" method="post">
<table>
<tr>
<th colspan="2">ITEM</th>
<th>QUANTITY</th>
<th>PRICE</th>
<th>SUBTOTAL</th>
<th>REMOVE</th>
</tr>
<?php
$query = "select * from cart where customer_id='$user' ";
$result = mysqli_query($con,$query);$b = 0;$c = 0;
while($row = mysqli_fetch_array($result))
{
$productid = $row['product_id'];
$query2 = "select * from product where product_id='$productid'";
$result2 = mysqli_query($con,$query2);
while($row2=mysqli_fetch_array($result2))
{
?>
<tr>
<td rowspan="3"><img src="upload/<?php echo $row2['pimage']; ?>" height="50px" width="50px"></td>
<td rowspan="3"><?php echo $row2['pname']; ?></td>
<td rowspan="3">
<input tpe="text" name="newqty" value="<?php echo $qty = $row['quantity']; ?>" onkeypress="showsubmit()">
<input style="visibility:hidden;width:80px;border-radius:10px;background-color:green;border:none;padding:5px;color:white;" type="submit" name="sub1" id="sub1" value="UPDATE">
<input type="hidden" name="hidcartid" value="<?php echo $row['cart_id'] ?>"/>
<input type="hidden" name="hidproductid" value="<?php echo $row['product_id']; ?>"/>
<script>
function showsubmit()
{
document.getElementById("sub1").style.visibility = "visible";
}
</script>
</td>
<td>Price:<?php echo $sp = $row2['psellingprice']; ?></td>
<?php
$total = $sp * $qty;
?>
<td rowspan="3">
<?php
echo $t = $total;
$b = $b + $t;
?></td>
<td rowspan="3">REMOVE</td>
</tr>
<?php
$action = ( array_key_exists( 'action', $_REQUEST) ? $_REQUEST['action'] : "" );
if($action =="delete")
{
deletecart($_REQUEST['cid']);
}
if($action=="update")
{
echo "update function called";
updatecart();
echo "update function executed";
}
?>
<tr>
<td>Selling Price:<?php echo $p = $row2['pprice']; ?></td>
</tr>
<tr>
<td>You Saved:
<?php
$d = $row2['pdiscount'];
$s = ($p*$d)/100;
echo $q = $s * $qty;
$c = $c + $q;
?> rs.</td>
</tr>
<?php
}
}
?>
</table>
and cart2.php
<?php
function deletecart($cartid)
{
include 'connection.php';
$sql1="delete from cart where cart_id=$cartid";
$executequery = mysqli_query($con,$sql1);
header('location:cart.php');
}
function updatecart()
{
include 'connection.php';
$cartId = $_POST['hidcartid'];
$productId = $_POST['hidproductid'];
$newqty = $_POST['newqty'];
echo("inside update function");
// update product quantity
$sql = "UPDATE cart
SET quantity = $newqty
WHERE cart_id = $cartId";
mysqli_query($con,$sql);
header('location:cart.php');
}?>
For row onw everything is fine.But for row2 update button appears in row1 and not updating at all.
<input tpe="text" name="newqty" value="<?php echo $qty = $row['quantity']; ?>" onkeypress="showsubmit(<?php echo $row['cart_id'] ?>)">
<input style="visibility:hidden;width:80px;border-radius:10px;background-color:green;border:none;padding:5px;color:white;"
type="submit"
name="sub_<?php echo $row['cart_id'] ?>"
id="sub_<?php echo $row['cart_id'] ?>"
value="UPDATE">
<script>
function showsubmit(id)
{
document.getElementById("sub_"+id).style.visibility ="visible";
}
</script>

Updating two tables using prepared statements and PDO

Am trying to update data in two tables and according to my codes below, only the first table 'student_information' is getting updated
leaving out the 'training_information' table not updated. The two tables are linked by IndexNo. I need guidance with my code on how I can update both the tables at once using my sample prepared statements.
Please follow also that I try to get the id value using the URL as given. This helps me view and update data about one distinct column with IndexNo in one operation.
URL: http://localhost/sample/updateStudentInfo.php?id=14
updateStudentInfo.php code as below
<?php
// Connect to MySQL database
function connect(){
try{
$dbConn = new PDO('mysql:host=localhost; dbname=hpcz', 'root', 'root');
$dbConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbConn;
}
catch(PDOException $e){
echo $e->getMessage();
}
}
$dbh = connect();
//gets the value of the id from the URL
$id = htmlspecialchars($_GET["id"]);
$sql = "SELECT
student_information.IndexNo,
student_information.SurName,
student_information.FirstName,
student_information.MiddleName,
grade_obtained.Grade,
secondary_school.SchoolName
FROM student_information
LEFT JOIN training_information
ON student_information.IndexNo = training_information.IndexNo
WHERE student_information.IndexNo='$id'";
$result = $dbh->prepare($sql);
$result->execute();
while ($row = $result->fetch(PDO::FETCH_ASSOC))
{
//Initializing the id from URL with the IndexNo from the database
$id=$row["IndexNo"];
?>
<div><form method="post" >
<table width="500" border="1" >
<tr>
<td colspan="4">Update Student Information</td>
</tr>
<tr>
<td colspan="4"><div align="center"><strong>Applicant Information</strong></div></td>
</tr>
<tr>
<td><div align="right">Sur Name:</div></td>
<td><input type="text" name="surname" id="surname" value="<?php echo $row['SurName']; ?>"/></td>
<td><div align="right">First Name:</div></td>
<td><input type="text" text-input" name="fname" id="fname" value="<?php echo $row['FirstName']; ?>"/></td>
</tr>
<tr>
<td><div align="right">Middle Name:</div></td>
<td><input type="text" name="mname" id="mname" value="<?php echo $row['MiddleName']; ?>"/></td>
<td><div align="right">NRC/Passport No:</div></td>
<td><input type="text" name="nrc" id="nrc" value="<?php echo $row['NRCPassportNo']; ?>"/></td>
</tr>
<tr>
<td colspan="4"><div align="center"><strong>Training Information</strong></div></td>
</tr>
<tr>
<td><div align="right">Secondary School Attended:</div></td>
<td><select name="secondarysch" id="secondarysch" >
<option selected="selected"><?php echo $row['SchoolName']; ?></option>
</select></td>
<td><div align="right">Grade Obtained:</div></td>
<td><select name="grade" id="grade" >
<option selected="selected"><?php echo $row['Grade']; ?></option>
</select></td>
</tr>
<input type="hidden" name="id" id="id" value="<?php echo $row['IndexNo']; ?>"/>
<tr>
<td colspan="4"><div align="center"><button id="update">Update</div></td>
</tr>
</table>
<?php }?>
</form>
JavaScript code:
$(document).ready(function(){
$("#update").click(function(){
/*Applicant Information*/
var vid = $("#id").val();
var vsurname = $("#surname").val();
var vmname = $("#mname").val();
var vfname = $("#fname").val();
/*Training Information*/
var vsecondarysch = $("#secondarysch").val();
var vgrade = $("#grade").val();
/*Jquery post method */
$.post("http://localhost/sample/sendUpdateStudentInfo.php",
{
id : vid,
surname : vsurname,
mname : vmname,
fname : vfname,
secondarysch :vsecondarysch,
grade : vgrade
},
/*Handles response from server*/
function(response){
alert(response);
});
alert("You are here");
});
});
sendUpdateStudentInfo.php code:
<?php
$method = $_SERVER['REQUEST_METHOD'];
function connect(){
try{
$dbConn = new PDO('mysql:host=localhost; dbname=hpcz', 'root', 'root');
$dbConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbConn;
}
catch(PDOException $e){
echo $e->getMessage();
}
}
/*Checks if method is HTTP POST*/
if(strtolower($method) == 'post'){
/*Applicant Information*/
$id = addslashes($_POST['id']);
$surname = addslashes($_POST['surname']);
$mname = addslashes($_POST['mname']);
$fname = addslashes($_POST['fname']);
/*Training Information*/
$secondarysch = addslashes($_POST['secondarysch']);
$grade = addslashes($_POST['grade']);
try {
$dbHandler = connect();
$dbHandler->beginTransaction();
$setInfo = "UPDATE student_information
SET
SurName = :vSurname,
MiddleName = :vMName,
FirstName = :vFName
WHERE
IndexNo = '$id'";
$stmt = $dbHandler->prepare($setInfo);
$stmt->bindParam(':vSurname', $surname);
$stmt->bindParam(':vMName', $mname);
$stmt->bindParam(':vFName', $fname);
$stmt->execute();
$stmt->closeCursor();
$setTrainingInfo = "UPDATE training_information
SET
SecondarySchoolID = :Secondarysch,
GradeObtainedID = :Grade
WHERE
IndexNo = '$id'";
$stmt = $dbHandler->prepare($setTrainingInfo);
$stmt->bindParam(':Secondarysch', $secondarysch);
$stmt->bindParam(':Grade', $grade);
$stmt->execute();
$stmt->closeCursor();
$dbHandler->commit();
echo "The Operation was Successful!!!!!!";
} catch (PDOException $e) {
$dbHandler->rollback();
die($e->getMessage());
}
}else{
echo "Oops! Make sure Method is POST";
}
?>

Auto submit php form

I want to submit a form after some interval periodically.
I have tried as follows.
<script language="JavaScript">
function fncAutoSubmitForm()
{
//alert('test alert');
alert("B : "+document.getElementById('myform').id);
document.getElementById('myform').submit();
alert("A : "+document.getElementById('myform').id);
setTimeout("fncAutoSubmitForm();",5000);}
</script>
displayPage.php code as follows
<body onload="fncAutoSubmitForm();">
<form id="myform" name="myform" action="code.php" method="post">
some controls
</form>
</body>
here, "displayPage.php" submits the page to "code.php"
"code.php" performs required action and redirects to "displayPage.php"
It works fine when I dont use autosubmit. i.e. fncAutoSubmitForm() function
but when I use fncAutoSubmitForm() "displayPage.php" disappears
here is the actual code
<form action="code.php" method="post" id="myform" name="myform" onload='setGenLeadId();'>
<tr><td colspan="2"><?php if($row1['lead_call_type']=="C"){echo"<font color=red>CALLBACK Lead</font>";}?></td>
<td align = "right"><strong>Lead Id :</strong> </td>
<!--<td><b><font color="red"></font>Reference Number</b></td>-->
<td align="left"><?php echo "" . $row1['lead_id'] ."";?></td>
</tr>
<tr>
<td align="right" ><b>Name :</b></td>
<td align="left"><input name="custname" id="custname" class="textbox" style="width: 100%;height: 25%;" maxlength="140" type="text" value="<?php echo htmlspecialchars($row1['lead_fname'])?>"></td>
<td align="right"><b>Phone :</b></td>
<td align="left"><input name="phone" id="phone" style="width: 100%;height: 25%;" maxlength="10" type="text" value = "<?php echo "" . $row1['lead_phone1'] ."";?>" ></td>
</tr>
<tr>
<td align="right"><b>City :</b></td>
<td align="left">
<input name="city" id="city" class="textbox" style="width: 100%;height: 25%;" maxlength="140" type="text" value="<?php echo "" . $row1['lead_city'] ."";?>">
</td>
<td align="right"><b>State :</b></td>
<td align="left" >
<input name="state" id="state" class="textbox" style="width: 100%;height: 25%;" maxlength="140" type="text" value="<?php echo "" . $row1['lead_state'] ."";?>">
</td>
</tr>
<tr>
<td align="right"><b>Email-ID :</b></td>
<td align="left" ><input name="email" id="email" style="width: 100%;height: 25%;" class="textbox" type="text" value = "<?php echo "" . $row1['lead_email'] ."";?>"></td>
<td align="right"><b>Source </b></td>
<td ><input type="text" name="source" id = "source" style ="width:100%;resize: none;" maxlength="900" value="<?php echo "". $row1['lead_source'] ."";?>"></td>
</tr>
<tr>
<td align="right"><b>Address : </b></td>
<td>
<textarea type="text" name="address" id = "address" style ="width:100%;resize: none;" maxlength="900" ><?php echo "". $row1['lead_address1'] ."";?></textarea>
</td>
<td align="right"><b>Zip Code :</b></td>
<td align="left"><input name="zip" id="zip" class="textbox" style="width: 100%;height: 25%;" maxlength="140" type="text" value="<?php echo htmlspecialchars($row1['lead_zip'])?>"></td>
<!--<td align="right"><b>Phone :</b></td>
<td align="left"><input name="phone" id="phone" style="width: 100%;height: 25%;" maxlength="10" type="text" value = "<?php //echo "" . $row1['lead_phone1'] ."";?>" ></td>-->
</tr>
<tr>
<td align="right"><b>Rounds :</b></td>
<td>
<?php
$query = mysql_query("SELECT param_field_value,param_field_itemdata FROM cti_service_parameters where param_service_id=$service_id and param_field_name='rounds'");
$k=0;
echo "<select style='width: 100%;' id='rounds' name ='rounds'>";
echo "<option value=".$row1['lead_rounds']." selected>".$row1['lead_rounds']."</option>";
while($row = mysql_fetch_array($query))
{
$value[$k] = $row['param_field_value'];
$item[$k] = $row['param_field_itemdata'];
if($field_val == $item[$k])
echo "<option value='$value[$k]' selected>$value[$k]</option>";
else
echo "<option value='$value[$k]'>$value[$k]</option>";
$k = $k + 1;
}
echo "</select>";
?>
</td>
<td align="right"><b>Preparing For IIT-JEE :</b></td>
<td align="left">
<?php
$query = mysql_query("SELECT param_field_value,param_field_itemdata FROM cti_service_parameters where param_service_id=$service_id and param_field_name='IIT-JEE'");
$k=0;
echo "<select style='width: 100%;' id='PrepIIT' name ='PrepIIT'>";
echo "<option value=".$row1['lead_prep_iit']." selected>".$row1['lead_prep_iit']."</option>";
while($row = mysql_fetch_array($query))
{
$value[$k] = $row['param_field_value'];
$item[$k] = $row['param_field_itemdata'];
if($field_val == $item[$k])
echo "<option value='$value[$k]' selected>$value[$k]</option>";
else
echo "<option value='$value[$k]'>$value[$k]</option>";
$k = $k + 1;
}
echo "</select>";
?>
</td>
</tr>
<tr>
<td align="right"><b>Which Standard :</b></td>
<td align="left" >
<?php
$query = mysql_query("SELECT param_field_value,param_field_itemdata FROM cti_service_parameters where param_service_id=$service_id and param_field_name='standered'");
$k=0;
echo "<select style='width: 100%;' id='standared' name ='standared'>";
echo "<option value=".$row1['lead_standared']." selected>".$row1['lead_standared']."</option>";
while($row = mysql_fetch_array($query))
{
$value[$k] = $row['param_field_value'];
$item[$k] = $row['param_field_itemdata'];
if($field_val == $item[$k])
echo "<option value='$value[$k]' selected>$value[$k]</option>";
else
echo "<option value='$value[$k]'>$value[$k]</option>";
$k = $k + 1;
}
echo "</select>";
?>
</td>
<td align="right"><b>Promo DVD :</b></td>
<td align="left">
<?php
$query = mysql_query("SELECT param_field_value,param_field_itemdata FROM cti_service_parameters where param_service_id=$service_id and param_field_name='PromoDVD'");
$k=0;
echo "<select style='width: 100%;' id='dvd' name ='dvd'>";
echo "<option value=".$row1['lead_dvd']." selected>".$row1['lead_dvd']."</option>";
while($row = mysql_fetch_array($query))
{
$value[$k] = $row['param_field_value'];
$item[$k] = $row['param_field_itemdata'];
if($field_val == $item[$k])
echo "<option value='$value[$k]' selected>$value[$k]</option>";
else
echo "<option value='$value[$k]'>$value[$k]</option>";
$k = $k + 1;
}
echo "</select>";
?>
</td>
</tr>
<tr>
<td align="right"><b>Percentage in 10th :</b></td>
<td align="left" ><input name="tenth" id="tenth" maxlength="5" style="width: 100%;height: 25%;" class="textbox" type="text" value = "<?php echo "" . $row1['lead_tenth'] ."";?>"></td>
<td align="right"><b>Percentage in 12th :</b></td>
<td align="left" ><input name="twelth" id="twelth" maxlength="5" style="width: 100%;height: 25%;" class="textbox" type="text" value = "<?php echo "" . $row1['lead_twelth'] ."";?>"> </td>
<!--<td align="right"><b>Time of Call</b></td>
<td align="left" ><input name="calltime" id="calltime" style="width: 100%;height: 25%;" class="textbox" type="text" value = "<?php// echo "" . $row1['lead_import_batch_start_date'] ."";?>" readonly> </td> -->
</tr>
<tr>
<td align="right"><b>JEE appearing year :</b></td>
<td align="left" >
<?php
$query = mysql_query("SELECT param_field_value,param_field_itemdata FROM cti_service_parameters where param_service_id=$service_id and param_field_name='JeeYear'");
$k=0;
echo "<select style='width: 100%;' id='jeeyear' name ='jeeyear'>";
echo "<option value=".$row1['lead_jee_year']." selected>".$row1['lead_jee_year']."</option>";
while($row = mysql_fetch_array($query))
{
$value[$k] = $row['param_field_value'];
$item[$k] = $row['param_field_itemdata'];
if($field_val == $item[$k])
echo "<option value='$value[$k]' selected>$value[$k]</option>";
else
echo "<option value='$value[$k]'>$value[$k]</option>";
$k = $k + 1;
}
echo "</select>";
?>
</td>
<td align="right"><b>Joined any classes :</b></td>
<td align="left">
<?php
$query = mysql_query("SELECT param_field_value,param_field_itemdata FROM cti_service_parameters where param_service_id=$service_id and param_field_name='JoinedClasses'");
$k=0;
echo "<select style='width: 100%;' id='classes' name ='classes'>";
echo "<option value=".$row1['lead_classes']." selected>".$row1['lead_classes']."</option>";
while($row = mysql_fetch_array($query))
{
$value[$k] = $row['param_field_value'];
$item[$k] = $row['param_field_itemdata'];
if($field_val == $item[$k])
echo "<option value='$value[$k]' selected>$value[$k]</option>";
else
echo "<option value='$value[$k]'>$value[$k]</option>";
$k = $k + 1;
}
echo "</select>";
?>
</td>
</tr>
<tr>
<td align="right"><b>Remarks :</b></td>
<td colspan="3"><textarea type="text" name="remarks" id = "remarks" style ="width:100%;resize: none;" maxlength="900" ><?php echo "". $row1['lead_remarks'] ."";?></textarea> </td>
</tr>
<tr>
<td colspan=4 class="tableHeading">
<!--<b><font color="red">Note : Fields with * are Mandatory</font></b>-->
</td>
</tr>
<!--<input type="hidden" id="clinicFlag" name="clinicFlag" value="<?php// echo $_GET["clinicFlag"]?>">-->
<tr>
<tr>
<td colspan=4 style="padding:0px">
<div align="center">
<input title="Save [Alt+S]" accessKey="S" class="crmbutton small save" type="button" name="save" value=" Save " style="width:100px;height:30px" >
</td>
</div>
</tr>
</table>
</div>
and Code.php code is as follows
<?php
//session_start();
//echo $_SESSION['user'];
include("connection.php");
$lead = $_POST['lead'];
$callnumber = $_POST['callnumber'];
$service = $_POST['service'];
$lead_fname = $_POST['custname'];
$lead_phone1 = $_POST['phone'];
$lead_city = $_POST['city'];
$lead_email = $_POST['email'];
$lead_state = $_POST['state'];
$lead_address1 = $_POST['address'];
$lead_zip = $_POST['zip'];
$lead_rounds = $_POST['rounds'];
$lead_IIT = $_POST['PrepIIT'];
$lead_standared = $_POST['standared'];
$lead_dvd = $_POST['dvd'];
$lead_tenth = $_POST['tenth'];
$lead_twelth = $_POST['twelth'];
$lead_jee_year = $_POST['jeeyear'];
$lead_classes = $_POST['classes'];
$lead_remarks = $_POST['remarks'];
$lead_source = $_POST['source'];
if($GLOBALS['database_type'] == "MySql")
{
$con=mysql_connect($GLOBALS['database_ip'],$GLOBALS['database_username'],$GLOBALS['database_password']);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($GLOBALS['database_name'],$con);
$sql1 = mysql_query("SELECT service_outbound_lead_dsn_string,
service_outbound_lead_db_user,
service_outbound_lead_db_password,
service_leadstructure_master_tablename,
service_outbound_lead_db_name
FROM cti_services WHERE service_id = $service");
while($row = mysql_fetch_array($sql1))
{
$lead_dsn = $row['service_outbound_lead_dsn_string'];
$lead_user = $row['service_outbound_lead_db_user'];
$lead_pwd = $row['service_outbound_lead_db_password'];
$lead_table = $row['service_leadstructure_master_tablename'];
$lead_db = $row['service_outbound_lead_db_name'];
}
if($_POST['save'])
{
//input_app_datetime = '$lead_appointment',
//input_app_reschedule = '$lead_reschedule',
mysql_select_db($GLOBALS['database_name'],$con);
$sqlquery = ("UPDATE $lead_db.$lead_table set lead_fname = '$lead_fname', lead_phone1 = '$lead_phone1', lead_email = '$lead_email', lead_remarks = '$lead_remarks', lead_address1 = '$lead_address1', lead_state = '$lead_state', lead_city = '$lead_city', lead_zip = '$lead_zip', lead_rounds ='$lead_rounds', lead_prep_iit ='$lead_IIT', lead_standared ='$lead_standared', lead_dvd ='$lead_dvd', lead_tenth ='$lead_tenth', lead_twelth ='$lead_twelth', lead_jee_year ='$lead_jee_year', lead_classes ='$lead_classes', lead_source ='$lead_source' WHERE lead_id=$lead");
$dbSql = mysql_query($sqlquery) or die("Error : " . mysql_error());
$sql="update cti_call_master set crm_remarks='$lead_remarks' where call_number=$callnumber";
$dbSql1 = mysql_query($sql);
//$flag = "saved";
$message = "Lead Id-".$lead." Data Saved .....";
//$message = $sqlquery;
//header("location:vision.php?LEADID=$lead&SERVICEID=$service&CALLNUMBER=$callnumber&MESSAGE=$message&FLAG=$flag&CLI=$lead_phone1&clinicFlag=$clinicFlag&alterno=$alter_no");
header("location:displayPage.php?LEADID=$lead&SERVICEID=$service&CALLNUMBER=$callnumber&MESSAGE=$message&FLAG=$flag&CLI=$lead_phone1");
}
}
?>
You can call the following function at 'onload' event. It will submit the form after 5 second to your code.php
function fncAutoSubmitForm() {
setTimeout(function(){
document.getElementById('myform').submit();
}, 5000);
}
Then your code.php will process the form action and redirect it back to displayPage.php.
Can you check if your form is not submitted at all to code.php or it is being submitted to code.php and due to some error it fails to redirect back to displayPage.php. In the later case you can turn ON the display error settings if it is not already ON. Use following in code.php to enable:
error_reporting(E_ALL);
ini_set('display_errors',1);
It it doesn't help then pls provide the code to get the actual scenario here.
As you call fncAutoSubmitForm() onload of displayPage.php, it immediately triggers document.getElementById('myform').submit();
So you are redirected to code.php, the action of your form.
If you want a delay you should not apply fncAutoSubmitForm() onload of the page.
but more something like:
setTimeout("fncAutoSubmitForm();",5000);}
function fncAutoSubmitForm(){
document.getElementById('myform').submit();
}
But you won't stay on displayPage.php it will redirect you to code.php. If you want to always display the same page you needs to change the action target in your form.
Use jQuery :)
$(document).ready(function(){
setInterval(function(){
submit();
}, 1000);
});
function submit(){
var data;
// extract data from your form and save it to data variable
$.ajax({
type: "POST",
url: "some.php",
data: data
});
}

Categories