ajax call without refresh response from alert - php

I am using ajax, to simply update the DB..The problem is that after update, I use a alert to display the output. However when I click the alert box,The entire page reloads. Is there any way to avoid it??
First Up(trailnew.php)- A select drop down button with three button.
When I choose the select drop down button and click edit button
Second- I get a form from aanew.php(with some other things)
Third-Validation of this form is done in aanew.php
Target-I want the success result to be viewed in trailnew.php, without reloads.
Any alternative ideas is highly welcomed..This is new to me..Thanks..
Here is the code.
Trailnew.php
<?php
session_start();
include('connect.php');
?>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.min.js"></script>
<script>
$(document).ready(function(){
$("#form1").validate({
debug: false,
rules: {
plid:"required",
},
messages: {
plid: "Please select a pack name id..",
},
submitHandler: function(form) {
$.ajax
({
type: "POST",
url: "aanew.php",
data: $('#form1').serialize(),
cache: false,
success: function(response) {
$('#result1').html(response);
}
});
}
});
});
</script>
</head>
<body>
<div class="result3"></div>
Packing List
</br>
<form id="form1" name="form1" action="" method="post">
<?php
echo '<select name="plid" id="plid">';
echo '<option value="" selected="selected">--Select the Pack Name--</option>';
$tempholder = array();
$sql="SELECT CONCAT( p.pl_no, '_', DATE_FORMAT( p.pl_dt, '%d/%m/%Y' ) , '_', g.acname ) AS plname, g.gl_id,p.pl_no,p.pl_dt,p.no_box,p.pl_id,g.acname FROM packlist p, glmast g WHERE g.gl_id = p.gl_id ORDER BY pl_dt DESC , pl_no DESC LIMIT 30";
$query = mysql_query($sql) or die(mysql_error());
$nr = mysql_num_rows($query);
for ($i=0; $i<$nr; $i++){
$r = mysql_fetch_array($query);
if (!in_array($r['plname'], $tempholder)){
$tempholder[$i] = $r['plname'];
echo "<option value='$r[pl_id]'>".$r["plname"]."</option>";
}
}
echo '</select>';
?><br/>
<input type="submit" name="delete" value="Delete"/><br/>
<input type="submit" name="edit" id="edit" value="Edit"/><br/>
</form>
<form>
<input type="submit" name="new" id="new" class="new" value="New" /><br/>
</form>
<?php
$e=isset($_POST['form2']) && $_POST['form2'];
if($e)
{
echo "Done";
}
?>
<div id="result1"></div>
</body>
</html>
aanew.php
<?php
session_start();
include('connect.php');
?>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.min.js"></script>
<script>
$("#form2").validate({
debug: false,
rules: {
plnoedit:"required",
pldtedit:"required",
noboxedit:"required",
glidedit:"required",
},
messages: {
plnoedit: "Please select a pack list id..",
pldtedit: "Please select a item id id..",
noboxedit: "Please select a quantity id..",
glidedit: "Please select a value id..",
},
submitHandler: function(form) {
$.ajax
({
type: "POST",
url: "trailnew.php",
data: $('#form2').serialize(),
cache: false,
success: function(response) {
$('#result1').html(response);
}
});
}
});
</script>
</head>
<body>
<div id="#result1"></div>
<?php
$e=isset($_POST['plid']) && $_POST['plid'];
$f=isset($_POST['edit']) && $_POST['edit'];
if($e&&$f)
{
$id=$_POST['plid'];
$query5=mysql_query("SELECT g.gl_id, p.pl_no, p.pl_dt, p.no_box, p.pl_id,g.acname
FROM packlist p, glmast g
WHERE g.gl_id = p.gl_id
AND p.pl_id ='".$id."'
LIMIT 0 , 30") or die(mysql_error());
$row=mysql_fetch_array($query5);
$pl_no=$row['pl_no'];
$pl_dt=$row['pl_dt'];
$no_box=$row['no_box'];
$acname=$row['acname'];
?>
<form name="form2" id="form2" method="post" action="">
<P>
<LABEL for="plnoedit">PackList No
<INPUT type="text" id="plnoedit" name="plnoedit" value= <?php echo $pl_no; ?> /></LABEL><BR><BR>
<input type="hidden" name="myFormsName" value="form5id" id="myFormsName">
<LABEL for="pldtedit">Date
<INPUT type="text" id="pldtedit" name="pldtedit" value= <?php echo $pl_dt; ?> /></LABEL><BR><BR>
<LABEL for="noboxedit">Box No
<INPUT type="text" id="noboxedit" name="noboxedit" value= <?php echo $no_box; ?> /></LABEL><BR><BR>
<LABEL for="glidedit">Party Name
<INPUT type="text" id="glidedit" name="glidedit" value= <?php echo $acname; ?> /></LABEL><BR><BR>
<INPUT type="submit" id="editsubmit" name="editsubmit" value="Submit"> <INPUT type="reset">
</P>
</form>
<?php
//pagination starts
$id=$_POST['plid'];
$per_page = 4;
$query12=mysql_query("SELECT `pld_id`,`pl_id`, `item_id`, `quantity`, `size`, `potency`, `box` FROM `packlistdtl` WHERE pl_id ='".$id."' GROUP BY `box` ORDER BY `box` desc") or die(mysql_error());
// figure out the total pages in the database
$total_results = mysql_num_rows($query12);
$total_pages = ceil($total_results / $per_page);
// check if the 'page' variable is set in the URL (ex: view-paginated.php?page=1)
if (isset($_GET['page']) && is_numeric($_GET['page']))
{
$show_page = $_GET['page'];
// make sure the $show_page value is valid
if ($show_page > 0 && $show_page <= $total_pages)
{
$start = ($show_page -1) * $per_page;
$end = $start + $per_page;
}
else
{
// error - show first set of results
$start = 0;
$end = $per_page;
}
}
else
{
// if page isn't set, show first set of results
$start = 0;
$end = $per_page;
}
// display pagination
echo "<p><a href='view.php'>View All</a> | <b>View Page:</b> ";
for ($i = 1; $i <= $total_pages; $i++)
{
echo "<a href='view.php?page=$i'>$i</a> ";
}
echo "</p>";
// display data in table
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>Box</th> <th>Item Name</th> <th>Size</th> <th>Potency</th> <th>Quantity</th> <th></th> <th></th></tr>";
// loop through results of database query, displaying them in the table
for ($i = $start; $i < $end; $i++)
{
$item_id=mysql_result($query12, $i, 'item_id');
$query13=mysql_query("SELECT `item_name` FROM `itemmast` WHERE item_id ='".$item_id."'") or die(mysql_error());
$row1=mysql_fetch_array($query13);
$item_name=$row1['item_name'];
// make sure that PHP doesn't try to show results that don't exist
if ($i == $total_results) { break; }
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . mysql_result($query12, $i, 'box') . '</td>';
echo '<td>' .$item_name. '</td>';
echo '<td>' . mysql_result($query12, $i, 'size') . '</td>';
echo '<td>' . mysql_result($query12, $i, 'potency') . '</td>';
echo '<td>' . mysql_result($query12, $i, 'quantity') . '</td>';
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo "</tr>";
}
// close table>
echo "</table>";
// pagination
}
?>
</body>
</html>

Probably need to return false from click handler of link or button to prevent the default action

Related

Ajax Pagination not working properly

<?php include("config.php");
error_reporting(E_ALL); ini_set('display_errors', 1);
$results = mysqli_query($con,"SELECT COUNT(name) FROM user_tbl ");
$get_total_rows = mysqli_fetch_array($results); //total records
//break total records into pages
$pages = ceil($get_total_rows[0]/$item_per_page);
?>
<script type="text/javascript">
$(document).ready(function() {
$("#results").load("fetch_pages.php"); //initial page number to load
$(".pagination").bootpag({
total: <?php echo $pages; ?>,
page: 1,
maxVisible: 5
}).on("page", function(e, num){
e.preventDefault();
$("#results").prepend('<div class="loading-indication"><img src="ajax-loader.gif" /> Loading...</div>');
$("#results").load("fetch_pages.php", {'page':num});
});
});
</script>
<body>
<div id="serch">
<form method="post" enctype="multipart/form-data">
<label>SEARCH BY NAME:</label>
<input type="text" name="name" class="name" >
<input type="submit" name="submit" class="sbmtt" value="SEARCH" />
</form>
</div>
</table>
<div class="res">
<div class="navi">
<div id="results"></div>
<div class="pagination"></div>
</div>
</div>
</body>
fetch_pages.php:
<?php
include("config.php"); //include config file
if(isset($_POST["page"])) {
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
if(!is_numeric($page_number)) {
//incase of invalid page number
die('Invalid page number!');
}
} else {
$page_number = 1;
}
//get current starting point of records
$position = (($page_number-1) * $item_per_page);
//Limit our results within a specified range.
$results = mysqli_query($con, "SELECT * FROM user_tbl WHERE name = 'aruna' ORDER BY id ASC LIMIT $position, $item_per_page");
//output results from database
echo '<ul class="page_result">';
while($row = mysqli_fetch_array($results)) {
echo 'Name: ' .$row['name'];
echo '<br /><br />Contact Number: ' .$row['cont'];
echo '<br /><br />Email ID: ' .$row['email'];
echo '<br /><br />View details';
echo "<br /><hr />";
}
echo '</ul>';
?>
Config.php:
<?php
$con = mysqli_connect("localhost","root","","mydb");
$item_per_page = 3;
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Here the result just shows in the div.. i want to fetch the result after the form get submitted .. i tried if(isset($_POST['submit'])) but not working.. and the search should be done by fetching the name from the html form not the way i ve given in fetch_pages.php like 'aruna' .. it should get fetched by the form data like $_POST['name'] .. i m really stuck here.. any help plzzz .. thanks in advance
You need to pass search form value. Below is the full updated code.
<?php include("config.php");
error_reporting(E_ALL); ini_set('display_errors', 1);
$name = "";
$where = "";
if(isset($_POST["name"])){
$name = $_POST["name"];
$where = " WHERE name = '".$name."' ";
}
$results = mysqli_query($con,"SELECT COUNT(name) FROM user_tbl $where");
$get_total_rows = mysqli_fetch_array($results); //total records
//break total records into pages
$pages = ceil($get_total_rows[0]/$item_per_page);
?>
<script type="text/javascript">
$(document).ready(function() {
var name = '<?php echo $name; ?>';
$("#results").load("fetch_pages.php", {'name':name}); //initial page number to load
$(".pagination").bootpag({
total: <?php echo $pages; ?>,
page: 1,
maxVisible: 5
}).on("page", function(e, num){
e.preventDefault();
$("#results").prepend('<div class="loading-indication"><img src="ajax-loader.gif" /> Loading...</div>');
$("#results").load("fetch_pages.php", {'page':num, 'name':name});
});
});
</script>
<body>
<div id="serch">
<form method="post" enctype="multipart/form-data">
<label>SEARCH BY NAME:</label>
<input type="text" name="name" class="name" value="<?php echo $name; ?>">
<input type="submit" name="submit" class="sbmtt" value="SEARCH" />
</form>
</div>
</table><div class="res">
<div class="navi">
<div id="results"></div>
<div class="pagination"></div>
</div> </div>
</body>
fetch_pages.php:
<?php
include("config.php"); //include config file
if(isset($_POST["page"])){
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
if(!is_numeric($page_number)){die('Invalid page number!');} //incase of invalid page number
}else{
$page_number = 1;
}
//get current starting point of records
$position = (($page_number-1) * $item_per_page);
$name = "";
$where = "";
if(isset($_POST["name"])){
$name = $_POST["name"];
$where = " WHERE name = '".$name."' ";
}
//Limit our results within a specified range.
$results = mysqli_query($con, "SELECT * FROM user_tbl $where ORDER BY id ASC LIMIT $position, $item_per_page");
//output results from database
echo '<ul class="page_result">';
while($row = mysqli_fetch_array($results))
{
echo 'Name: ' .$row['name'];
echo '<br /><br />Contact Number: ' .$row['cont'];
echo '<br /><br />Email ID: ' .$row['email'];
echo '<br /><br />View details';
echo "<br /><hr />";
}
echo '</ul>';
?>
Hope it will help.

How to update my sql table with out page refresh in php?

Hi i want to update my sql table field without page refresh in php how can i achieve i tried but my code is not working i do not know where i am wrong
index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready(function(){
$('#myForm').on('submit',function(e) {
$.ajax({
url:'assignlead.php',
data:$(this).serialize(),
type:'POST',
success:function(data){
console.log(data);
$("#success").show().fadeOut(5000);
},
error:function(data){
$("#error").show().fadeOut(5000);
}
});
e.preventDefault();
});
});
</script>
</head>
<body>
<?php
include('conn.php');
$per_page = 3;
if($_GET)
{
$page=$_GET['page'];
}
$start = ($page-1)*$per_page;
$select_table = "select * from clientreg order by id limit $start,$per_page";
$variable = mysql_query($select_table);
?>
<form class="form2" action="" method="POST" name="myForm" id="myForm">
<div style="width:100%;">
<?php
$i=1;
while($row = mysql_fetch_array($variable))
{
?>
<input type="checkbox" name="users[]" value="<?php echo $row["id"]; ?>" >
<?php
}
?>
<div class="buttons"> <span id="error" style="display:none; color:#F00">Some Error!Please Fill form Properly </span> <span id="success" style="display:none; color:#0C0">All the records are submitted!</span>
<input class="greybutton" type="submit" value="Send" />
</div>
<?php
$sql = mysql_query("SELECT *FROM login where role=1");
while ($row = mysql_fetch_array($sql)){
?>
<input type="checkbox" name="eid[]" value="<?php echo $row["eid"]; ?>" ><?php echo $row["username"]; ?>
<?php
}
?>
</div>
</form>
</div>
</body>
</html>
assignlead.php
<?php
$conn = mysql_connect("localhost","root","root");
mysql_select_db("helixcrm",$conn);
if(isset($_POST["submit"]) && $_POST["submit"]!="") {
$usersCount = count($_POST["id"]);
for($i=0;$i<$usersCount;$i++) {
mysql_query("UPDATE clientreg set eid='" . $_POST["eid"][$i] . "' WHERE id='" . $_POST["id"][$i] . "'");
}
}
?>
<?php
$rowCount = count($_POST["users"]);
for($i=0;$i<$rowCount;$i++) {
$result = mysql_query("SELECT * FROM clientreg WHERE Id='" . $_POST["users"][$i] . "'");
$row[$i]= mysql_fetch_array($result);
$id=$row[$i]['id'];
?>
<input type="hidden" name="id[]" class="txtField" value="<?php echo $row[$i]['id']; ?>"></td>
<?php
$rowCoun = count($_POST["eid"]);
for($j=0;$j<$rowCoun;$j++) {
$result = mysql_query("SELECT * FROM login WHERE eid='" . $_POST["eid"][$j] . "'");
$row[$j]= mysql_fetch_array($result);
$eid=$row[$j]['eid'];
?>
<input type="hidden" name="eid[]" class="txtField" value="<?php echo $row[$j]['eid']; ?>">
<?php
}
}
?>
i tried a lot but i am not able to get my output
How can i achieve my output
Thanks in advance
Update your javascript like this :
$(document).ready(function(){
$('#myForm').submit(function(){
$.ajax({
url : 'assignlead.php',
data : $(this).serialize(),
type : 'POST',
success : function(data){
console.log(data);
$("#success").show().fadeOut(5000);
},
error:function(data){
$("#error").show().fadeOut(5000);
}
});
// !important for ajax form submit
return false;
});
});

View customer info on select change

I'm creating a page which will allow an admin to select a user from a drop down list, which populates from a database. When the person is selected, the info associated with that person will then be viewed on the page. I already have a select statement which selects all the info and the drop down menu is populating correctly. However, I'm unsure on how to get that selected user's info to display on the page once selected. Would I need to do an entirely different select statement and query which checks which customer was selected? Or is there another way?
customer.php
<div id="view_form" class="view">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<label for="viewCustomer">Select Customer</label>
<?php
echo "<select name='selectCust' id='selectCust'>";
echo "<option></option>";
while($row = mysqli_fetch_assoc($custResult)){
$name = "{$row['fName']} {$row['lName']}";
echo "<option>$name</option>";
}
echo "</select>";
?>
</fieldset>
</form>
</div>
viewUser.php
if(isset($search)){
$select = "SELECT * FROM $cust WHERE acctNum='{$search}'";
$result = mysqli_query($db, $select);
if(mysqli_num_rows($result) > 0){
if($row = mysqli_fetch_assoc($result)){
$acct = "{$row['acctNum']}";
echo $acct;
}
}
}
script.js
$(document).ready(function(){
function searchAjax(){
var search = $('#selectCust').val();
$.post('includes/viewUser.php', {searchUsers: search}, function(data){
$('#view_form').append(data);
})
}
$('#selectCust').on('change', function(ev){
ev.preventDefault();
searchAjax();
})
})
Search.php
<script type="text/javascript "src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
$(".dropdown-users").on("change",function(event){
event.preventDefault();
search_ajax_way();
});
});
function search_ajax_way(){
var search_this=$("dropdown-users").val();
$.post("Ajaxsearch.php", {searchusers : search_this}, function(data){
$(".results").html(data);
})
}
</script>
<div id="view_form" class="view">
<form method="post">
<fieldset>
<label for="viewCustomer">Select Customer</label>
<?php
echo "<select class="dropdown-users">";
echo "<option></option>";
while($row = mysqli_fetch_assoc($custResult)){
$name = "{$row['fName']} {$row['lName']}";
$acct = $row['acctNum'];
echo "<option value="$acct">$name ($acct)</option>";
}
echo "</select>";
?>
</fieldset>
</form>
</div>
<label>Enter</label>
<input type="text" name="search_query" id="search_query" placeholder="What You Are Looking For?" size="50"/>
<input type="<span id="IL_AD1" class="IL_AD">submit</span>" <span id="IL_AD6" class="IL_AD">value</span>="Search" id="button_find" />
<div class="results"></div>
//********************************************************************************************
********************************************************************************************//
Ajaxsearch.php
<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db"); // Enter your information here
$term = $_POST['searchusers']
$term = mysqli_real_escape_string($con, $term);
if($term == "")
echo "Enter Something to search";
else {
$query = mysqli_query($con, "select * from USERDATEBASEHERE where ID = '{$term}' ");
$string = '';
if (mysqli_num_rows($query) > 0) {
if (($row = mysqli_fetch_assoc($query)) !== false) {
$string = "{$row['ID']}";
}
} else {
$string = "This Person does not exist";
}
echo $string;
}
?>
<div id="view_form" class="view">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<label for="viewCustomer">Select Customer</label>
<?php
echo "<select name=\"somename\" onchange=\"this.form.submit();\">";
echo "<option value=\"\">Select User</option>";
while($row = mysqli_fetch_assoc($custResult)){
$name = "{$row['fName']} {$row['lName']}";
$acct = $row['acctNum'];
echo '<option value="'.$acct.'">$name ($acct)</option>';
}
echo "</select>";
?>
</fieldset>
</form>
</div>
The options must have some refering value, through which you can retrieve the details of selected user, whenever the value of option is not initiated then the default value of the option will be option's label.

