Alert message in Forms - javascript

I still can't get the right flow for this. I know it's simple and i think that my code is right but still the alert message is showing when i hit the buy button even if the input box is null. What i wanted is that no alert message will show if the input box is null but if the input box is filled then that;s the only time where the alert message will show when button is clicked. Here is my code:
<?php
require_once('auth.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Athan Motorcycle</title>
<style type="text/css">
<!--
.style1 {
color: #000000;
font-weight: bold;
font-size: 24px;
}
-->
</style>
<!--<script type="text/javascript">
function validateForm()
{
var a=document.forms["abc"]["qty"].value;
if ((a==null || a==""))
{
alert("Please specify the quantity.");
return false;
}
}
</script>-->
</head>
<body>
<form action="saveorder.php" name="abc" method="post">
<input name="id" type="hidden" value="<?php echo $_SESSION['SESS_MEMBER_ID']; ?>" />
<input name="transcode" type="hidden" value="<?php echo $_SESSION['SESS_FIRST_NAME']; ?>" />
<table width="400" border="0" cellpadding="0" cellspacing="0">
<?php
if (isset($_GET['id']))
{
include('config.php');
$id=$_GET['id'];
$result = mysql_query("SELECT * FROM athan_products WHERE product_id = $id and status='available'");
$row3 = mysql_fetch_array($result);
echo '<tr>';
echo '<td width="80"><img alt="Motor" src="images/motor/'.$row3['product_photo'].'" /></td>';
echo '<td width="200"><span class="style1">'.'</span></td>';
echo '<td width="120"></span></td>';
echo '</tr>';
echo '<tr>';
echo '<td width="80"><input name="name" type="text" value="'.$row3['partsname'].'" readonly/><input name="ingre" type="hidden" value="'.$row3['product_ingredients'].'"/> <input name="ids" type="hidden" value="'.$row3['id'].'"/></td>';
echo '<td width="120"></span></td>';
echo '</tr>';
}
?>
</table>
<br />
<label style="color:#000000;">Qty:
<input type="number" min="1" id="qty" name="qty" required = "required" />
</label>
<br />
<table width="400" border="0" cellpadding="0" cellspacing="0" style="color:#000000;">
<tr>
<!--<td width="179">Size</td>-->
<td width="128">Price</td>
<td width="179">Description</td>
<td width="93">Selection</td>
</tr>
<?php
if (isset($_GET['id']))
{
include('config.php');
$id=$_GET['id'];
$result = mysql_query("SELECT * FROM athan_products WHERE product_id = $id");
while($row3 = mysql_fetch_array($result))
{
$resultq = mysql_query("SELECT * FROM inventory WHERE product_id LIKE '%".$id."%'");
//$resultq = mysql_query("SELECT * FROM inventory WHERE product_id LIKE =$id");
while($rows = mysql_fetch_array($resultq))
{
$qwerty=$rows['qtyleft'];
}
if ($qwerty !=0){
echo '<tr>';
//echo '<td>'.$row3['product_size_name'].'</td>';
echo '<td>'.$row3['price'].'</td>';
echo '<td>'.$row3['description'].'</td>';
echo '<td>'.'<input name="but" type="image" value="'.$row3['id'].'" src="images/button.png" onclick="return myFunction()" />'.'</td>';
echo '</tr>';
}
else
{
echo '"This Item is not Available"';
//echo '<td>'.'<h1>'.'"not available"'.'</h1>'.'</td>';
}
}
}
?>
</table>
</form>
<script type="text/javascript">
function myFunction()
{
var a=document.forms["abc"]["qty"].value;
if (a!=null || a!= ""){
alert("Item has been successfully added to your Cart");
}
}
</script>
</body>
</html>

Your OR should be an AND:
if(a!=null && a!= "")
Since a is not equal to null, the condition is true

Instead of checking for null or empty, you should check if a.length is 0
if(a.length !== 0){
// do stuff
}

Related

How to update quantity of database from php action

I am building a database of different devices which is displayed in a page which sells medical devices. When a user adds a quantity of the device to the cart, I want the database to be updated with (stock - quantity in cart) I am trying to do this on PHP but am having no luck. My attempt and code is below.
Here is a snippet of my attempt. I'm not sure where to place this in the code below.
<?php
$value = isset($_POST['item']) ? $_POST['item'] : 1; //to be displayed
if(isset($_POST['incqty'])){
$value += 1;
$query = "UPDATE products SET stock= (stock-$product_qty) WHERE product_name=$product_name";
mysql_select_db('products');
$retval = mysql_query($query,$mysqli);
}
?>
This is code for index.php
<?php
session_start();
include_once("config.php");
//current URL of the Page. cart_update.php redirects back to this URL
$current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Shopping Cart</title>
<link href="style/style.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1 align="center">Products </h1>
<!-- View Cart Box Start -->
<?php
if(isset($_SESSION["cart_products"]) && count($_SESSION["cart_products"])>0)
{
echo '<div class="cart-view-table-front" id="view-cart">';
echo '<h3>Your Shopping Cart</h3>';
echo '<form method="post" action="cart_update.php">';
echo '<table width="100%" cellpadding="6" cellspacing="0">';
echo '<tbody>';
$total =0;
$b = 0;
foreach ($_SESSION["cart_products"] as $cart_itm)
{
$product_name = $cart_itm["product_name"];
$product_qty = $cart_itm["product_qty"];
$product_price = $cart_itm["product_price"];
$product_code = $cart_itm["product_code"];
$product_color = $cart_itm["product_color"];
$bg_color = ($b++%2==1) ? 'odd' : 'even'; //zebra stripe
echo '<tr class="'.$bg_color.'">';
echo '<td>Qty <input type="text" size="2" maxlength="2" name="product_qty['.$product_code.']" value="'.$product_qty.'" /></td>';
echo '<td>'.$product_name.'</td>';
echo '<td><input type="checkbox" name="remove_code[]" value="'.$product_code.'" /> Remove</td>';
echo '</tr>';
$subtotal = ($product_price * $product_qty);
$total = ($total + $subtotal);
}
echo '<td colspan="4">';
echo '<button type="submit">Update</button>Checkout';
echo '</td>';
echo '</tbody>';
echo '</table>';
$current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';
echo '</form>';
echo '</div>';
}
?>
<!-- View Cart Box End -->
<!-- Products List Start -->
<?php
$results = $mysqli->query("SELECT product_code, product_name, product_desc, product_img_name, price, stock FROM products ORDER BY id ASC");
if($results){
$products_item = '<ul class="products">';
//fetch results set as object and output HTML
while($obj = $results->fetch_object())
{
$products_item .= <<<EOT
<li class="product">
<form method="post" action="cart_update.php">
<div class="product-content"><h3>{$obj->product_name}</h3>
<div class="product-thumb"><img src="images/{$obj->product_img_name}"></div>
<div class="product-desc">{$obj->product_desc}</div>
<div class="product-info">
Price {$currency}{$obj->price}
<fieldset>
<label>
<span>Color</span>
<select name="product_color">
<option value="Black">Black</option>
<option value="Silver">Silver</option>
</select>
</label>
<label>
<span>Quantity</span>
<input type="text" size="2" maxlength="2" name="product_qty" value="1" />
</label>
</fieldset>
<input type="hidden" name="product_code" value="{$obj->product_code}" />
<input type="hidden" name="type" value="add" />
<input type="hidden" name="return_url" value="{$current_url}" />
<div align="center"><button type="submit" id="updateb" class="add_to_cart">Add</button></div>
</div></div>
</form>
</li>
EOT;
}
$products_item .= '</ul>';
echo $products_item;
}
?>
<!-- Products List End -->
</body>
</html>
This is code for cart_update.php
<?php
session_start();
include_once("config.php");
//add product to session or create new one
if(isset($_POST["type"]) && $_POST["type"]=='add' && $_POST["product_qty"]>0)
{
foreach($_POST as $key => $value){ //add all post vars to new_product array
$new_product[$key] = filter_var($value, FILTER_SANITIZE_STRING);
}
//remove unecessary vars
unset($new_product['type']);
unset($new_product['return_url']);
//we need to get product name and price from database.
$statement = $mysqli->prepare("SELECT product_name, price, stock FROM products WHERE product_code=? LIMIT 1");
$statement->bind_param('s', $new_product['product_code']);
$statement->execute();
$statement->bind_result($product_name, $price, $stock);
while($statement->fetch()){
//fetch product name, price from db and add to new_product array
$new_product["product_name"] = $product_name;
$new_product["product_price"] = $price;
$new_product["product_stock"] = $stock;
if(isset($_SESSION["cart_products"])){ //if session var already exist
if(isset($_SESSION["cart_products"][$new_product['product_code']])) //check item exist in products array
{
unset($_SESSION["cart_products"][$new_product['product_code']]); //unset old array item
}
}
$_SESSION["cart_products"][$new_product['product_code']] = $new_product; //update or create product session with new item
}
}
//update or remove items
if(isset($_POST["product_qty"]) || isset($_POST["remove_code"]))
{
//update item quantity in product session
if(isset($_POST["product_qty"]) && is_array($_POST["product_qty"])){
foreach($_POST["product_qty"] as $key => $value){
if(is_numeric($value)){
$_SESSION["cart_products"][$key]["product_qty"] = $value; //change
}
}
}
//remove an item from product session
if(isset($_POST["remove_code"]) && is_array($_POST["remove_code"])){
foreach($_POST["remove_code"] as $key){
unset($_SESSION["cart_products"][$key]);
}
}
}
//back to return url
$return_url = (isset($_POST["return_url"]))?urldecode($_POST["return_url"]):''; //return url
header('Location:'.$return_url);
?>
This is code for view_cart.php
<?php
session_start();
include_once("config.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>View shopping cart</title>
<link href="style/style.css" rel="stylesheet" type="text/css"></head>
<body>
<h1 align="center">View Cart</h1>
<div class="cart-view-table-back">
<form method="post" action="cart_update.php">
<table width="100%" cellpadding="6" cellspacing="0"><thead><tr><th>Quantity</th><th>Name</th><th>Price</th><th>Total</th><th>Remove</th></tr></thead>
<tbody>
<?php
if(isset($_SESSION["cart_products"])) //check session var
{
$total = 0; //set initial total value
$b = 0; //var for zebra stripe table
foreach ($_SESSION["cart_products"] as $cart_itm)
{
//set variables to use in content below
$product_name = $cart_itm["product_name"];
$product_qty = $cart_itm["product_qty"];
$product_price = $cart_itm["product_price"];
$product_code = $cart_itm["product_code"];
$product_color = $cart_itm["product_color"];
$subtotal = ($product_price * $product_qty); //calculate Price x Qty
$bg_color = ($b++%2==1) ? 'odd' : 'even'; //class for zebra stripe
echo '<tr class="'.$bg_color.'">';
echo '<td><input type="text" size="2" maxlength="2" name="product_qty['.$product_code.']" value="'.$product_qty.'" /></td>';
echo '<td>'.$product_name.'</td>';
echo '<td>'.$currency.$product_price.'</td>';
echo '<td>'.$currency.$subtotal.'</td>';
echo '<td><input type="checkbox" name="remove_code[]" value="'.$product_code.'" /></td>';
echo '</tr>';
$total = ($total + $subtotal); //add subtotal to total var
}
$grand_total = $total + $shipping_cost; //grand total including shipping cost
foreach($taxes as $key => $value){ //list and calculate all taxes in array
$tax_amount = round($total * ($value / 100));
$tax_item[$key] = $tax_amount;
$grand_total = $grand_total + $tax_amount; //add tax val to grand total
}
$list_tax = '';
foreach($tax_item as $key => $value){ //List all taxes
$list_tax .= $key. ' : '. $currency. sprintf("%01.2f", $value).'<br />';
}
$shipping_cost = ($shipping_cost)?'Shipping Cost : '.$currency. sprintf("%01.2f", $shipping_cost).'<br />':'';
}
?>
<tr><td colspan="5"><span style="float:right;text-align: right;"><?php echo $shipping_cost. $list_tax; ?>Amount Payable : <?php echo sprintf("%01.2f", $grand_total);?></span></td></tr>
<tr><td colspan="5">Add More Items<button type="submit">Update</button></td></tr>
</tbody>
</table>
<input type="hidden" name="return_url" value="<?php
$current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
echo $current_url; ?>" />
</form>
</div>
</body>
</html>
your variables $product_qty and $product_name are not defined and in the query pass the product name in the quotes as your query is in double quotes so pass name in the single quotes.
Also it will be better if you update using primary id not by name.

Show second Submit button after clicking first Submit with form submit - Javascript

I've build a function in javascript to show me a second submit but only after the first submit was clicked.
Edited - this is ex.php:
<form method="post" action = "ex.php">
<input type="submit" id="button" name="search" value="Search"
onclick="myFunction();" >
<br>
<input type="submit" name="search_close" id="submit" style="display:
none;" value="Find close results">
</form>
<?php
if(isset($_POST['search']))
{
echo "first search";
}
else if(isset($_POST['search_close']))
{
echo "second search";
}
else {
echo "nothing";
}
?>
<script type="text/javascript">
inputSubmit = document.getElementById("submit");
function myFunction(){
inputSubmit.style.display = "block"; };
</script>
Updated:
I've edited in order to conclude the main problem.
So what I want is this:
a) The user has pressed the first submit button "search" then it will echo on the page "first search" and then show the second submit button "search_close" .
b)Then, if the user has pressed the second submit button it will show "second search".
When first Refreshing:
======
search (button)
======
if clicking the "search" button:
======
search (button)
======
first search (text)
==================
Find close results (button)
==================
if clicking the "find close results:
======
search (button)
======
first search (text)
==================
Find close results (button)
==================
second search (text)
This code doesn't do what I want. Why?
Updated - why the button find close results disappers after one second?
<?php
session_start();
$db=mysqli_connect("localhost","root","","travelersdb");
if(#$_SESSION["username"]){
?>
<?php
// function to connect and execute the query
function filterTable($query)
{
$connect=mysqli_connect("localhost","root","","travelersdb");
$filter_Result = mysqli_query($connect, $query) or die(mysqli_error($connect));
return $filter_Result;
}
$submit_value = 0;
if(isset($_POST['search']))
{
$Destination = $_POST['Destination'];
$TypeOfTravel = $_POST['TypeOfTravel'];
$Age= $_POST['Age'];
$email = $_POST['email'];
$topic_name = $_POST['topic_name'];
$StartingPoint = $_POST['StartingPoint'];
// search in all table columns
$query = "SELECT * FROM `topics`
left join `users` on users.username = topics.topic_creator
WHERE 1=1 ";
if(!empty($Destination)) {
$query.="AND destination='$Destination'";
}
if(!empty($TypeOfTravel)) {
$query.=" AND typeTravel='$TypeOfTravel'";
}
if(!empty($Age)) {
$query.="AND age='$Age'";
}
if(!empty($email)) {
$query.=" AND email='$email'";
}
if(!empty($topic_name)) {
$query.=" AND topic_name='$topic_name'";
}
if(!empty($StartingPoint)) {
$query.=" AND StartingPoint='$StartingPoint'";
}
$search_result = filterTable($query);
$submit_value = 1;
}
///Make The search more wider, only for the fields that were in the post
else if(isset($_POST['search_close']))
{
$Destination = $_POST['Destination'];
$TypeOfTravel = $_POST['TypeOfTravel'];
$topic_name = $_POST['topic_name'];
$StartingPoint = $_POST['StartingPoint'];
// search in all table columns
$query = "SELECT * FROM `topics`
left join `users` on users.username = topics.topic_creator
WHERE 1=1 ";
if(!empty($Destination)) {
$query.="AND destination='$Destination'";
}
if(!empty($TypeOfTravel)) {
$query.=" AND typeTravel='$TypeOfTravel'";
}
if(!empty($topic_name)) {
$query.=" AND topic_name='$topic_name'";
}
if(!empty($StartingPoint)) {
$query.=" AND StartingPoint='$StartingPoint'";
}
$search_result = filterTable($query);
$submit_value = 2;
}
else {
$query = "SELECT * FROM `topics`";
$search_result = filterTable($query);
}
?>
<html>
<head>
<?php header('Content-Type: text/html; charset=utf-8'); ?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Home Page</title>
<style>
.hidden {
display: none;
}
</style>
<script type="text/javascript">
function showHide()
{
var checkbox = document.getElementById("chk");
var hiddeninputs = document.getElementsByClassName("hidden");
for (var i=0; i != hiddeninputs.length; i++) {
if(checkbox.checked){
hiddeninputs[i].style.display = "block";
} else {
hiddeninputs[i].style.display = "none";
}
}
}
<?php
if($submit_value == 1 || $submit_value == 2){ ?>
myFunction();
inputSubmit = document.getElementById("submit");
function myFunction(){
document.getElementById('submit').style.display = "block";
};
<?php } ?>
</script>
<body>
</body>
</head>
<?php include("header.php");?>
<center>
</br>
<button>Post</button>
</br>
<br/>
<h4>Simple Serach</h4>
<form action="" method="post">
<input type="text" name="Destination" placeholder="Destination" value=
"<?php if(isset($_POST['Destination']))
{echo htmlentities($_POST['Destination']);}?>" ></br>
<input type="text" name="TypeOfTravel" placeholder="Type Of Travel"
value=
"<?php if(isset($_POST['TypeOfTravel']))
{echo htmlentities($_POST['TypeOfTravel']);}?>"
></br>
<input type="text" name="Age" placeholder="Age" value="<?php if(isset($_POST['TypeOfTravel']))
{echo htmlentities($_POST['Age']);}?>">
</br>
</br>
<!-- Advanced Search-->
<input type="checkbox" name="chkbox" id="chk" onclick="showHide()" />
<label for="chk"><b>Advanced search</b></label>
</br>
<input type ="text" name="email" placeholder="Email" class="hidden" value="<?php if(isset($_POST['TypeOfTravel']))
{echo htmlentities($_POST['email']);}?>">
<input type ="text" name="topic_name" placeholder="topic name" class="hidden"value="<?php if(isset($_POST['TypeOfTravel']))
{echo htmlentities($_POST['topic_name']);}?>">
<input type="text" name="StartingPoint" placeholder="Starting Point" class="hidden"value="<?php if(isset($_POST['TypeOfTravel']))
{echo htmlentities($_POST['StartingPoint']);}?>">
</br><br/>
<input type="submit" id="button" name="search" value="Search"
onclick="myFunction();" >
<br><br>
<input type="submit" name="search_close" id="submit" style="display:
none;" value="Find close results">
</form>
<br/>
<?php echo '<table border="1px">';?>
<td width="400px;" style="text-align:center;">
Name
</td>
<td width="400px;" style="text-align:center;">
Destination
</td>
<td width="400px;" style="text-align:center;">
Type Of Travel:
</td>
<td width="80px;" style="text-align: center;">
First Name
</td>
<td width="80px;" style="text-align: center;">
Age
</td>
<td width="400px;" style="text-align:center;">
profile picture
</td>
<td width="80px;" style="text-align: center;">
Creator
</td>
<td width="80px;" style="text-align: center;">
Date
</td>
</tr>
</center>
<?php
$sql = "Select * from `topics`";
$check = mysqli_query($db,$sql);
$rows = mysqli_num_rows($search_result);
if($rows != 0){
while ($row = mysqli_fetch_assoc($search_result)){
$id = $row['topic_id'];
echo "<tr>";
//echo "<td>".$row['topic_id']."</td>";
echo "<td style='text-align:center;'><a href='topic.php?id=$id'>".$row['topic_name']."</a></td>";
echo "<td>".$row['Destination']."</td>";
echo "<td>".$row['typeTravel']."</td>";
$sql_u = "Select * from users where username='".$row['topic_creator']."'";
$check_u = mysqli_query($db,$sql_u);
while ($row_u = mysqli_fetch_assoc($check_u))
{
$user_id = $row_u['id'];
$profile_pic = $row_u['profile_pic'];
$firstname = $row_u['firstname'];
$age = $row_u['age'];
echo "<td>".$firstname."</td>";
echo "<td>".$age."</td>";
echo "<td><img src='".$profile_pic."' width='10%' height='10%' alt='me'></td>";
echo "<td><a href='profile.php?id=$user_id'>".$row['topic_creator']."</a></td>";
}
$get_date = $row['date'];
echo "<td>".$row['date']."</td>";
echo "</tr>";
}
}else {
echo "No topics found";
}
echo "</table>";
if (#$_GET['action']=="logout")
{
session_destroy();
header('location:login.php');
}
}else
{
echo "You must be logged in.";
echo "<a href ='login.php'>Click here to login</a>";
}
?>
</br>
</br>
<body>
</body>
</html>
you need to set type button cause when you set type submit then form automatically submit so show second not show but it work.
<form method="post" action = "">
<input type="submit" id="button" name="search" value="Search" >
<br>
<input type="submit" name="search_close" id="submit" style="display:
none;" value="Find close results">
</form>
<?php
$submit_value = 0;
if(isset($_POST['search']))
{
echo "first search";
$submit_value = 1;
}
else if(isset($_POST['search_close']))
{
echo "first search";
echo '<br>';
echo "second search";
$submit_value = 2;
}
else {
echo "nothing";
}
?>
<script type="text/javascript">
<?php
if($submit_value == 1 || $submit_value == 2){ ?>
document.getElementById('submit').style.display = "block";
<?php } ?>
</script>
check this code
I have cleaned up your code, but the issue of having two submit buttons still persists. Even if the clicking of the first button causes the second to show, the first button will cause the page to reload with the results from the form's action resource. In this example, I have cancelled the form's submit event to show that the display of the second button works.
In the end, I think you are going about this all wrong. I think you should be making AJAX calls to your server-side resource and injecting the results of that call into your page - - no forms and no submits.
// Don't forget to add "var" to your variable declarations, otherwise the variables
// become global!
var sub1 = document.getElementById("btnSub1");
var sub2 = document.getElementById("btnSub2");
// Set up the event handler for the first button
sub1.addEventListener("click", myFunction);
function myFunction(e){
// Adjust classes, not individual styles
sub2.classList.remove("hidden");
// Cancel the native event and stop bubbling
e.preventDefault();
e.stopPropagation();
};
.hidden { display:none; }
<form>
<!-- Submit buttons don't get a name attriute unless you expect their value to be submitted
along with all the other form data. Inline styles should be avoided and internal style
sheets used instead. And, inline JavaScript event attributes (onclick, etc.) should not
be used. -->
<input type="submit" id="btnSub1" name="search" value="Search" >
<br>
<input type="submit" id="btnSub2" class="hidden" value="Find close results">
</form>
<?php
if(isset($_POST['search']))
{
echo "first search";
}
else if(isset($_POST['search_close']))
{
echo "second search";
}
else {
echo "nothing";
}
?>

how to make my page auto submit?

I have one payment page where payment values will fill automatically . so i don't want allow that page to user to submit . how can i do auto submit of my page ?
my code is
include "configaration/config.php";
// Merchant key here as provided by Payu
$MERCHANT_KEY = "4LbrUG";
// Merchant Salt as provided by Payu
$SALT = "EhDp06FA";
// End point - change to https://secure.payu.in for LIVE mode
$PAYU_BASE_URL = "https://test.payu.in";
$sucess_url = 'http://localhost/georamble/success.php';
$failur_url = 'http://localhost/georamble/failure.php';
$action = '';
$posted = array();
if(!empty($_POST)) {
foreach($_POST as $key => $value) {
$posted[$key] = $value;
}
}
$formError = 0;
if(empty($posted['txnid'])) {
// Generate random transaction id
$txnid = substr(hash('sha256', mt_rand() . microtime()), 0, 20);
} else {
$txnid = $posted['txnid'];
}
$hash = '';
// Hash Sequence
$hashSequence = "key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5|udf6|udf7|udf8|udf9|udf10";
if(empty($posted['hash']) && sizeof($posted) > 0) {
if(
empty($posted['key'])
|| empty($posted['txnid'])
|| empty($posted['amount'])
|| empty($posted['firstname'])
|| empty($posted['email'])
|| empty($posted['phone'])
|| empty($posted['productinfo'])
|| empty($posted['surl'])
|| empty($posted['furl'])
|| empty($posted['service_provider'])
) {
$formError = 1;
} else {
//$posted['productinfo'] = json_encode(json_decode('[{"name":"tutionfee","description":"","value":"500","isRequired":"false"},{"name":"developmentfee","description":"monthly tution fee","value":"1500","isRequired":"false"}]'));
$hashVarsSeq = explode('|', $hashSequence);
$hash_string = '';
foreach($hashVarsSeq as $hash_var) {
$hash_string .= isset($posted[$hash_var]) ? $posted[$hash_var] : '';
$hash_string .= '|';
}
$hash_string .= $SALT;
$hash = strtolower(hash('sha512', $hash_string));
$action = $PAYU_BASE_URL . '/_payment';
}
} elseif(!empty($posted['hash'])) {
$hash = $posted['hash'];
$action = $PAYU_BASE_URL . '/_payment';
}
//data from previous page
if(isset($_POST['submit1']))
{
$packname = $_POST['pname'];
$package_price = $_POST['advn_pay'];
$person = $_POST['person'];
$date = $_POST['date'];
$date = date('Y-m-d', strtotime($date));
$package_id = $_POST['pkid'];
$wallet_amount = $_POST['wallet_amount'];
$wallet_amount_use = 0;
if(isset($_POST['wuamount']))
{
$wallet_amount_use = $_POST['wuamount'];
}
$ref_no =rand(20,10000000);
$pay_status = "unpaid";
$req_status = "requested";
$wallet_update_money= $wallet_amount - $wallet_amount_use;
$update= mysql_query("UPDATE wallet SET amount='$wallet_update_money' WHERE user_id='$login_session'");
//fetch a user name
$query = mysql_query("select * from user where user_id= '$login_session'");
if(!$query)
{
echo "error";
}
while($row=mysql_fetch_array($query))
{
$name = $row['first_name'];
$email = $row['email'];
$contact_number = $row['contact_number'];
}
$p_name=$_POST['name'];
$age=$_POST['age'];
for($i=0;$i<count($p_name);$i++)
{
$qry_add="INSERT INTO trvel_person_details (ref_user_id,ref_cus_name,cus_name,cus_age,travel_date)
VALUES ('$login_session', '$name','$p_name[$i] ','$age[$i]','$date')";
if(!mysql_query($qry_add))
{
die('Error: ' . mysql_error());
}
}
$total_amount= $package_price - $wallet_amount_use ; //total amount
$qry="INSERT INTO pack_req (user_id,user_name,package_id,pacakage_name,amount,date_jrny,no_person,refrence_number,payment_status,req_status)
VALUES ('$login_session', '$name','$package_id ','$packname','$total_amount','$date ','$person','$ref_no','$pay_status ','$req_status')";
if(!mysql_query($qry))
{
die('Error: ' . mysql_error());
}
}
?>
<html>
<head>
<script>
var hash = '<?php echo $hash ?>';
function submitPayuForm() {
if(hash == '') {
return;
}
var payuForm = document.forms.payuForm;
payuForm.submit();
}
</script>
</head>
<body onload="submitPayuForm()">
<h2>PayU Form</h2>
<br/>
<?php if($formError) { ?>
<span style="color:red">Please fill all mandatory fields.</span>
<br/>
<br/>
<?php } ?>
<form action="<?php echo $action; ?>" method="post" id="payuForm" name="payuForm">
<input type="hidden" name="key" value="<?php echo $MERCHANT_KEY ?>" />
<input type="hidden" name="hash" value="<?php echo $hash ?>"/>
<input type="hidden" name="txnid" value="<?php echo $txnid ?>" />
<table>
<tr>
<td><b>Mandatory Parameters</b></td>
</tr>
<tr>
<td>Amount: </td>
<td><input name="amount" id="amount" value="<?php echo (empty($posted['amount'])) ? $total_amount : $posted['amount']; ?>" /></td>
<td>First Name: </td>
<td><input name="firstname" id="firstname" value="<?php echo (empty($posted['firstname'])) ? $name : $posted['firstname']; ?>" /></td>
</tr>
<tr>
<td>Email: </td>
<td><input name="email" id="email" value="<?php echo (empty($posted['email'])) ? $email : $posted['email']; ?>" /></td>
<td>Phone: </td>
<td><input name="phone" value="<?php echo (empty($posted['phone'])) ? $contact_number : $posted['phone']; ?>" /></td>
<td>transation Id: </td>
<td><input name="txnid" value="<?php echo (empty($posted['txnid'])) ? $ref_no : $posted['txnid']; ?>" /></td>
</tr>
<tr>
<td>Product Info: </td>
<td colspan="3"><textarea name="productinfo"><?php echo (empty($posted['productinfo'])) ? $packname : $posted['productinfo'] ?></textarea></td>
</tr>
<tr>
<td>Success URI: </td>
<td colspan="3"><input name="surl" value="<?php echo (empty($posted['surl'])) ? $sucess_url : $posted['surl'] ?>" size="64" /></td>
</tr>
<tr>
<td>Failure URI: </td>
<td colspan="3"><input name="furl" value="<?php echo (empty($posted['furl'])) ? $failur_url : $posted['furl'] ?>" size="64" /></td>
</tr>
<tr>
<td colspan="3"><input type="hidden" name="service_provider" value="payu_paisa" size="64" /></td>
</tr>
<?php if(!$hash) { ?>
<td colspan="4"><input type="submit" value="Submit" /></td>
<?php } ?>
</tr>
</table>
</form>
even i have tried with one javascript to auto submit the form
<script type="text/javascript">
$(document).ready(function(){
$("#payuForm").submit();
});
</script>
but still its not redirecting . how can do this . any hint or help . sorry for my bad english
Create a hidden submit type button(i.e. display:none;), after page load through jquery click on it automatically(i.e. $('#submit').click() ), Create a function for clicking on submit button, call it after page loads...
EDIT:
HTML:
<form ...>
...
<input type="submit" id="submit" style="display:none;" />
</form>
Javascript:
function submit_click(){
$("#submit").click();
}
Now, when your auto form populating data's function called, call this function in last line submit_click();
try this
<script>
$(document).ready(function(){
$('#payuForm').trigger('submit');
})
</script>
Remember that some browser do not let you trigger the "submit" event if you have not an ENABLED submit button (be it an input or button, with type="submit")
Thus, you need to a button in the form, and if you don't want it to be shown, you can add
#button {
display: none;
visibility: hidden;
}

