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
});
}
Related
I am using AJAX to call a PHP file that pulls a summary of calls from a MySQL database. The AJAX routine then inserts the returned table with an HTML form for each row in the table into the original webpage. Each row has a submit button to open the actual record and display all info so it can be edited. When I code this just in HTML without the AJAX update it works perfectly but I need to refresh the webpage to update the data. I want the data refreshed every 5 seconds automatically without needing to refresh the entire page. When I move the code to the AJAX routine the table pulls in perfectly with the data and the submit buttons for each row but the submit buttons don't do anything.
Code calling AJAX routine in main HTML page
const interval = setInterval(function() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
document.getElementById("unitstatus").innerHTML = this.responseText;
}
xhttp.open("GET", "updatestatus.php");
xhttp.send();
}, 5000);
Code Displaying Response in main HTML page
<div id='unitstatus' name='unitstatus'></div>
PHP File called by AJAX
<?php
session_start();
$event = $_SESSION['event'];
set_include_path('./includes/');
include 'conn.inc';
$conn = new mysqli($servername, $username, $password, $dbname);
$sql="SELECT * from sags WHERE Complete='N' AND event='$event' ORDER BY bib";
?>
<!DOCTYPE html >
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
</head>
<body>
<table width='100%' border='1'>
<tr>
<td width='100%' height='45px' colspan='8' class='w3-center'>
<button class='w3-button w3-blue w3-text-white w3-medium w3-padding-8' name='addnew' id='addnew' onclick='gotonewcall()'>ADD NEW REQUEST</button>
</td>
</tr>
<tr>
<td width='6%' class='w3-padding-small w3-small'><b>ID</b></td>
<td width='14%' class='w3-padding-small w3-small'><b>NAME</b></td>
<td width='6%' class='w3-padding-small w3-small'><b>BIB</b></td>
<td width='12%' class='w3-padding-small w3-small'><b>CELL PHONE</b></td>
<td width='24%' class='w3-padding-small w3-small'><b>CALL</b></td>
<td width='18%' class='w3-padding-small w3-small'><b>LAST UPDATE</b></td>
<td width='15%' class='w3-padding-small w3-small'><b>STATUS</b></td>
<td width='5%'></td>
</tr>
<?php
if(mysqli_query ($conn, $sql)){
$result = mysqli_query ($conn, $sql);
while($row=mysqli_fetch_array($result)){
if ($row['status']=="ONLOCATION"){
$status = "ON LOCATION";
} else {
$status = $row['status'];
}
?>
<form action="editrequest.php" method="post">"
<tr>
<td width='6%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['id'] ?><input type='text' name='id' id='id' style='width:100%' class='w3-light-gray' value=<?php echo $row['id'] ?> hidden></b></td>
<td width='14%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['fName'] ?></b></td>
<td width='6%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['bib'] ?></b></td>
<td width='12%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['cellphone'] ?></b></td>
<td width='24%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['sagrequest'] ?></b></td>
<td width='18%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['statstime'] ?></b></td>
<?php
if ($status == "ON LOCATION"){
echo "<td width='15%' class='w3-padding-small w3-small w3-text-white w3-red'>";
echo "<b>" . $status . "</b>";
echo "</td>";
} elseif ($status == "ENROUTE"){
echo "<td width='15%' class='w3-padding-small w3-small w3-text-black w3-yellow'>";
echo "<b>" . $status . "</b>";
echo "</td>";
} elseif ($status == "NEW"){
echo "<td width='15%' class='w3-padding-small w3-small w3-text-black w3-white'>";
echo "<b>" . $status . "</b>";
echo "</td>";
} elseif ($status == "RECEIVED"){
echo "<td width='15%' class='w3-padding-small w3-small w3-text-black w3-gray'>";
echo "<b>" . $status . "</b>";
echo "</td>";
} elseif ($status == "TRANSPORTING"){
echo "<td width='15%' class='w3-padding-small w3-small w3-text-white w3-purple'>";
echo "<b>" . $status . "</b>";
echo "</td>";
}
?>
<td width='5%' class='W3-center w3-tiny'>
<input type="submit" value="OPEN" name="editentry" id="editentry" class="w3-button w3-blue w3-center" style="width:100%; height:100%">
</td>
</tr>
</form>
<?php
}
} else {
echo "<tr><td colspan='8' class='w3-center'><h3><b>NO ACTIVE CALLS</b></h3></td></tr>";
}
?>
</table>
<?php
mysqli_close();
?>
I will do something like this, working example here.
PHP file
<?php
session_start();
$event = $_SESSION['event'];
set_include_path('./includes/');
include 'conn.inc';
$conn = new mysqli($servername, $username, $password, $dbname);
$sql="SELECT * from sags WHERE Complete='N' AND event='$event' ORDER BY bib";
if(mysqli_query ($conn, $sql)){
$result = mysqli_query ($conn, $sql);
while($row=mysqli_fetch_array($result)){
if ($row['status']=="ONLOCATION"){
$status = "ON LOCATION";
} else {
$status = $row['status'];
}
?>
<tr>
<td width='6%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['id'] ?>
</b></td>
<td width='14%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['fName'] ?></b></td>
<td width='6%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['bib'] ?></b></td>
<td width='12%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['cellphone'] ?></b></td>
<td width='24%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['sagrequest'] ?></b></td>
<td width='18%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['statstime'] ?></b></td>
<?php
if ($status == "ON LOCATION"){
echo "<td width='15%' class='w3-padding-small w3-small w3-text-white w3-red'>";
echo "<b>" . $status . "</b>";
echo "</td>";
} elseif ($status == "ENROUTE"){
echo "<td width='15%' class='w3-padding-small w3-small w3-text-black w3-yellow'>";
echo "<b>" . $status . "</b>";
echo "</td>";
} elseif ($status == "NEW"){
echo "<td width='15%' class='w3-padding-small w3-small w3-text-black w3-white'>";
echo "<b>" . $status . "</b>";
echo "</td>";
} elseif ($status == "RECEIVED"){
echo "<td width='15%' class='w3-padding-small w3-small w3-text-black w3-gray'>";
echo "<b>" . $status . "</b>";
echo "</td>";
} elseif ($status == "TRANSPORTING"){
echo "<td width='15%' class='w3-padding-small w3-small w3-text-white w3-purple'>";
echo "<b>" . $status . "</b>";
echo "</td>";
}
?>
<td width='5%' class='W3-center w3-tiny'>
<form action="editrequest.php" method="post">
<input type='text' name='id' id='id' style='width:100%' class='w3-light-gray' value=<?php echo $row['id'] ?> hidden>
<input type="submit" value="OPEN" name="editentry" id="editentry" class="w3-button w3-blue w3-center" style="width:100%; height:100%">
</form>
</td>
</tr>
<?php
}
} else {
echo "<tr><td colspan='8' class='w3-center'><h3><b>NO ACTIVE CALLS</b></h3></td></tr>";
}
?>
JavaScript
const interval = setInterval(function() {
$("#tableForm").load("updatestatus.php");//Load since just updating data
//You can use $.get() as well
//Or use $.post() if you have some data to send to php file.
//and append response with .html()
}, 5000);
HTML
<!DOCTYPE html >
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
</head>
<body>
<table width='100%' border='1'>
<tr>
<td width='100%' height='45px' colspan='8' class='w3-center'>
<button class='w3-button w3-blue w3-text-white w3-medium w3-padding-8' name='addnew' id='addnew' onclick='gotonewcall()'>ADD NEW REQUEST</button>
</td>
</tr>
<tr>
<td width='6%' class='w3-padding-small w3-small'><b>ID</b></td>
<td width='14%' class='w3-padding-small w3-small'><b>NAME</b></td>
<td width='6%' class='w3-padding-small w3-small'><b>BIB</b></td>
<td width='12%' class='w3-padding-small w3-small'><b>CELL PHONE</b></td>
<td width='24%' class='w3-padding-small w3-small'><b>CALL</b></td>
<td width='18%' class='w3-padding-small w3-small'><b>LAST UPDATE</b></td>
<td width='15%' class='w3-padding-small w3-small'><b>STATUS</b></td>
<td width='5%'></td>
</tr>
<div id="tableForm"><!-- I will load form here from php --></div>
</table>
Edit:-
Explanation
In the inspect element I saw <form .....> ... but no </form>, I tried lot things to make it a clear defined form but failed. There is some part of your code which is breaking the input element so I declared it separately since the form has only 1 input.
Suggestion
Echo out only the needed code from ajax requested file.
Avoid using <b> why? idk but better use font-weight:bold
Use $.ajax() $.post() $.get() more easy way to AJAX requests.
Because you are adding new elements to the DOM, you'll need register event handlers for each new added button.
However there is another method you can use is to register event listener on the table itself only once and capture events originated from buttons:
const templ = document.getElementById("templ").content;
const result = document.getElementById("result");
//event listener on parent
document.getElementById("table2").addEventListener("click", buttonClicked2);
function add(parent, addEvent)
{
parent = document.getElementById(parent);
const row = templ.cloneNode(true);
row.querySelector("td").textContent = "row " + (parent.children.length+1);
//event listener on button
if (addEvent)
row.querySelector("button").addEventListener("click", buttonClicked);
parent.tBodies[0].appendChild(row);
}
function buttonClicked(e) {
result.textContent = "table=" + e.target.parentNode.offsetParent.id + " row=" + e.target.parentNode.parentNode.rowIndex;
}
function buttonClicked2(e) {
result.textContent = e.target.tagName; //this will show which element clicked unless button was clicked
if (e.target.tagName != "BUTTON")
return;
result.textContent = "table=" + e.target.parentNode.offsetParent.id + " row=" + e.target.parentNode.parentNode.rowIndex;
}
.flex {
grid-gap: 1em;
display: flex;
}
Clicked button at <span id="result"></span>
<div class="flex">
<div>Events from button
<button onclick="add('table1', true)">Insert</button>
<table id="table1">
<thead><tr><th>col1</th><th>col2</th></tr></thead>
<tbody></tbody>
</table>
</div>
<div>Events from table
<button onclick="add('table2', false)">Insert</button>
<table id="table2">
<thead><tr><th>col1</th><th>col2</th></tr></thead>
<tbody></tbody>
</table>
</div>
<template id="templ"><tr><td></td><td><button>click me</button></td></tr></template>
</div>
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>
I want a Select Box where I can Filter the Data from the Database (with Ajax - no site reload). For example: Order the data by ID or Order the data by name
Thats working fine and now when I get that data I want also that I can edit the data with Inputs and save it (also trough ajax) but I dont know how. I know how to save data with ajax but not when the data is a response from another ajax.
Code: (Its not well formatted here, that's why pastebin: http://pastebin.com/7mgi6VMc)
Index:
<div class="wrapper">
<p id="result">Erfolgreich gespeichert!</p>
<br>
<div class="filter">
<form>
Anzeige:
<select class="selectFilter" onchange="filterFunction(this.value)">
<option value="id_back">ID - Aufwärts</option>
<option value="id_up">ID - Abwärts</option>
</select>
</form>
</div>
<br>
<br>
<div id="resultCatalogue">
<b>Bitte wähle die gewünschte Anzeige ...</b>
</div>
</div>
getData.php:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css? family=Open+Sans" />
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
$("#save").on("submit", function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "./save.php",
data: $(this).serialize(),
success: function(data) {
if($('#result').css('display') == 'none') {
document.getElementById('result').style.display = 'block'
} else {
document.getElementById('result').style.display = 'none'
setTimeout(function() {
document.getElementById('result').style.display = 'block'
}, 100);
}
},
});
});
</script>
</head>
<body>
<?php
$type = intval($_GET['type']);
if($type == "id_up")
{
echo '
<table class="tableCatalogue">
<tr>
<th class="th" width="5%">ID</th>
<th class="th" width="5%">Unter-ID</th>
<th class="th" width="15%">Titel</th>
<th class="th" width="5%">Iceron</th>
<th class="th" width="10%">Sichtbar</th>
<th class="th" width="10%">Aktiv</th>
<th class="th" width="5%">Min. Rank</th>
<th class="th" width="5%">VIP</th>
<th class="th" width="5%">Reihen Nummer</th>
<th class="th" width="10%">Layout</th>
</tr>
<form method="post" id="save">
';
$index = 0;
$getCataloguePages = mysql_query("SELECT * FROM catalog_pages");
while($row = mysql_fetch_array($getCataloguePages))
{
$id = $row['id'];
$parent_id = $row['parent_id'];
$caption = $row['caption'];
$icon_image = $row['icon_image'];
$visible = $row['visible'];
$enabled = $row['enabled'];
$min_rank = $row['min_rank'];
$min_vip = $row['min_vip'];
$order_num = $row['order_num'];
$page_layout = $row['page_layout'];
$i++;
if(IsEven($i)){
$even = "Even";
} else {
$even = "Odd";
}
echo '
<tr>
<td class="td'.$even.'" width="5%"><input placeholder="ID" class="inputTable" name="id[]" value="'.$id.'"></td>
<td class="td<?php echo $even; ?>" width="5%"><input placeholder="Unter-ID" class="inputTable" name="parent_id[]" value="'.$parent_id.'"></td>
<td class="td<?php echo $even; ?>" width="15%"><input placeholder="Titel" class="inputTable" name="caption[]" value="'.$caption.'"></td>
<td class="td<?php echo $even; ?>" width="5%"><input placeholder="Icon" class="inputTable" name="icon_image[]" value="'.$icon_image.'"></td>
<td class="td<?php echo $even; ?>" width="5%"><select placeholder="Sichtbar" class="selectTable" name="visible[]"><option value="1">Sichtbar</option><option value="0">Nicht sichtbar</option></select></td>
<td class="td<?php echo $even; ?>" width="5%"><select placeholder="Aktiviert" class="selectTable" name="enabled[]"><option value="1">Aktiv</option><option value="0">Nicht aktiv</option></select></td>
<td class="td<?php echo $even; ?>" width="5%"><select placeholder="Mindest Rank" class="selectTable" name="min_rank[]"><option>1</option></select></td>
<td class="td<?php echo $even; ?>" width="5%"><select placeholder="VIP" class="selectTable" name="min_vip[]"><option value="1">Nur VIP</option><option value="0">Alle</option></select></td>
<td class="td<?php echo $even; ?>" width="5%"><input placeholder="Reihen Nummer" class="inputTable" name="order_num[]" value="'.$order_num.'"></td>
<td class="td<?php echo $even; ?>" width="10%"><input placeholder="Layout" class="inputTable" name="page_layout[]" value="'.$page_layout.'"></td>
</tr>
';
$index++;
}
echo '
<input class="save" type="submit" name="save" value="Speichern">
<br><br>
</form>
</table>
';
?>
<script>
$("#save").on("submit", function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "./save.php",
data: $(this).serialize(),
success: function(data) {
if($('#result').css('display') == 'none') {
document.getElementById('result').style.display = 'block'
} else {
document.getElementById('result').style.display = 'none'
setTimeout(function() {
document.getElementById('result').style.display = 'block'
}, 100);
}
},
});
});
</script><?php
}
?>
save.php:
$size = count($_POST['id']);
$i = 0;
while ($i < $size)
{
$id = $_POST['id'][$i];
$query = "UPDATE catalog_pages SET id = '".$id."' LIMIT 1";
mysql_query($query) or die ("Error in query: $query");
++$i;
}
Like I said, everything is included. Database Connection, all fine.
It is also showing me the Response with the Select but then I want to Update that data - also with ajax.
Where do I have do place the Ajax Code? How can I do that?
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";
}
?>
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;
?>