PHP Multiple form in same page

I'm doing form in php but I have some problem.
First I will have 3 different form in the same page.
What I want is only 1 form appear and then with the answer a second form will appear and so on.
The answer of the form will be display on the same page.
For now my first form work and after get the answer go to the 2nd form but I want to submit the 2nd form the problem appear.
It delete the answer of my first form and don't do anything (everything start like I am in my first form).
I try to find the problem but can't have idea about how to solve it.
Here is my code:
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Q1?
<input type="number" name="nbtemplate" min="1" max="30">
<input type="submit" name="submitbutton1" value="Confirm!">
</form>
<?php
if(!isset($submitbutton1)) {
if (!empty($_POST['nbtemplate']) != "") {
echo "<b>{$_POST['nbtemplate']}</b> !\n";
echo "<br />";
$Nnbtemplate = $_POST['nbtemplate'];
$result = mysql_query("UPDATE tb SET day='$Nnbtemplate'") or die(mysql_error());
?>
<form action='<?php echo $_SERVER['PHP_SELF'];?>' method='post'>
Q2? <br>
<?php
for ($i = 1; $i <= $Nnbtemplate; $i++) { // start loop
echo "Template ";
echo $i;
?>
<input type="number" name="nbtime" min="1" max="96">
<?php
}
echo '<input type="submit" name="submitbutton2" value="Confirm!">';
echo '</form>';
if(isset($submitbutton1) && !isset($submitbutton2)) {
if (!empty($_POST['nbtime']) != "") {
echo "<b>{$_POST['nbtime']}</b> !\n";
echo "<br />";
$nbtime = $_POST['nbtime'];
for ($j = 1; $j <= $nbtime; $j++) {
echo "Time";
echo $j;
?>
Q3:
<input type="time" name="starttime"> To <input type="time" name="endtime">
<?php
}
echo '<input type="submit">';
echo '</form>';
}
}
}
}
?>
That is some gnarly code you got there, brother. This is a really simple task when handled with some javascript. Then you can have a single post to your php. I like using the jQuery framework so here's a couple links I found quickly: this one and this one
Example code in response to comment about building form elements dynamically:
<html>
<head>
<!-- load jquery library -->
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body>
<form action="toyourpage.php">
How Many?:
<input type="text" name="number" id="number">
<div id="add"></div>
</form>
<!-- javascript go -->
<script type="text/javascript">
$(document).ready(function()
{
$('input#number').keyup(function()
{
var num = $(this).val(); // get num
if(!isNaN(num)) // check if number
{
$('div#add').html(''); // empty
for(i = 1; i <= num; i++) // add
{
$('div#add').append('New Field ' + i + ': <input type="text" name="next_' + i + '" id="next' + i + '"><br>');
}
}
else
{
alert('Valid number required');
}
});
});
</script>
</body>
</html>
I did some changes on Your code, and have tested, it works.
You had any mistakes in your {} brackets and if conditions. Also as I commented I added extract($_POST).
<?php
extract ( $_POST );
if (! isset ( $submitbutton1 ) && !isset($submitbutton2)) {
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Q1? <input type="number" name="nbtemplate" min="1" max="30"> <input
type="submit" name="submitbutton1" value="Confirm!">
</form>
<?php ;
}
if (isset ( $submitbutton1 )) {
if (! empty ( $_POST ['nbtemplate'] ) != "") {
echo "<b>{$_POST['nbtemplate']}</b> !\n";
echo "<br />";
$Nnbtemplate = $_POST ['nbtemplate'];
$result = mysql_query("UPDATE tb SET day='$Nnbtemplate'") or
die(mysql_error());
?>
<form action='<?php echo $_SERVER['PHP_SELF'];?>' method='post'>
Q2? <br>
<?php
for($i = 1; $i <= $Nnbtemplate; $i ++) { // start loop
echo "Template ";
echo $i;
?>
<input type="number" name="nbtime" min="1" max="96">
<?php
}
echo '<input type="submit" name="submitbutton2" value="Confirm!">';
echo '</form>';
}
}
if ( isset ( $submitbutton2 )) {
if (! empty ( $_POST ['nbtime'] ) != "") {
echo "<b>{$_POST['nbtime']}</b> !\n";
echo "<br />";
$nbtime = $_POST ['nbtime'];
for($j = 1; $j <= $nbtime; $j ++) {
echo "Time";
echo $j;
?>
Q3:
<input type="time" name="starttime"> To <input type="time"
name="endtime">
<?php
}
echo '<input type="submit">';
echo '</form>';
}
}
?>