I need help to making automatic submit quiz using timer

Hello guys i have a quiz system and i want that quiz will auto submit after the time is over this is my code but its not working.
<script type="text/javascript">
function countDown(secs, elem)
{
var element = document.getElementById(elem);
element.innerHTML = "<h2>You have <b>"+secs+"</b> seconds to answer the questions</h2>";
if(secs < 1) {
document.quiz.submit();
}
else
{
secs--;
setTimeout('countDown('+secs+',"'+elem+'")',1500);
}
}
function validate() {
return true;
}
</script>
<div id="status"></div>
<script type="text/javascript">countDown(4,"status");</script>
<title>Questionnaire</title>
<style type="text/css">
span {
color: #FF00CC;
}
</style>
<body>
<br />
<div class="col-sm-8">
<div class="panel panel-black">
<?php
include("db_conn.php");
$query="select * from question";
$rs=mysql_query("select * from question where test_id=$tid",$cn) or die(mysql_error());
if(!isset($_SESSION[qn]))
{
$_SESSION[qn]=0;
mysql_query("delete from useranswer where sess_id='" . session_id() ."'") or die(mysql_error());
$_SESSION[trueans]=0;
}
else
{
if($submit=='Next Question' && isset($ans))
{
mysql_data_seek($rs,$_SESSION[qn]);
$row= mysql_fetch_row($rs);
mysql_query("insert into useranswer(sess_id, test_id, que_des, ans1,ans2,ans3,ans4,true_ans,your_ans) values ('".session_id()."', $tid,'$row[2]','$row[3]','$row[4]','$row[5]', '$row[6]','$row[7]','$ans')") or die(mysql_error());
if($ans==$row[7])
{
$_SESSION[trueans]=$_SESSION[trueans]+1;
}
$_SESSION[qn]=$_SESSION[qn]+1;
}
else if($submit=='Get Result' && isset($ans))
{
mysql_data_seek($rs,$_SESSION[qn]);
$row= mysql_fetch_row($rs);
mysql_query("insert into useranswer(sess_id, test_id, que_des, ans1,ans2,ans3,ans4,true_ans,your_ans) values ('".session_id()."', $tid,'$row[2]','$row[3]','$row[4]','$row[5]', '$row[6]','$row[7]','$ans')") or die(mysql_error());
if($ans==$row[7])
{
$_SESSION[trueans]=$_SESSION[trueans]+1;
}
echo "<h1 class=head1> Result</h1>";
$_SESSION[qn]=$_SESSION[qn]+1;
echo "<Table align=center><tr class=tot><td>Total Question<td> $_SESSION[qn]";
echo "<tr class=tans><td>True Answer<td>".$_SESSION[trueans];
$w=$_SESSION[qn]-$_SESSION[trueans];
echo "<tr class=fans><td>Wrong Answer<td> ". $w;
echo "</table>";
mysql_query("insert into result(login,test_id,test_date,score) values('$login',$tid,'".date("d/m/Y")."',$_SESSION[trueans])") or die(mysql_error());
unset($_SESSION[qn]);
unset($_SESSION[sid]);
unset($_SESSION[tid]);
unset($_SESSION[trueans]);
exit;
}
}
$rs=mysql_query("select * from question where test_id=$tid",$cn) or die(mysql_error());
if($_SESSION[qn]>mysql_num_rows($rs)-1)
{
unset($_SESSION[qn]);
echo "<h1 class=head1>Some Error Occured</h1>";
session_destroy();
echo "Please <a href=test.php> Start Again</a>";
exit;
}
mysql_data_seek($rs,$_SESSION[qn]);
$row= mysql_fetch_row($rs);
echo "<form name=quiz method=post action=quiz.php onsubmit=return validate()>";
echo "<table width=100%> <tr> <td width=30> <td> <table border=0>";
$n=$_SESSION[qn]+1;
echo "<tR><td><span class=style2>Que ". $n .": $row[2]</style>";
echo "<tr><td class=style8><input type=radio name=ans value=1>$row[3]";
echo "<tr><td class=style8> <input type=radio name=ans value=2>$row[4]";
echo "<tr><td class=style8><input type=radio name=ans value=3>$row[5]";
echo "<tr><td class=style8><input type=radio name=ans value=4>$row[6]";
if($_SESSION[qn]<mysql_num_rows($rs)-1)
echo "<tr><td><input type=submit name=submit class='btn btn-lg btn-black' value='Next Question'></form>";
else
echo "<tr><td><input type=submit name=submit class='btn btn-lg btn-black' value='Get Result'></form>";
echo "</table></table>";
?>
</div>
</div>
This code i am using guys but problem is that the auto timer not submitting the quiz after over
Use setInterval instead of setTimeout. Because if you use setTimeout your countDown function will fire just one time.
setInterval(function() {
countDown(secs, elem)
},1500);

