Error: Uncaught ReferenceError: onChangeAssignedGroup is not defined at HTMLSelectElement.onchange - javascript

I've been having issues trying to call a php script via javascript when the user changes a value in the "Assigned To Group" selection. Which is ultimately supposed to change the option list of, a not yet created, "Assign to User" selection.
I keep getting an error saying that it doesn't recognize the function's name. When I tried running a simple value change and alert to verify it could get the values, it recognized it and it updated accordingly. When I added the Ajax command is when it started not recognizing it. I'm sure I'm probably just using incorrectly, somehow, sense I've never used ajax before. But from the samples I've seen, it seems fairly straight forward.
Error: Uncaught ReferenceError: onChangeAssignedGroup is not defined at HTMLSelectElement.onchange
<?php
include('classes/class.User.php');
include('classes/class.Role.php');
include('classes/class.User_Role.php');
include('constants.php');
session_start();
?>
<html>
<head>
<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
function onChangeAssignedGroup() {
var new_assigned_to_role_id = document.getElementById("option_list_assigned_to_role_id").value;
document.getElementById("assignedGroupId").innerHTML = "You selected: " + new_assigned_to_role_id;
alert(new_assigned_to_role_id);
$.ajax({
method: "POST",
url: "ticket_details.php",
data:{
ticket_id:$_POST['ticket_id'];
creator_user_id:$_POST['creator_user_id'];
creator_user_name:$_POST['creator_user_name'];
status:$_POST['status'];
priority:$_POST['priority'];
title:$_POST['title'];
assigned_to_role_id:new_assigned_to_role_id;
assigned_to_role_name:"";
assigned_to_user_id:$_POST['assigned_to_user_id'];
assigned_to_user_name:$_POST['assigned_to_user_name'];
},
success: function () {
alert('form was submitted');
}
});
}
</script>
</head>
<body>
<p>Return to Tickets</p>
<?php
if(isset($_POST['submit']) or isset($_POST['submit_new_comment']) or isset($_POST['submit_update_ticket'])){
$ticket_id = $_POST['ticket_id'];
$creator_user_id = $_POST['creator_user_id'];
$creator_user_name = $_POST['creator_user_name'];
$status = $_POST['status'];
$priority = $_POST['priority'];
$title = $_POST['title'];
$assigned_to_role_id = $_POST['assigned_to_role_id'];
$assigned_to_role_name = $_POST['assigned_to_role_name'];
$assigned_to_user_id = $_POST['assigned_to_user_id'];
$assigned_to_user_name = $_POST['assigned_to_user_name'];
//connect to database
include("database_connection.php");
//handle update to ticket
if(isset($_POST['submit_update_ticket'])){
$update = $mysqli->query("UPDATE `ticket` SET `status` = '$status', `priority` = '$priority',
`assigned_to_role_id` = '$assigned_to_role_id', `assigned_to_role_name` = '$assigned_to_role_name',
`assigned_to_user_id` = '$assigned_to_user_id', `assigned_to_user_name` = '$assigned_to_user_name'
WHERE `ticket`.`id` = $ticket_id");
if(!$update){
echo"<p>".$mysqli->error."</p>";
}
}
//handle new comment
if(isset($_POST['submit_new_comment'])){
$new_comment = $_POST['new_comment'];
$current_id = $_SESSION['user']->getId();
$current_username = $_SESSION['user']->getUsername();
//sanitize data
$new_comment = $mysqli->real_escape_string($new_comment);
unset($_POST['submit_new_comment']);
//insert new comment into database.
$insert = $mysqli->query("INSERT INTO ticket_comment (ticket_id, user_id, user_name, text) VALUES ('$ticket_id', '$current_id', '$current_username', '$new_comment')");
if(!$insert){
echo"<p>".$mysqli->error."</p>";
}
}
//include arrays for converting values returned
include("value_maps.php");
echo "<p id='assignedGroupId'></p>";
echo "<p>role id:".$assigned_to_role_id."</p>";
echo "<p>role name:".$assigned_to_role_name."</p>";
if(in_array($assigned_to_role_id,$_SESSION['user']->getRoles())){
echo "<p>you have this role.</p>";
} else {
echo "<p>you don't have this role.</p>";
}
print_r($_SESSION['user']->getRoles());
echo"
<form action='' method='post'>
<input type='hidden' name='ticket_id' value='$ticket_id'>
<input type='hidden' name='creator_user_id' value='$creator_user_id'>
<input type='hidden' name='creator_user_name' value='$creator_user_name'>
<input type='hidden' name='title' value='$title'>
<input type='hidden' name='assigned_to_role_id' value='$assigned_to_role_id'>
<input type='hidden' name='assigned_to_role_name' value='$assigned_to_role_name'>
<input type='hidden' name='assigned_to_user_id' value='$assigned_to_user_id'>
<input type='hidden' name='assigned_to_user_name' value='$assigned_to_user_name'>
<table border='0' align='center' cellpadding='5'>
<tr>
<th>Ticket ID</th>
<th>Title</th>
<th>Status</th>
<th>Priority</th>
<th>Assigned To Group</th>
<th>Assigned To User</th>
</tr>
<tr>
<td>$ticket_id</td>
<td>$title</td>";
if(in_array($assigned_to_role_id,$_SESSION['user']->getRoles()) or in_array(ROLE_ID_ADMIN,$_SESSION['user']->getRoles())){
echo "<td><select name='status'>";
$status_index = 0;
foreach($status_array as $status_choice){
if($status == $status_index){
echo "<option value='". $status_index."' selected>". $status_choice ."</option>";
} else {
echo "<option value='". $status_index."'>". $status_choice ."</option>";
}
$status_index++;
}
echo "</select></th>";
echo "<td><select name='priority'>";
$priority_index = 0;
foreach($priority_array as $priority_choice){
if($priority == $priority_index){
echo "<option value='". $priority_index."' selected>". $priority_choice ."</option>";
} else {
echo "<option value='". $priority_index."'>". $priority_choice ."</option>";
}
$priority_index++;
}
echo "</select></th>";
} else {
echo "<td>".$status_array[$status]."</th>";
echo "<td>".$priority_array[$priority]."</th>";
}
if(in_array(ROLE_ID_ADMIN,$_SESSION['user']->getRoles())){
echo "<td><select id='option_list_assigned_to_role_id' name='assigned_to_role' onchange='onChangeAssignedGroup()'>";
foreach($_SESSION['roles'] as $assigned_to_role_choice){
if($assigned_to_role_id == $assigned_to_role_choice->getId()){
echo "<option value='". $assigned_to_role_choice->getId()."' selected>". $assigned_to_role_choice->getName() ."</option>";
} else {
echo "<option value='". $assigned_to_role_choice->getId()."'>". $assigned_to_role_choice->getName() ."</option>";
}
}
echo "</select></td>";
} else {
echo "<td>$assigned_to_role_name</td>";
echo "<td>$assigned_to_user_name</td>";
}
echo"
</tr>
<tr>
<td colspan='5'></td>
<td><input type='submit' name='submit_update_ticket' value='Update Ticket Details' required></td>
</tr>
</table>
</form>
";
//get back ticket details
$results = $mysqli->query("SELECT `id`,`ticket_id`,`user_id`,`user_name`,`text`,`create_date`,`modify_date` FROM `ticket_comment` WHERE `ticket_id` = ".$ticket_id." ORDER BY `create_date`");
//if insert was successful
if($results){
//header('location:registration_email_sent.php');
if ($results->num_rows > 0){
echo "
<table border='0' align='center' cellpadding='5'>
<tr>
<th>Username</th>
<th>Comment</th>
</tr>
";
while($row = $results->fetch_row()){
echo"
<tr>
<td>".$row[3].": </td>
<td>".$row[4]."</td>
</tr>";
}
} else {
echo "<p>No comments found. </p>";
}
}
$mysqli->close();
echo"
<form method='post' action=''>
<input type='hidden' name='ticket_id' value='$ticket_id'>
<input type='hidden' name='creator_user_id' value='$creator_user_id'>
<input type='hidden' name='creator_user_name' value='$creator_user_name'>
<input type='hidden' name='status' value='$status'>
<input type='hidden' name='priority' value='$priority'>
<input type='hidden' name='title' value='$title'>
<input type='hidden' name='assigned_to_role_id' value='$assigned_to_role_id'>
<input type='hidden' name='assigned_to_role_name' value='$assigned_to_role_name'>
<input type='hidden' name='assigned_to_user_id' value='$assigned_to_user_id'>
<input type='hidden' name='assigned_to_user_name' value='$assigned_to_user_name'>
<table border='0' align='center' cellpadding='5'>
<tr>
<th>New Comment</th>
<th><input type='submit' name='submit_new_comment' value='Post New Comment'></th>
</tr>
<tr>
<td colspan='2'><textarea name='new_comment' rows='10' cols='30' placeholder='New Comment Here' required></textarea></td>
</tr>
</table>
</form>
";
}
?>
</body>
</html>

In the data object in your ajax request, you need to replace the semicolons with commas.
You should also always use prepared statements to interact with the database.

Related

Pagination does not work on page2 in php web page

Can someone help me on pagination syntax for php webpage. I have a set a pagination code to display 20 records per page. The records are displaying based on 'start date' and 'end date'.
The issue is, it works on page 1 but when I click on page 2 in pagination then it won't work. I assume the values of $_POST['startdate'] and $_POST['enddate] are not forwarding on page2.
<html>
<head>
<title></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="multitab/bootstrap.min.css">
<link rel="stylesheet" href="css/font-awesome.min.css">
<style>
.inline{
display: inline-block;
float: right;
margin: 20px 0px;
}
input, button{
height: 34px;
}
</style>
</head>
<body>
<form id="form1" name="form1" action="" method="post">
<table>
<tr>
<td><b>Start date:</b></td>
<td><input type="date" id="startdate" name="startdate" size="10"> </td>
<td><b>End date:</b></td>
<td><input type="date" id="enddate" name="enddate" size="10" max=<?php echo date('Y-m-d');?>></td>
<td><input type="submit" value="Search" name="Search" onClick="return check()"></td>
</tr>
</table>
</form>
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("abc_db",$con);
$limit = 20;
if (isset($_GET["page"])) {
$pn = $_GET["page"];
}
else {
$pn=1;
};
if(isset($_POST['Search'])){
$startdate1 = $_POST['startdate'];
echo "Start date : ".$startdate1", ";
$enddate1 = $_POST['enddate'];
echo "End date : ".$enddate1;
}
$start_from = ($pn-1) * $limit;
$serial = (($pn-1) * $limit) + 1;
$today1= date("Y/m/d");
$days14_ago = date('Y/m/d', mktime(0, 0, 0, date("m") , date("d") - 14, date("Y")));
if ($startdate1 !=Null) {
$sql = "SELECT * FROM hd where datearrival='$startdate1' LIMIT $start_from, $limit";
} else if ($enddate1 !=Null) {
$sql = "SELECT * FROM hd where datearrival='$enddate1' LIMIT $start_from, $limit";
} else {
$sql = "SELECT * FROM hd where datearrival between '$days14_ago' and '$today1' LIMIT $start_from, $limit";
}
if (($startdate !=Null) && ($enddate !=Null)) {
$sql = "SELECT * FROM hd where datearrival between '$startdate1' and '$enddate1' LIMIT $start_from, $limit";
}
$rs_result = mysql_query ($sql);
?>
<div class="container">
<button style="height:25px;width:70px;" onclick="window.location.reload(true);">Refresh</button>
<br>
<div>
<font face='cambria'><p><span style="display:inline-block; margin-left: 650px; ">
</span></p> </font>
<font face="Cambria" size="2"> <table class="table table-striped table-condensed table-bordered">
<thead>
<tr>
<th width="5%" valign="top">Sr#</th>
<th width="10%" valign="top">Date arrival</th>
<th width="10%" valign="top">Pno</th>
<th width="10%" valign="top">First name</th>
<th valign="top"></th>
<th valign="top"></th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysql_fetch_array($rs_result, MYSQL_ASSOC)) {
$pno1=$row['pno'];
$datearrival1=$row['datearrival'];
$sr_num = $serial++;
?>
<tr>
<td><?php echo $sr_num; ?></td>
<td><?php echo date("d/m/Y", strtotime($row['datearrival'])); ?></td>
<td><?php echo $row["pno"]; ?></td>
<td><?php echo $row["first_name"]; ?></td>
<td><p align="center">edit</font></td>
<td><p align="center">delete</font></td>
</tr>
<?php
};
?>
</tbody>
</table>
</font>
<div>
<ul class="pagination">
<?php
$sql = "SELECT COUNT(*) FROM hd where datearrival between '$startdate1' and '$enddate1'";
$rs_result = mysql_query($sql);
$row = mysql_fetch_row($rs_result);
$total_records = $row[0];
$total_pages = ceil($total_records / $limit);
$k = (($pn+4>$total_pages)?$total_pages-4:(($pn-4<1)?5:$pn));
$pagLink = "";
if($pn>=2){
echo "<li><a href='qm.php?page=1'> << </a></li>";
echo "<li><a href='qm.php?page=".($pn-1)."'> < </a></li>";
}
for ($i=-4; $i<=4; $i++) {
if($k+$i==$pn)
$pagLink .= "<li class='active'><a href='qm.php?page=".($k+$i)."'>".($k+$i)."</a></li>";
else
$pagLink .= "<li><a href='qm.php?page=".($k+$i)."'>".($k+$i)."</a></li>";
};
echo $pagLink;
if($pn<$total_pages){
echo "<li><a href='qm.php?page=".($pn+1)."'> > </a></li>";
echo "<li><a href='qm.php?page=".$total_pages."'> >> </a></li>";
}
?>
</ul>
<div class="inline">
<input id="pn" type="number" min="1" max="<?php echo $total_pages?>"
placeholder="<?php echo $pn."/".$total_pages; ?>" required>
<button onclick="go2Page();">Go</button>
</div>
</div>
</div>
</div>
<script>
function go2Page()
{
var pn = document.getElementById("pn").value;
pn = ((pn><?php echo $total_pages; ?>)?<?php echo $total_pages; ?>:((pn<1)?1:pn));
window.location.href = 'qm.php?page='+pn;
}
/* start and end date- validation checks */
function check(){
var startdatea=document.getElementById("startdate").value;
var enddatea=document.getElementById("enddate").value;
if(Date.parse(startdatea)>Date.parse(enddatea)){
alert("Please select a different End Date.");
return false;
}
}
</script>
</body>
</html>
$_POST superglobal variable is populated by PHP when a POST HTTP request is processed. This is the case on the request for page 1.
However, your go2page() function is mutating location.href, which generates a GET HTTP request, and so does pagination links.
You should append your startdate and enddate params to the pagination URLs, to forward your params to the next/previous requests :
qm.php?page=<YOUR-PAGE-NUMBER>&startdate=<YOUR-START-DATE>&enddate=<YOUR-END-DATE>';
And use $_GET['startdate'] and $_GET['enddate] to retrieve those when processing GET requests.
More about $_POST https://www.php.net/manual/en/reserved.variables.post.php
More about GET AND POST HTTP requests : https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
There's an error in your isset($_POST['Search'])
your code:
if(isset($_POST['Search'])){
$startdate1 = $_POST['startdate'];
echo "Start date : ".$startdate1", ";
$enddate1 = $_POST['enddate'];
echo "End date : ".$enddate1;
}
possible working solution:
if(isset($_POST['Search'])){
$startdate1 = $_POST['startdate'];
echo "Start date : ".$startdate1.", ";
$enddate1 = $_POST['enddate'];
echo "End date : ".$enddate1;
}
Though I didn't try it yet, but I assume this is the cause, pagination in page2 will not work since the code is not executed after the error which is the pagination for page2.
EDIT: The . fixes things.
echo "Start date : ".$startdate1", ";
is different than
echo "Start date : ".$startdate1.", ";
Add values of your $_POST inside links and use them as $_GET so you would use both.
$startdate1=$enddate1=null; //to hide notice
if(isset($_POST['Search'])){
$startdate1 = $_POST['startdate'];
echo "Start date : ".$startdate1.", ";
$enddate1 = $_POST['enddate'];
echo "End date : ".$enddate1;
} else if (!empty($_GET['startdate']) && !empty($_GET['enddate'])){
$startdate1 = $_GET['startdate'];
echo "Start date : ".$startdate1.", ";
$enddate1 = $_GET['enddate'];
echo "End date : ".$enddate1;
}
$pagLink .= "<li><a href='qm.php?page=".($k+$i)."&startdate=".startdate1."&enddate=".$enddate1."'>".($k+$i)."</a></li>";
For your need:
$pagLink = "";
if($pn>=2){
echo "<li><a href='qm.php?page=1&startdate=".startdate1."&enddate=".$enddate1."'> << </a></li>";
echo "<li><a href='qm.php?page=".($pn-1)."&startdate=".startdate1."&enddate=".$enddate1."'> < </a></li>";
}
for ($i=-4; $i<=4; $i++) {
if($k+$i==$pn)
$pagLink .= "<li class='active'><a href='qm.php?page=".($k+$i)."&startdate=".startdate1."&enddate=".$enddate1."'>".($k+$i)."</a></li>";
else
$pagLink .= "<li><a href='qm.php?page=".($k+$i)."&startdate=".startdate1."&enddate=".$enddate1."'>".($k+$i)."</a></li>";
};
echo $pagLink;
if($pn<$total_pages){
echo "<li><a href='qm.php?page=".($pn+1)."&startdate=".startdate1."&enddate=".$enddate1."'> > </a></li>";
echo "<li><a href='qm.php?page=".$total_pages."&startdate=".startdate1."&enddate=".$enddate1."'> >> </a></li>";
}
That would help you to move dates to next page.
You need to set it to all paging links. Also you can make extra if statement to not pass empty GET
EDIT:
As I already told: You need to set it to all paging links. Also you can make extra if statement to not pass empty GET (that includes javascript)
function go2Page()
{
var pn = document.getElementById("pn").value;
pn = ((pn><?php echo $total_pages; ?>)?<?php echo $total_pages; ?>:((pn<1)?1:pn));
window.location.href = 'teztz.php?page='+pn+'&startdate=<?=startdate1;?>&enddate=<?=$enddate1;?>';
}

Edit/Update data in php through AJAX

In my index.php I am fetching data from the database. I put an edit button on that and I have used a datatable to view data information in this form. I have four field: Name, Age, Email, Update through mysqli_fetch_array I have fetched the data.
This is the index.php file:
<?php
//including the database connection file
include_once("config.php");
//fetching data in descending order (lastest entry first)
//$result = mysql_query("SELECT * FROM users ORDER BY id DESC"); // mysql_query is deprecated
// using mysqli_query instead
?>
<html>
<head>
<title>Homepage</title>
<link rel="stylesheet" href="DataTables/datatables.css" type="text/css">
<link rel="stylesheet" href="DataTables/DataTables/css/dataTables.bootstrap.css" type="text/css">
<link rel="stylesheet" href="DataTables/DataTables/css/jquery.dataTables.css" type="text/css">
<script src="DataTables/datatables.js"></script>
<script src="style/jquery-3.2.1.js"></script>
<script src="style/datatable.js"></script>
<script src="DataTables/DataTables/js/dataTables.bootstrap.js"></script>
<script src="DataTables/DataTables/js/jquery.dataTables.js"></script>
</head>
<body>
Add New Data<br/><br/>
<table id="datatable" class="display" width='100%' border=0>
<thead>
<tr bgcolor='#CCCCCC'>
<td>Name</td>
<td>Age</td>
<td>Email</td>
<td>Update</td>
</tr>
</thead>
<?php
//while($res = mysql_fetch_array($result)) { // mysql_fetch_array is deprecated, we need to use mysqli_fetch_array
//$action=$_POST["action"];
//if($action=='showroom')
{
$result = mysqli_query($mysqli, "SELECT * FROM users ORDER BY id DESC");
while ($res = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $res['name'] . "</td>";
echo "<td>" . $res['age'] . "</td>";
echo "<td>" . $res['email'] . "</td>";
echo "<td>Edit | Delete</td>";
}
}
?>
</table>
</body>
</html>
This is my edit.php file. First I check empty fields, after that I run updating the table query redirecting to the display page. In our case, it is index.php then getting id from url, selecting data associated with this particular id, fetching data through mysqli_fetch_array .
<?php
// including the database connection file
include_once("config.php");
$id = $_POST['id'];
$name = $_POST['name'];
$age = $_POST['age'];
$email = $_POST['email'];
// checking empty fields
if (empty($name) || empty($age) || empty($email)) {
if (empty($name)) {
echo "<font color='red'>Name field is empty.</font><br/>";
}
if (empty($age)) {
echo "<font color='red'>Age field is empty.</font><br/>";
}
if (empty($email)) {
echo "<font color='red'>Email field is empty.</font><br/>";
}
} else {
//updating the table
$result = mysqli_query($mysqli, "UPDATE users SET name='$name',age='$age',email='$email' WHERE id=$id");
//redirectig to the display page. In our case, it is index.php
header("Location: index.php");
}
//getting id from url
$id = $_GET['id'];
//selecting data associated with this particular id
$result = mysqli_query($mysqli, "SELECT * FROM users WHERE id=$id");
while ($res = mysqli_fetch_array($result)) {
$name = $res['name'];
$age = $res['age'];
$email = $res['email'];
}
?>
<html>
<head>
<title>Edit Data</title>
<script src="style/jquery-3.2.1.js"></script>
<script src="style/insert.js"></script>
<script src="style/view.js"></script>
<script src="style/edit.js"></script>
</head>
<body>
Home
<br/><br/>
<p id="message"></p>
<form name="form1" method="POST" action="edit.php">
<table border="0">
<tr>
<td>Name</td>
<td><input type="text" name="name" value="<?php echo $name; ?>"></td>
</tr>
<tr>
<td>Age</td>
<td><input type="text" name="age" value="<?php echo $age; ?>"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" value="<?php echo $email; ?>"></td>
</tr>
<tr>
<td><input type="hidden" name="id" value=<?php echo $_GET['id']; ?>></td>
<td><input type="submit" name="update" id="update" value="Update"></td>
</tr>
</table>
</form>
</body>
</html>
Finally, this is my edit.js file. In this file I try to do edit the form through AJAX, but I can't find where I doing mistakes.
<script>
$(document).ready(function (e) {
$('#update').click(function (event)
{
event.preventDefault();
$.ajax({
data: $('form').serialize(),
url: "edit.php", //php page URL where we post this data to save in database
type: 'POST',
success: function (strMessage) {
$('#message').text("strMessage");
}
})
});
});
</script>
You are doing edit and update on same file so you have to add condition on file. change your code as below:
edit.php
<?php
// including the database connection file
include_once("config.php");
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$id = $_POST['id'];
$name = $_POST['name'];
$age = $_POST['age'];
$email = $_POST['email'];
// checking empty fields
if(empty($name) || empty($age) || empty($email)) {
if(empty($name)) {
echo "<font color='red'>Name field is empty.</font><br/>";
}
if(empty($age)) {
echo "<font color='red'>Age field is empty.</font><br/>";
}
if(empty($email)) {
echo "<font color='red'>Email field is empty.</font><br/>";
}
} else {
//updating the table
$result = mysqli_query($mysqli, "UPDATE users SET name='$name',age='$age',email='$email' WHERE id=$id");
//redirectig to the display page. In our case, it is index.php
header("Location: index.php");
}
}
//getting id from url
$id = $_GET['id'];
//selecting data associated with this particular id
$result = mysqli_query($mysqli, "SELECT * FROM users WHERE id=$id");
while($res = mysqli_fetch_array($result))
{
$name = $res['name'];
$age = $res['age'];
$email = $res['email'];
}
?>
<html>
<head>
<title>Edit Data</title>
<script src="style/jquery-3.2.1.js"></script>
<script src="style/insert.js"></script>
<script src="style/view.js"></script>
<script src="style/edit.js"></script>
</head>
<body>
Home
<br/><br/>
<p id="message"></p>
<form name="form1" method="POST" action="edit.php">
<table border="0">
<tr>
<td>Name</td>
<td><input type="text" name="name" value="<?php echo $name;?>"></td>
</tr>
<tr>
<td>Age</td>
<td><input type="text" name="age" value="<?php echo $age;?>"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" value="<?php echo $email;?>"></td>
</tr>
<tr>
<td><input type="hidden" name="id" value=<?php echo $_GET['id'];?>></td>
<td><input type="submit" name="update" id="update" value="Update"></td>
</tr>
</table>
</form>
</body>
</html>

