<?php
//include the DB connection
include("includes/config.php");
//include the header
include("includes/header.php");
?>
<?php
//checks if the form was submitted
if(isset($_POST['submit']))
{
//get form values when submitted
$name=$_POST['name'];
$email=$_POST['email'];
$phone=$_POST['phone'];
$password=$_POST['password'];
$subject=$_POST['subject'];
$target_dir = "uploads/";
$target_file = $target_dir . time() . basename($_FILES["file"]["name"]);
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file))
{
mysql_query("INSERT INTO `login`(`name`,`email`,`phone`,`password`,`file`,`subject`)VALUES('$name','$email','$phone','$password',
'$target_file','$subject')");
echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";
}
else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
<div class="form">
<form action="" method="post" name="registration" enctype="multipart/form-data" onSubmit="return formValidation();">
<table width="500" border="1" cellspacing="0" cellpadding="0" class="table">
<tr>
<td>Name</td>
<td><input name="name" type="text" class="input" placeholder="Please Enter Your Name" value="<?php //echo $userName ;?>" /></td>
</tr>
<tr>
<td>Email</td>
<td><input name="email" type="email" class="input" placeholder="Please Enter Your Email ID "value=" <?php //echo $userEmail ;?>" /></td>
</tr>
<tr>
<td>Phone</td>
<td><input name="phone" type="text" class="input" placeholder="Please Enter Your Phone Number" value="<?php //echo $userPhone;?>" /></td>
</tr>
<tr>
<td>Password</td>
<td><input name="password" type="password" class="input" value="" /></td>
</tr>
<tr>
<td>Upload file</td>
<td><input name="file" type="file" class="input" value="" </td>
</tr>
<tr>
<td>Subject</td>
<td><textarea name="subject" cols="" rows="" class="input" placeholder="Please Enter Your Query "/> <?php //echo $userSubject;?></textarea></td>
</tr>
<tr>
<td></td>
<td><input name="submit" type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</div>
<?php
//include the footer
include("includes/footer.php");
?>
<script type="text/javascript">
function formValidation()
{
var uname = document.registration.name;
var uphone= document.registration.phone;
if(allLetter(uname))
{
if(phonenumber(uphone))
{
}
}
return false;
}
function allLetter(uname)
{
var letters = /^[A-Za-z]+$/;
if(uname.value.match(letters))
{
return true;
}
else
{
alert('Username must have alphabet characters only');
uname.focus();
return false;
}
}
function phonenumber(inputtxt)
{
var phoneno = /^\d{10}$/;
if((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}
</script>
for the user name the code for validation works but for the phone validation it's not working,i want phone validation for empty field check and format check and email check.help me out as i'm new to javascript
Try this code.
function formValidation()
{
var phone=document.forms["registration"]["phone"].value;
var phone_num = /^\d{10}$/;
if (phone=="")
{
alert("enter your phone number");
return false;
}
else if(phone)
{
if(!phone_num.test(phone))
{
alert("Not a valid Phone Number");
return false;
}
}
var email = document.forms["registration"]["email"].value;
if (email=="")
{
alert("enter your email id");
return false;
}
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length)
{
alert("Not a valid e-mail address");
return false;
}
}
you have a typo in your phone function an extra (:
try:
if(inputtxt.value.match(phoneno))
instead of if((inputtxt.value.match(phoneno))
PS: Tip do look and use console tools while working with JS
Related
I have an html form with three input fields which I increment dynamically with javascript. I have to parse the data to PHP which I have done but I can't access the data and insert it into the database as this is an array data. I have tried but it's not working.
Here is my code:
html and Javascript
<body>
<div class="container">
<div class="form-group">
<form name="add_name" id="add_name">
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" /></td>
<td><input type="text" name="othername[]" placeholder="Enter your Name" class="form-control name_list" /></td>
<td><input type="text" name="lastName[]" placeholder="Enter your Name" class="form-control name_last" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
</tr>
</table>
<input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
</form>
</div>
</div>
</body>
<script>
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" /></td><td><input type="text" name="otherName[]" placeholder="Enter your Name" class="form-control name_last" /></td><td><input type="text" name="lastName[]" placeholder="Enter your Name" class="form-control name_last" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
$('#submit').click(function(){
$.ajax({
url:"name.php",
method:"POST",
data:$('#add_name').serialize(),
success:function(data)
{
alert(data);
$('#add_name')[0].reset();
}
});
});
});
</script>
PHP
<?php
$connect = mysqli_connect("localhost", "root", "", "testing");
$number = count($_POST["name"]);
$numberx = count($_POST["othername"]);
$numbers = count($_POST["lastname"]);
if($number > 1 && $numbers > 1){
for(($i=0; $i<$number; $i++) && ($x=0; $x<$numberx; $x++) && ($w=0; $w<$numbers; $w++)){
if(trim($_POST["name"][$i] != '') && trim($_POST["othername"][$x] != '') &&
trim($_POST["lastname"][$w] != '')){
$namex = mysqli_real_escape_string($connect, $_POST["name"][$i]);
$othernamex = mysqli_real_escape_string($connect, $_POST["othername"][$x]);
$lastnamex = mysqli_real_escape_string($connect, $_POST["lastname"][$w]);
$check = "INSERT INTO bl_name (name, othername, lastname) VALUES ('$namex', '$othernamex', '$lastnamex')";
mysqli_query($connect, $check);
}
}
echo "Data Inserted";
}
else
{
echo "Please Enter Name";
}
I need help as I have been on this for two days now. Is there any way I can do this?
Simplify your input names, change them to:
user[][name]
user[][othername]
user[][lastname]
Run a simple foreach() loop on $_POST['user']:
foreach($_POST['user'] as $user){
$namex = mysqli_real_escape_string($connect, $user["name"]);
$othernamex = mysqli_real_escape_string($connect, $user["othername"]);
$lastnamex = mysqli_real_escape_string($connect, $user["lastname"]);
$check = "INSERT INTO bl_name (name, othername, lastname) VALUES ('{$namex}', '{$othernamex}', '{$lastnamex}')";
mysqli_query($connect, $check);
}
Keep in mind that form field names are case sensitive. You're also not testing if the mysqli_query() function returns successfully. You should probably do that. And yes, prepared statements are safer.
Trying to get my customer registration page for a hotel database to validate the input with javascript then php, and update the database with the new customers info and redirect them to the correct login page (customerlogin).
When i click submit, state, telephone, country, suburb, title go blank and the other feilds remain with the info entered.
Please help thanks
<?php
require_once("dbconn.php");
$username = $pwrd = $repwrd = $gname = $sname = $addr = $suburb = $state = $ptcode = $mobile = $email = "";
$usernameErr = $pwrdErr = $repwrdErr = $gnameErr = $snameErr = $addrErr = $suburbErr = $stateErr = $ptcodeErr = $mobileErr = $emailErr = "";
//when the form is being submitted
if (isset($_POST["submit"]))
{
$username = mysqli_real_escape_string($dbConn, $_POST["uname"]);
if (empty($username))
$usernameErr = '<span class="error">Please enter a Unique ID</span>';
else {
$Npattern = "/^[a-zA-Z0-9]{1,20}+$/";
if (!preg_match($Npattern, $username))
{
$usernameErr = '<span class="error">Username already exists!</span>';
}
}
$pwrd = mysqli_real_escape_string($dbConn, $_POST["pword"]);
if (empty($pwrd))
$pwrdErr = '<span class="error">Please enter a password</span>';
else {
$PWpattern = "/^[a-zA-Z0-9]{6,20}+$/";
if ( !preg_match($PWpattern, $pwrd))
{
$pwrdErr = '<span class="error">Password must be minimum of 6 characters</span>';
}
}
$repwrd = mysqli_real_escape_string($dbConn, $_POST["pword2"]);
if ( empty($repwrd))
$repwrdErr = '<span class="error">Please ensure passwords match</span>';
else {
$pwrd = mysqli_real_escape_string($dbConn, $_POST["pword"]);
if (! $repwrd == $pwrd )
{
$repwrdErr = '<span class="error">Passwords do not match</span>';
}
}
$gname = mysqli_real_escape_string($dbConn, $_POST["FName"]);
if (empty($gname))
$gnameErr = '<span class="error">Please enter your First Name</span>';
else {
$Gpattern = "/^[a-zA-Z .\-]{1,20}+$/";
if ( !preg_match($Gpattern, $gname))
{
$gnameErr = '<span class="error">First Name can only contain alphabetical letters, spaces, hyphens and apostrophe';
$gnameErr .= 'it also must not exceed 20 characters</span>';
}
}
$sname = mysqli_real_escape_string($dbConn, $_POST["LName"]);
if (empty($sname))
$snameErr = '<span class="error">Please enter Last Name</span>';
else {
$Fpattern = "/^[a-zA-Z .\-]{1,20}+$/";
if ( !preg_match($Fpattern, $sname))
{
$snameErr = '<span class="error">Family Name can only contain alphabetical letters, spaces, hyphens and apostrophe';
$snameErr .= 'it also must not exceed 20 characters</span>';
}
}
$addr = mysqli_real_escape_string($dbConn, $_POST["add"]);
if (empty($addr))
$addrErr = '<span class="error">Please enter Address</span>';
else {
if (strlen($addr) > 40 )
{
$addrErr = '<span class="error">Your Address must not exceed 40 characters long </span>';
}
}
$state = mysqli_real_escape_string($dbConn, $_POST["state"]);
if ($state == "--" )
$stateErr = '<span class="error"> Please enter state</span>';
$ptcode = mysqli_real_escape_string($dbConn, $_POST["pcode"]);
if (empty($ptcode))
$ptcodeErr = '<span class="error">Please enter postcode</span>';
else {
$pcPattern = "/^[0-9]{4}$/";
if (!preg_match($pcPattern,$ptcode))
$ptcodeErr = '<span class="error">Postcode must be 4 digits</span>';
}
$mobile = mysqli_real_escape_string($dbConn, $_POST["mobile"]);
if (empty($mobile))
$mobileErr = '<span class="error">Please enter mobile number</span>';
else {
$Mobilepattern = "/^04?\d{8}$/";
if (!preg_match($Mobilepattern, $mobile))
$mobileErr = '<span class="error">Mobile number must be 10 digits</span>';
}
$email = mysqli_real_escape_string($dbConn, $_POST["email"]);
if (empty($email))
$emailErr = '<span class="error">Please Enter email address</span>';
else {
if ( filter_var($email,FILTER_VALIDATE_EMAIL))
{
$emailErr = '<span class="error">Email not Valid</span>';
}
}
}
else if (isset($_POST["reset"]))
{
unset($_POST["username"]);
unset($_POST["password"]);
unset($_POST["repassword"]);
unset($_POST["gname"]);
unset($_POST["sname"]);
unset($_POST["address"]);
unset($_POST["state"]);
unset($_POST["postcode"]);
unset($_POST["mobile"]);
unset($_POST["email"]);
unset($_POST[""]);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Registration Form</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<script type="text/javascript" language="javascript" >
function validateUsername(uname)
{
var uname = document.getElementById("uname").value;
if (uname.length < 21) {
return true;
} else {
Alert("Please choose a username with a max of 20 characters");
return false;
}
}
function validatePword(input)
{
var pword = document.getElementById("pword").value;
if (pword.length > 6) {
return true;
}
else
{
alert("Please choose a Password between 6 and 20 characters");
return false;
}
if (pword.length < 20) {
return true;
} else {
alert("Please choose a Password between 6 and 20 characters");
}
}
function confirmPword(input)
{
var pword = document.getElementById("pword").value;
var pword2 = document.getElementById("pword2").value;
if (pword2 == pword){
return true;
}
else
{
alert("Passwords do not match, please retype password in both feilds.");
}
}
function validateName(txt) {
var letters = /^[A-Za-z-']+$/;
if (txt.value.match(letters)) {
return true;
} else {
alert("Invalid Characters Entered for Name")
return false;
}
}
function validateAdd(input) {
var add = document.getElementById("add").value;
if (add.length < 41) {
return true;
} else {
alert("Address must not be more then 40 characters");
}
}
function validatePcode(input) {
var pcode = document.getElementById("pcode").value;
var numbers = "123456789";
if (pcode.length < 4) {
alert("Postcode must be 4 digits")
}
else {
if (pcode.value.match(numbers)){
return true;
}
}
}
function validatePhone(input) {
var phoneNo = /^\d{10}$/;
if (input.value.match(phoneNo)) {
return true;
} else {
alert("Phone number must be in the format of 04xxxxxxxx");
}
}
function validateEmail(input) {
var email = input.value;
if (email.indexOf("#") > -1 && email.indexOf(".") > -1) {
return true;
} else {
alert("Please enter a valid email address");
return false;
}
}
</script>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>
<body>
<form id="regForm" name="regForm" action="<?php echo htmlspecialchars ($_SERVER["PHP_SELF"]); ?>" method="post" onsubmit="return confirmPword();">
<div id="header">
<h1>Western Sydney Hotel</h1>
</div>
<h1>Register as a User</h1>
<p> Please fill out the form below to register for the hotel website. </p>
<hr>
<h2>Account Details</h2>
<b>Username</b>
<input type= "text" name="uname" id="uname" size="20" maxlength="20" onblur="validateUsername(this);" value="<?php echo htmlspecialchars($username); ?>">
<br><br>
<b>Password</b>
<input type= "password" name="pword" id="pword" size="20" maxlength="20" min="6" onblur="validatePword(this);" value="<?php echo htmlspecialchars($pwrd); ?>">
<b>Retype password</b>
<input type= "password" name="pword2" id="pword2" size="20" maxlength="20" min="6" value="<?php echo htmlspecialchars($repwrd); ?>">
<br>
<hr>
<h2>Personal Details</h2>
<p>
<b>Title:</b>
<br>
<select name="Title" required>
<option value=" "></option>
<option value="Dr">Dr</option>
<option value="Mr">Mr</option>
<option value="Mrs">Mrs</option>
<option value="Ms">Ms</option>
<option value="Miss">Miss</option>
</select>
</p>
<p><b>First Name:</b><br> <input type= "text" name="FName" id="FName" size="20" maxlength="20" onblur="validateName(this);" value="<?php echo htmlspecialchars($gname); ?>" /></p>
<p><b>Family Name:</b><br> <input type="text" name="LName" id="LName" size="20" maxlength="20" onblur="validateName(this);" value="<?php echo htmlspecialchars($sname); ?>" /></p>
<hr>
<h2>Contact Details</h2>
<p><b>Street Address:</b><br> <input type="Text" Name="add" id="add" size="40" maxlength="40" onblur="validateAdd(this);" value="<?php echo htmlspecialchars($addr); ?>" /></p>
<p><b>Suburb:</b><br> <input type="text" name ="Suburb" value="<?php echo htmlspecialchars($suburb); ?>" /></p>
<p><b>State:</b><br> <select name ="state" id="state" value="<?php echo htmlspecialchars($state); ?>" >
<option value=" "> </option>
<option value="nsw"> NSW </option>
<option value="wa"> WA </option>
<option value="sa"> SA </option>
<option value="vic"> VIC </option>
<option value="qld"> QLD </option>
<option value="nt"> NT </option>
<option value="act"> ACT </option>
</p>
</select>
<br>
<p><b>Country:</b><br> <input type="text" name ="country" /></p>
<p><b>Postcode:</b> <br><input type="Text" size="4" maxlength="4" name="pcode" id="pcode" onblur="validatePostcode(this);" value="<?php echo htmlspecialchars($ptcode); ?>"/> </p>
<p><b>Telephone:</b><br> <input type="Tel" name="Telephone" /></p>
<p><b>Mobile:</b><br> <input type="text" name="mobile" id="mobile" onblur="validatePhone(this);" value="<?php echo htmlspecialchars($mobile); ?>" /></p>
<p><b>Email:</b><br> <input type="Email" name="email" maxlength="40" onblur="validateEmail(this);" value="<?php echo htmlspecialchars($email); ?>" /></p>
<br>
<hr>
<input type="Submit" name="submit" value="Submit"/>
<input type="Reset" name ="reset" value="Reset"/>
<br>
<br>
<div id="footer">
Copyright © Western Sydney Hotels
</div>
</form>
<?php
require_once("dbconn.php");
if (isset($_POST["submit"]) && strlen($usernameErr)==0 && strlen($pwrdErr)==0 && strlen($repwrdErr)==0 && strlen($gnameErr)==0 && strlen($snameErr)==0
&& strlen($addrErr)==0 && strlen($stateErr)==0 && strlen($ptcodeErr)==0 && strlen($mobileErr)==0 && strlen($emailErr)==0)
{
$sql = "INSERT INTO customers(username, password, gname, sname, address, state, postcode, mobile, email)
VALUES ('$username', '$pwrd', '$gname', '$sname', '$addr', '$state', '$ptcode', '$mobile', '$email')";
if (mysqli_query($dbConn, $sql))
{
echo "Registration for Western Sydney Hotels complete";
header("location: customerlogin.php");
}
else {
echo "Error: " . $sql . "<br>" . mysqli_error($dbConn);
}
}
mysqli_close($dbConn);
die();
?>
</body>
</HTML>
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 am trying to display a table from my PHP file on a web page which is the index.html file using ajax. I am new to PHP and ajax so I currently do not know what is wrong with the codes. However what I do know is that there data is not getting through this line in the javascript file.
document.getElementById("divTable").innerHTML=xmlhttp.responseText;
It works without ajax but of course I do need to go to database.php to display the table. I want it to display on index.html. Also, will my delete button in my PHP file still work?
P.S. I'm using vi editor as I'm currently coding this on a server. However it's just to test out. I am new to server stuff, ajax and PHP so do pardon my mistakes if any. And ignore the table formatting in my HTML file.
P.P.S I do not know any form of jQuery and what I have written is my current knowledge of AJAX.
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css"/>
<script src="function.js" type="text/javascript"></script>
</head>
<body>
<form name="infoForm" method="post" onsubmit="return checkFields()" action="">
<table>
<tr>
<td>Name:</td>
<td><input type="text" name="name" id="name" maxlength="40"></td>
</tr>
<tr>
<td>Address:</td>
<td><textarea maxlength="45" name="address"id="address" ></textarea></td>
</tr>
<tr>
<td>Phone:</td>
<td><input type="text" name="phone" id="phone" maxlength="20"><br></td>
</tr>
<tr>
<td>Gender:</td>
<td><input checked type="radio" name="gender" id="male" value="Male">Male
<input type="radio" name="gender" id="female" value="Female">Female</td>
</tr>
<tr>
<td>
Nationality:
</td>
<td>
<select name="nation">
<option value="Singapore">Singapore</option>
<option value="Malaysia">Malaysia</option>
<option value="Thailand">Thailand</option>
<option value="Indoensia">Indonesia</option>
<option value="Philippines">Philippines</option>
</select>
</td>
</tr>
<tr>
<td></td>
<td>
<br><input type="reset" value="Cancel">
<input type="submit" name="result" value="Submit" onclick="checkFields()"/>
</td>
</tr>
</table>
</form>
<div id="divTable"></div>
</body>
</html>
This is my javascript file, function.js:
function checkFields(){
var name = document.getElementById("name");
var address = document.getElementById("address");
var phone = document.getElementById("Phone");
if(confirm('Do you want to submit')){
if(name == null, name == ""||address == null, address == ""||phone == null, phone == ""){
alert("Please fill in all your details.");
return false;
}
else{
var page = "database.php";
var xmlhttp = new XMLHttpRequest();
if(xmlhttp==null){
alert("Your browser does not support AJAX!");
return false;
}
xmlhttp.onreadystatechange=function(){
document.getElementById("divTable").innerHTML=xmlhttp.responseText;
}
xmlhttp.open("GET", page, true);
xmlhttp.send(null);
}
}
else{
return false;
}
}
This is my PHP file, database.php:
<?php
// Define database parameters //
DEFINE ('DB_USER' ,'iqwer222');
DEFINE ('DB_PASSWORD', 'wfwqr');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'aqwfvaqf');
$table_info = "info";
// Connect to database
$conn = #mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) OR die ('Could not connect to Database:'. mysql_error());
#mysql_select_db (DB_NAME) OR die ('Could not select the Database: '.mysql_error());
// Delete Row
if(isset($_POST['delete'])){
$id = $_POST['deleteRow'];
$query_string = "delete from $table_info where user_id='$id'";
$result = #mysql_query($query_string);
}
//Check if phone no. is duplicate and if not, insert data
if(isset($_POST['result'])){
$phone = $_POST['phone'];
$query_string = "select phone from $table_info where phone='$phone'";
$result = #mysql_query($query_string);
$num_row = mysql_num_rows($result);
if($num_row){
echo "A same phone number has been found. Please enter a different phone number.";
}else{
$query_string = "insert into $table_info(name, address, phone, gender, nation) values('".$_POST['name']."','".$_POST['address']."','".$_POST['phone']."','".$_POST['gender']."','".$_POST['nation']."')";
$result = #mysql_query($query_string);
}
}
// Display table
$query_string = "select * from $table_info";
$result = #mysql_query($query_string);
$num_row = mysql_num_rows($result);
if($num_row){
echo "<table border=1>";
echo "<tr><th>Name</th><th>Address</th><th>Phone no.</th><th>Gender</th><th>Nationality</th><th>Created</th><th>Modified</th><th>Action</th></tr>";
while($row = mysql_fetch_array($result)){
echo "<tr><td>", $row['name'], "</td>";
echo "<td>", $row['address'], "</td>";
echo "<td>", $row['phone'], "</td>";
echo "<td>", $row['gender'], "</td>";
echo "<td>", $row['nation'], "</td>";
echo "<td>", $row['createdTime'], "</td>";
echo "<td>", $row['modifiedTime'], "</td>";
?>
<!--Delete button-->
<td><form id="delete" method="post" action="">
<input type="hidden" name="deleteRow" value="<?php echo $row['user_id'] ?>"/>
<input type="submit" name="delete" value="Delete" onclick="return confirm('Are you sure you want to delete this contact?')"/></td></form></tr>
<?php
}
echo "</table>";
}
else{
echo "0 results";
}
?>
<form method="post" action="index.html">
<input type="submit" name="goBack" value="Back"/>
</form>
Considering that you database.php file is giving out correct data back.
a) Error :-
You are not using return false on form submit handler , just add return false and things will work for you
b) Suggestion
1) You are attaching the checkFields() function 2 times, once on submit button click and other on form submit, remove one of them(use sumbit)
2) User below callback in onreadystatechange , the one you have done will work but it is not correct as this callback get called mulitple times
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("divTable").innerHTML=xmlhttp.responseText;
}
}
Example Code below :
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css"/>
<script >
function checkFields(){
var name = document.getElementById("name");
var address = document.getElementById("address");
var phone = document.getElementById("Phone");
if(confirm('Do you want to submit')){
if(name == null, name == ""||address == null, address == ""||phone == null, phone == ""){
alert("Please fill in all your details.");
return false;
}
else{
var page = "database.php";
var xmlhttp = new XMLHttpRequest();
if(xmlhttp==null){
alert("Your browser does not support AJAX!");
return false;
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("divTable").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", page, true);
xmlhttp.send(null);
}
}
return false;
}
</script>
</head>
<body>
<form name="infoForm" method="post" onsubmit="return checkFields()" action="">
<table>
<tr>
<td>Name:</td>
<td><input type="text" name="name" id="name" maxlength="40"></td>
</tr>
<tr>
<td>Address:</td>
<td><textarea maxlength="45" name="address"id="address" ></textarea></td>
</tr>
<tr>
<td>Phone:</td>
<td><input type="text" name="phone" id="phone" maxlength="20"><br></td>
</tr>
<tr>
<td>Gender:</td>
<td><input checked type="radio" name="gender" id="male" value="Male">Male
<input type="radio" name="gender" id="female" value="Female">Female</td>
</tr>
<tr>
<td>
Nationality:
</td>
<td>
<select name="nation">
<option value="Singapore">Singapore</option>
<option value="Malaysia">Malaysia</option>
<option value="Thailand">Thailand</option>
<option value="Indoensia">Indonesia</option>
<option value="Philippines">Philippines</option>
</select>
</td>
</tr>
<tr>
<td></td>
<td>
<br><input type="reset" value="Cancel">
<input type="submit" name="result" value="Submit" />
</td>
</tr>
</table>
</form>
<div id="divTable"></div>
</body>
</html>
Im trying to make my school project and would like to make a login system and registration system...my login queries are fine but my registration is taking its time...ivev been here for 3-4 hours trying to figure this out im crying right now.... ive done everything....so in my desperate need i asked this community... please provide immediate answers i desperately need it... the problem is... i cannot seem to haul in the data that i type into my form...tahts it...i dont know whats the reason behind
if($_POST['registerbtn'])
{
$getuser = $_POST['user'];
$getemail = $_POST['email'];
$getpass = $_POST['pass'];
$getconfirmation = $_POST['confirmation'];
if($getemail){
if($getuser){
if($getpass){
if($getconfirmation){
if( $getpass === $getconfirmation ){
if( (strlen($getemail) >= 7) && (strstr($getemail, "#")) && (strstr($getemail, "."))) {
require("./Connect.php");
$query = mysql_query("SELECT * FROM users WHERE username='$getuser'");
$numrows = mysql_num_rows($query);
if($numrows == 0){
$query = mysql_query("SELECT * FROM users WHERE email='$getemail'");
$numrows = mysql_num_rows($query);
if($numrows == 0){
$date = date("F d, Y");
$code = rand();
mysql_query("INSERT INTO users VALUES('', '$getuser', '$getemail', '$getpass', '$date' )");
mysql_query("SELECT * FROM users WHERE username='$getuser'");
$numrows = mysql_num_rows($query);
if($numrows == 1){
}else
$errormsg = "An Error Has Occurred. Account Not Processed";
}else
$errormsg ="There is already a user with that email.";
}else
$errormsg ="There is already a user with that username.";
mysql_close();
}else
$errormsg = "You must enter a valid email address";
}else
$errormsg = "Your passwords did not match";
}else
$errormsg = "Confirm your password";
}else
$errormsg = "You must enter your password";
}else
$errormsg = "You must enter your username";
}else
$errormsg = "You must enter your email address";
}
$form = "<form action='./register.php' method='post'>
<table>
<tr>
<td></td>
<td><font color='red'>$errormsg</font></td>
</tr>
</table>
<fieldset>
<legend>Account</legend>
<input type='text' name='user' size='15' value='$getuser'/>:Username<br/>
<input type='text' name='email' size='15'value='$getemail'>:Email<br/>
<input type='password' name='pass' size='15' value=''/>:Passcode<br/>
<input type='password' name='confirmation' size='15' value=''/>:Confirmation<br/>
<br/>
<input type='submit' name='registerbtn' value='EAT ME'/>
</fieldset>
</form>";
echo "$form";
?>
if you are submitting form at same page.
$form = "<form action='' method='post'>
try this..
if(isset($_POST['registerbtn']))
instead of
if($_POST['registerbtn'])
and
if your Connect.php and registration is in same folder then use require("Connect.php"); if outside the folder then give proper path
First of all, you need to check if the variables are set if not set them to "" except for registerbtn.
Like this:
<?php
if(isset($_POST['registerbtn']))
{
...
} else {
$getuser = $getemail = $errormsg = "";
}
$form = "<form action='./register.php' method='post'>
<table>
<tr>
<td></td>
<td><font color='red'>$errormsg</font></td>
</tr>
</table>
<fieldset>
<legend>Account</legend>
<input type='text' name='user' size='15' value='$getuser'/>:Username<br/>
<input type='text' name='email' size='15'value='$getemail'>:Email<br/>
<input type='password' name='pass' size='15' value=''/>:Passcode<br/>
<input type='password' name='confirmation' size='15' value=''/>:Confirmation<br/>
<br/>
<input type='submit' name='registerbtn' value='EAT ME'/>
</fieldset>
</form>";
echo "$form";
It should work provided there isn't any problem with the db part.
In the one of the if-conditionals viz:
if($numrows == 1){
}else
$errormsg = "An Error Has Occurred. Account Not Processed";
This is not needed because the else of if($numrows == 0 ) takes care of it.
change <form action='./register.php' method='post'> to <form action='' method='post'> or <form action='#' method='post'>