javascript function to allow to add only 12 characters

I have a php code with javascript function. the script is having "Add more" button, if we click on this button it will add one more row having 2 text box named "Pront ID:" and "Pronto Title:". the script is working fine. but i need the script that it should allow me to enter exact 12 characters to "Pronto ID" field. if it's more than/less than 12 characters, it should echo message to add exact 12 characters.
in HTML code we can use "pattern="\w{12}" title="Enter 12 characters" " line to echo "Enter 12 characters" but i need this in inside javascript function"add".
Please help me on this.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="./jquery-1.7.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.del').live('click',function(){
$(this).parent().parent().remove();
});
$('.add').live('click',function(){
var i = 1;
var appendTxt = "<tr><td>Pront ID:</td><td><input type='text' name='input_box_one[]' pattern='\w{12}' title='Enter 12 characters'></td><td>Pronto Title:</td> <td><input type='text' name='input_box_two[]' /></td> <td><input type='button' class='del' value='Delete' /></td></tr>";
$("tr:last").before(appendTxt);
var inputs = document.getElementsByTagName('input').length;
//alert(inputs);
if(inputs == 18){
document.getElementById("countButton").disabled = true;
}
$i++
});
});
</script>
</head>
<body>
<form name="form1" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<table id="options-table">
<tr>
<td>Pront ID:</td><td><input type="text" name="input_box_one[]" pattern="\w{12}" title="Enter 12 characters" /></td>
<td>Pronto Title:</td><td><input type="text" name="input_box_two[]" /></td>
<td><input type="button" class='del' value='Delete' /></td>
<input type="hidden" name="count" value="<?php $i; ?>">
</tr>
<?php
echo "<tr><td><input id=\"countButton\" type=\"button\" class=\"add\" value=\"Add More\"/></td><td><input type=\"submit\" name=\"submit\" value=\"submit\"></td></tr>";
?>
</table>
</form>
</body>
</html>
<?php
foreach ($_POST['input_box_one'] as $v) {
echo $v;
echo "\n";
}
foreach ($_POST['input_box_two'] as $p) {
echo $p . "\n";
}
?>

Categories