php html javascript wrong result

This is my code
<html>
<head>
<title>
Aplikasi KRS
</title>
</head>
<body>
<p>IPK : 1.xx</p>
<form name="formTes" method="post">
<script>
function cekKrs()
{
var jum_sks = 0;
for(var i=0; i<7; i++)
{
if(document.formTes.elements[i].checked)
jum_sks += mataKuliah;
}
document.formTes.fieldJumlah.value = jum_sks;
if(jum_sks > 15)
{
alert("Anda harus mengurangi SKS\n karena melebihi 15 SKS");
}
}
function cekKirim()
{
if(document.formTes.fieldJumlah.value > 15)
alert("Anda harus mengurangi SKS\n karena melebihi 15 SKS");
else
window.location.href = "tesform.html";
}
</script>
<table border="2">
<tr><th>Kode</th><th>Mata Kuliah</th><th>SKS</th><th><Pilihan/th></tr>
<?php
include "koneksi.php";
$sql = "SELECT * FROM mata_kul";
$query = $con->query($sql);
while($mataKuliah = $query->fetch_array())
{
echo "<tr><td>". $mataKuliah['kodeMK'] ."</td>";
echo "<td>". $mataKuliah['namaMK'] ."</td>";
echo "<td>". $mataKuliah['sks'] ."</td>";
echo "<script>var mataKuliah= ".$mataKuliah['sks']."</script>";
echo "<td><input name='mk". $mataKuliah['kodeMK'] ."' type='checkbox' onclick='cekKrs()'></td>";
}
?>
<tr><td colspan="2" align="right">Jumlah SKS</td>
<td colspan="2"><input size="3" value="0" name="fieldJumlah" type="text" readonly="readonly"></td></tr></table>
<br>
<input type="button" name="tombolKirim" value="Kirim" onclick="cekKirim()">
</form>
</body>
</html>
My question is
"Why when i click checklist it show the last value of sks in jumlah SKS, not the sks checked value i click ? like when i click checklist which have value of 2 in sks it should show 2 not 8 in jumlah SKS"
Here's the image
Can you tell me where did i go wrong ? I'm still new
I guess you need send the checkbox obj as param to cekKrs() , and in function cekKrs evaluates if obj is checked to + or - the obj.value from total
Try this DEMO
HTML ( draft )
<table>
<!-- while($mataKuliah = $query->fetch_array())
{ -->
<tr>
<!-- echo "<td><input name='mk". $mataKuliah['kodeMK'] ."' type='checkbox' onclick='cekKrs(this)' value='".$mataKuliah['sks']."'></td>"; // PHP -->
<td><input type='checkbox' onclick='cekKrs(this)' value='1'>1</td>
</tr>
<tr>
<td><input type='checkbox' onclick='cekKrs(this)' value='2'>2</td>
</tr>
<tr>
<td><input type='checkbox' onclick='cekKrs(this)' value='3'>3</td>
</tr>
<!-- } -->
</table>
<input size="3" value="0" name="fieldJumlah" id='fieldJumlah' type="text" readonly="readonly">
onclick='cekKrs(this)' sends checkbox obj , and you keep the mataKuliah's value inside the checkbox value
JS
function cekKrs(chkObj)
{
//Get current total
var jum_sks = parseInt(document.getElementById('fieldJumlah').value);
//Get checkbox value clicked
var mataKuliah = parseInt(chkObj.value);
//Evaluate check to + or -
if(!chkObj.checked)
{
mataKuliah = (mataKuliah * -1)
}
jum_sks += mataKuliah;
//Set new total
document.getElementById('fieldJumlah').value = jum_sks;
}

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
});
}