Php Ajax form submit in colorbox

I have a form with some php to validate and insert in the database on submit and the form opens in colorbox.
So far so good. What I'm trying to do is to close colorbox and refresh a div on success.
I guess I need to pass a response to ajax from php if everything OK, close the colorbox with something like setTimeout($.fn.colorbox.close,1000); and refresh the div, but I'm stuck because I'm new in ajax.
I'll appreciate any help here.
Here is my ajax:
jQuery(function(){
jQuery('.cbox-form').colorbox({maxWidth: '75%', onComplete: function(){
cbox_submit();
}});
});
function cbox_submit()
{
jQuery("#pre-process").submit(function(){
jQuery.post(
jQuery(this).attr('action'),
jQuery(this).serialize(),
function(data){
jQuery().colorbox({html: data, onComplete: function(){
cbox_submit();
}});
}
);
return false;
});
}
form php code:
<?php
error_reporting(-1);
include "conf/config.php";
if(isset($_REQUEST['rid'])){$rid=safe($_REQUEST['rid']);}
if(isset($_REQUEST['pid'])){$pid=safe($_REQUEST['pid']);}
$msg = '';
if (!$_SESSION['rest_id']) $_SESSION['rest_id']=$rid; //change to redirect
$session_id=session_id();
if(isset($_REQUEST['submit'])){
if(isset($_POST['opta'])){
$opta=safe($_POST['opta']);
$extraso = implode(',',array_values( array_filter($_POST['opta']) ));
}
if (array_search("", $_POST['opt']) !== false)
{
$msg = "Please select all accessories!";
}else{
$extrasm = implode(',',array_values( array_filter($_POST['opt']) ));
if ($_POST['opt'] && isset($_POST['opta'])) {$extras= $extrasm .",". $extraso;}
if ($_POST['opt'] && !isset($_POST['opta'])) {$extras= $extrasm;}
if (!$_POST['opt'] && isset($_POST['opta'])) {$extras= $extraso;}
$sql['session_id'] = $session_id;
$sql['rest_id'] = $_POST['rid'];
$sql['prod_id'] = $_POST['pid'];
$sql['extras'] = $extras;
$sql['added_date'] = Date("Y-m-d H:i:s");
$newId=insert_sql("cart",$sql);
}
}
?>
<form id="pre-process" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<div style="background-color:#FFF; padding:20px;">
<?=$msg;?>
<?php
$name = getSqlField("SELECT name FROM products WHERE resid=".$_SESSION['rest_id']." and id=".$pid."","name");
echo "<div style='color:#fff; background-color:#F00;padding:10px;' align='center'><h2>".$name."</h2></div><div style='background-color:#FFF; padding: 20px 70px 30px 70px; '>Please select accessories.<br><br>";
$getRss = mysql_query("SELECT * FROM optional_groups_product where prodid=".$pid." order by id asc");
while ($rsrw = #mysql_fetch_array($getRss)) {
$goptionals = getSqlField("SELECT goptionals FROM optionals_groups WHERE resid=".$_SESSION['rest_id']." and id=".$rsrw['goptid']."","goptionals");
$goptionals=explode(', ',($goptionals));
echo "<select name='opt[]' id='opt[]' style='width:220px;'>";
echo "<option value='' >Select Options</option>";
foreach($goptionals as $v)
{
$vname = mysql_query("SELECT * FROM optionals where id=".$v." LIMIT 0,1");
while ($rsgb = #mysql_fetch_array($vname)) {
$aa=$rsgb['optional'];
}
echo "<option value=".$v." >".$aa."</option>";
}
echo "</select>(required)<br>";
//}
}
$getRss = mysql_query("SELECT * FROM optional_product where prodid=".$pid."");
?>
<br><br>
<table border="0" cellpadding="0" cellspacing="0" >
<tr>
<td bgcolor="#EAFFEC">
<div style="width:440px; ">
<?php
while ($rssp = #mysql_fetch_array($getRss)) {
$optional=getSqlField("SELECT optional FROM optionals WHERE id=".$rssp['optid']."","optional");
$price=getSqlField("SELECT price FROM optionals WHERE id=".$rssp['optid']."","price");
?>
<div style="width:180px;background-color:#EAFFEC; float:left;padding:10px;""><input type="checkbox" name="opta[]" id="opta[]" value="<?=$rssp['optid']?>" /> <i><?=$optional?> [<?=CURRENCY?><?=$price?> ]</i> </div>
<?php } ?>
</div>
</td>
</tr></table>
<input type="hidden" name="rid" value="<?=$rid?>" />
<input type="hidden" name="pid" value="<?=$pid?>"/>
</div><input type="hidden" name="submit" /><input id='submit' class="CSSButton" style="width:120px; float:right;" name='submit' type='submit' value=' Continue ' /><br />
<br /><br />
</div>
</form>
I don't know colobox, but if I understand well what you are trying to do,
I would say your javascript should more look like this
function cbox_submit()
{
jQuery("#pre-process").submit(function(e) {
e.preventDefault(); // prevents the form to reload the page
jQuery.post(
jQuery(this).attr('action')
, jQuery(this).serialize()
, function(data) {
if (data['ok']) { // ok variable received in json
jQuery('#my_colorbox').colorbox.close(); // close the box
}
}
);
return false;
});
}
jQuery(function() {
jQuery('#my_colorbox').colorbox({
maxWidth: '75%'
, onComplete: cbox_submit // Bind the submit event when colorbox is loaded
});
});
You should separate at least your php script that does the post part.
And this php (called with jQuery(this).attr('action')) should return a json ok variable if successfull. Example:
<?php
# ... post part ...
# if success
ob_clean();
header('Content-type: application/json');
echo json_encode(array('ok' => true));
?>

Categories