I'm trying to pull data from database into selectboxes

I'm trying to pull data from database into selectboxes, but when the data is pulled it goes into one 'td' and not into separate td's. I'm trying to achieve result as shown below
but I keep getting this result
here is my code
<?php
$data_array = array();
$result2 = mysql_query("SELECT * FROM `firefightersonscene`
JOIN `firefighterinfo` ON `firefightersonscene`.`FireFighterInfo_fighterID` = `firefighterinfo`.`fighterID`
JOIN `stationlocation` ON `firefighterinfo`.`StationLocation_locationID`=`stationlocation`.`locationID`
WHERE `IncidenceOfFire_incidentID`='$getIncID' ORDER BY `firstName`");
if(mysql_num_rows($result2) > 0)
{
while($rows2 = mysql_fetch_object($result2))
{
$data_array[] = $rows2;
}
}
?>
<form action="core_viewfireoccurrence.php?incidentID=<?php echo $rows->incidentID; ?>" method="post" class="view_occurrence_form">
<table id="myTable">
<thead>
<tr>
</tr>
</thead>
<tbody>
<tr>
<td class="count">1</td>
<td>
<?php
foreach($data_array as $rows2):
$fighterID = $rows2->FireFighterInfo_fighterID;
$results = mysql_query("SELECT `fighterID`, `firstName`, `middleName`, `lastName`, `stationlocation`.`exactlocation`
FROM `firefighterinfo`
JOIN `stationlocation` ON `firefighterinfo`.`StationLocation_locationID`=`stationlocation`.`locationID` ORDER BY `firstName`");
echo '<select name="fireman[]" required><option value=""></option>';
while($row = mysql_fetch_array($results))
{
if($row['fighterID'] == $fighterID)
echo '<option selected>'. $row['firstName']." ".$row['middleName']." ".$row['lastName'].", ".$row['exactlocation'].'</option>';
else
echo '<option>'. $row['firstName']." ".$row['middleName']." ".$row['lastName'].", ".$row['exactlocation'].'</option>';
}// end while
echo '</select><br>';
endforeach;
?>
</td>
<td>
<input type="button" value="X" class="removeVar"/>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
<input type="button" id="addVar" value="Add Item"/>
</tr>
</tfoot>
</table>
</form>
JS CODE
<script type="text/javascript">
$('form').on('click', '.removeVar', function(){
$(this).closest('tr').remove();
$('.count').each(function(i){
$(this).text(i + 1);
});
});
//add a new node
$('#addVar').on('click', function(){
var varCount = $('#myTable tr').length - 1;
$node = ['<tr>',
'<td class="count">'+varCount+'</td>',
'<td><select name="fireman[]" class="ctlGroup" required>',
'<option value=""></option>',
'<?php require("php/fireman_list.php"); ?>',
'</select></td>',
'<td><input type="button" value="X" class="removeVar"/>',
'</td></tr>'].join('\n');
$('#myTable > tbody:last').append($node);
});
</script>
You need to put your whole table row in the loop. You will also need to add a variable to count the row number for you.
<?php
$row =1;
foreach($data_array as $rows2):
?>
<tr>
<td class="count"><?php echo $row; ?></td>
<td>
<?php
$fighterID = $rows2->FireFighterInfo_fighterID;
$results = mysql_query("SELECT `fighterID`, `firstName`, `middleName`, `lastName`, `stationlocation`.`exactlocation`
FROM `firefighterinfo`
JOIN `stationlocation` ON `firefighterinfo`.`StationLocation_locationID`=`stationlocation`.`locationID` ORDER BY `firstName`");
echo '<select name="fireman[]" required><option value=""></option>';
while($row = mysql_fetch_array($results))
{
if($row['fighterID'] == $fighterID)
echo '<option selected>'. $row['firstName']." ".$row['middleName']." ".$row['lastName'].", ".$row['exactlocation'].'</option>';
else
echo '<option>'. $row['firstName']." ".$row['middleName']." ".$row['lastName'].", ".$row['exactlocation'].'</option>';
}// end while
echo '</select><br>';
?>
</td>
<td>
<input type="button" value="X" class="removeVar"/>
</td>
</tr>
<?php
$row++;
endforeach;
?>

Categories