<?php
//Clear the cache for form values
header('Cache-Control: no store, no-cache, must-revalidate');
header('Cache-Control: no store, no-cache, must-revalidate');
header('Pragma: no-cache');
//Load up functions
include "recon.php";
//Create the PHP Self Function
$username = $nohours = $noitem = $ipaddr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = filter_input(INPUT_POST, "username", FILTER_SANITIZE_STRING);
$nohours = filter_input(INPUT_POST, "hours", FILTER_SANITIZE_NUMBER_INT);
$noitem = 0;
$xnoitem = filter_input(INPUT_POST, "itemselect", FILTER_SANITIZE_STRING);
if ($xnoitem === "item1") {
$noitem = 1;
}
$ipaddr = get_client_ip();
if(!empty($username)){
echo "Username is not null";
}
else{
echo '<script type="text/javascript">document.getElementById("warning").innerHTML = "New text!";</script>';
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title> GGG Time Form </title>
<script type="text/javascript">
function outputUpdate(hours)
{
document.querySelector('#nohours').value = hours;
document.getElementById("total").innerHTML = "$" + hours * 3.75;
document.getElementById("item1").checked = false;
}
function xitem1()
{
document.getElementById("total").innerHTML = "$16";
}
</script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div>
<div>
<h1 class="ctext">GGG Time Order Form</h1>
</div>
<div>
<p id="warning"></p>
</div>
</div>
<hr>
<div>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
(Enter your username you login with at GGG) Username:<span style="color:red;">*</span> <input type="text" name="username">
<br>
<br>
<label for="hourslider">Number of hours you would like to purchase: </label>
<input type="range" name="hours" min="1" max="24" value="12" id="hourslider" oninput="outputUpdate(value)">
<output for="hourslider" id="nohours">12</output>
<br>
<br>
<h3> Or select one of our packages below </h3>
<br>
<input type="radio" name="itemselect" value="item1" id="item1" onclick="xitem1()"> Day Pass $16.00
<hr>
<h3> Total payment owed: <p id="total">$0</p></h3>
<input type="submit">
<hr>
</form>
</div>
<div id="ipbox">
<span>For security purposes your ip address is being logged: <?php echo get_client_ip(); ?></span>
</div>
<div>
</div>
</body>
</html>
So on that logical statement below this text ( Also located in the code above) I'm wondering why when I echo out the javascript it's not changing the contents of the <p> element with the id of warning. I've tried looking everywhere for my answer and I'm sorry if this is a duplicate but any help would be appreciated...
if(!empty($username)){
echo "Username is not null";
}
else{
echo '<script type="text/javascript">document.getElementById("warning").innerHTML = "New text!";</script>';
}
"your basic problem is that it is executing, but none of your document has loaded yet. there is no element with the id of warning at the point your javascript is being loaded and executed" ~ Watcher
Related
I have a page where I have this form that sends the data in an email.
I want that when I click the submit button, other than sending the data through email, I want to send the data in a page where I have an INSERT script.
Here's the code of my page:
<!doctype html>
<html lang="en">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<?php
require_once __DIR__.'/vendor/autoload.php';
require_once __DIR__.'/config.php';
session_start();
if (!empty($_SESSION['_contact_form_error'])) {
$error = $_SESSION['_contact_form_error'];
unset($_SESSION['_contact_form_error']);
}
if (!empty($_SESSION['_contact_form_success'])) {
$success = true;
unset($_SESSION['_contact_form_success']);
}
?>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<title>Appointmenta</title>
<!-- reCAPTCHA Javascript -->
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-8 offset-md-2">
<div class="card mt-5">
<div class="card-body">
<h1 class="card-title">
Add an Appointment
</h1>
<?php
if (!empty($success)) {
?>
<div class="alert alert-success">Message sent successfully.</div>
<?php
}
?>
<?php
if (!empty($error)) {
?>
<div class="alert alert-danger"><?= $error ?></div>
<?php
}
?>
<?php $Field1= $_POST['Field1']; ?>
<?php $Field2= $_POST['Field2']; ?>
<?php $Field3= $_POST['Field3']; ?>
<?php $Field4= $_POST['Field4']; ?>
<?php $Field5= $_POST['Field5']; ?>
<?php $Field6= $_POST['Field6']; ?>
<?php $Field7= $_POST['Field7']; ?>
<?php $Field8= $_POST['Field8']; ?>
<?php $Field9= $_POST['Field9']; ?>
<form id="target" method="post">
<div class="form-group">
<label for="name">Field 1</label>
<input type="text" name="Field1" id="Field1" class="form-control"
value="<?php echo $Field1?>">
</div>
<div class="form-group">
<label for="subject">Field 2</label>
<input type="text" name="Field2" id="Field2" class="form-control"
value="<?php echo $Field2?>">
</div>
<div class="form-group">
<label for="email">Field 3</label>
<input type="text" name="Field3" id="Field3" class="form-control"
value="<?php echo $Field3?>">
</div>
<div class="form-group">
<label for="subject">Field 4</label>
<input type="text" name="Field4" id="Field4" class="form-control"
value="<?php echo $Field4?>">
</div>
<div class="form-group">
<label for="subject">Field 5</label>
<input type="text" name="Field5" id="Field5" class="form-control"
value="<?php echo $Field5?>">
</div>
<div class="form-group">
<label for="subject">Field 6</label>
<input type="text" name="Field6" id="Field6" class="form-control"
value="<?php echo $Field6?>">
</div>
<div class="form-group">
<label for="subject">Field 7</label>
<input type="text" name="Field7" id="Field7" class="form-control"
value="<?php echo $Field7?>">
</div>
<div class="form-group">
<label for="subject">Field 8</label>
<input type="text" name="Field8" id="Field8" class="form-control"
value="<?php echo $Field8?>">
</div>
<div class="form-group">
<label for="message">Field 9</label>
<input type="text" name="Field9" id="Field9" class="form-control"
value="<?php echo $Field9?>">
</div>
<div class="form-group text-center">
<div align="center" class="g-recaptcha" data-sitekey="<?= CONTACTFORM_RECAPTCHA_SITE_KEY ?>"></div>
</div>
<button "name="submit" class="btn btn-primary btn-block"> Send Email</button>
</form>
<form action="../list.php">
<p><br></p>
<button class="btn btn-primary btn-block">Return home.</button>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
<script language="Javascript">
<!--
$('form').submit(function(event) {
event.preventDefault();
$.ajax({
method: 'POST',
url: 'submit.php',
data: $( this ).serialize()
});
});
-->
</script>
When I click on 'Send Email' nothing happens.
**I want to click 'Send Email' and see the message 'Message sent successfully'. At the same time I want that same data to be sent to appointment.php, which inserts the data into a table. I'd prefer that 'appointment.php' doesn't even open, I want to stay on index.php when I click 'Send Email'**
Code of submit.php
<?php
require_once __DIR__.'/vendor/autoload.php';
require_once __DIR__.'/functions.php';
require_once __DIR__.'/config.php';
session_start();
// Basic check to make sure the form was submitted.
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
echo "The form must be submitted with POST data.";
exit();
}
require "appointment.php";
// Do some validation, check to make sure the name, email and message are valid.
if (empty($_POST['g-recaptcha-response'])) {
echo "Please complete the CAPTCHA.";
}
$recaptcha = new \ReCaptcha\ReCaptcha(CONTACTFORM_RECAPTCHA_SECRET_KEY);
$resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_REQUEST['REMOTE_ADDR']);
if (!$resp->isSuccess()) {
$errors = $resp->getErrorCodes();
$error = $errors[0];
$recaptchaErrorMapping = [
'missing-input-secret' => 'No reCAPTCHA secret key was submitted.',
'invalid-input-secret' => 'The submitted reCAPTCHA secret key was invalid.',
'missing-input-response' => 'No reCAPTCHA response was submitted.',
'invalid-input-response' => 'The submitted reCAPTCHA response was invalid.',
'bad-request' => 'An unknown error occurred while trying to validate your response.',
'timeout-or-duplicate' => 'The request is no longer valid. Please try again.',
];
$errorMessage = $recaptchaErrorMapping[$error];
echo "Please retry the CAPTCHA: ".$errorMessage;
}
// Everything seems OK, time to send the email.
$mail = new \PHPMailer\PHPMailer\PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = CONTACTFORM_PHPMAILER_DEBUG_LEVEL;
$mail->isSMTP();
$mail->Host = CONTACTFORM_SMTP_HOSTNAME;
$mail->SMTPAuth = true;
$mail->Username = CONTACTFORM_SMTP_USERNAME;
$mail->Password = CONTACTFORM_SMTP_PASSWORD;
$mail->SMTPSecure = CONTACTFORM_SMTP_ENCRYPTION;
$mail->Port = CONTACTFORM_SMTP_PORT;
// Recipients
$mail->setFrom(CONTACTFORM_FROM_ADDRESS, CONTACTFORM_FROM_NAME);
//$mail->addAddress(CONTACTFORM_TO_ADDRESS, CONTACTFORM_TO_NAME);
//$mail->addAddress(CONTACTFORM2_TO_ADDRESS, CONTACTFORM2_TO_NAME);
$mail->addAddress(CONTACTFORM3_TO_ADDRESS, CONTACTFORM3_TO_NAME);
//$mail->addAddress(CONTACTFORM4_TO_ADDRESS, CONTACTFORM4_TO_NAME);
//$mail->addReplyTo("marketing#lgp-italia.it");
// Content
$mail->Subject = "Appointment at ".$_POST['Field1'];
$mail->Body = <<<EOT
Appointment at: {$_POST['Field1']}, {$_POST['Field2']}
{$_POST['Field3']}
{$_POST['Field4']}
{$_POST['Field5']}
{$_POST['Field6']}
{$_POST['Field7']}
EOT;
$mail->send();
} catch (Exception $e) {
echo "An error occurred while trying to send your message: ". $mail->ErrorInfo;
}
Code of appointment.php
<?php
if (isset($_POST['submit'])) {
require "../../../security/config.php";
require "../../../security/common.php";
try {
$connection = new PDO($dsn, $username, $password, $options);
$new_call = array(
"Field1" => $_POST['Field1'],
[...]
);
echo var_dump("1");
$sql = sprintf(
"INSERT INTO %s (%s) values (%s)",
"db.appointments",
implode(", ", array_keys($new_call)),
":" . implode(", :", array_keys($new_call))
);
echo var_dump("2");
$statement = $connection->prepare($sql);
$statement->execute($new_call);
echo var_dump("3");
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
echo var_dump("4");
}
echo var_dump("5");
?>
Have been working on a form with Ajax and used to work on a version with no extras (css and so on) before. It worked all fine, data has been inserted successfully into the database and I have been able to show and hide two divs.
Now I used to apply it to the form I've been working on. It acts different from the previous version, so it's exactly the same (sure, changed some names, added some inputs), like no "success message" from the PHP-file, suddenly all data visible in the URL, the current form doesn't hide and shows the next one.
I can't understand the sudden change in behavior, took a look for mistakes, compared the codes, but have no idea. It seems to be such a small mistake that I don't spot it or something is wrong with the whole construction.
The current file is:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<?
require 'config.php';
session_start();
// Check if user is logged in using the session variable
if ( $_SESSION['logged_in'] != 1 ) {
$_SESSION['message'] = "You must log in before viewing your profile page!";
header("location: error.php");
}
else {
// Makes it easier to read
$id = $_SESSION['id'];
$name = $_SESSION['name'];
$email = $_SESSION['email'];
$active = $_SESSION['active'];
$hash = $_SESSION['hash'];
}
?>
<script type="text/javascript">
function getState(val) {
$.ajax({
type: "POST",
url: "demo_ajax.php",
data:'country_id='+val,
success: function(data){
$("#region").html(data);
}
});
}
$(document).ready(function(){
$("#submit").click(function(){
var size=$("#size").val();
var industry=$("#industry").val();
var country=$("#country").val();
var region=$("#region").val();
var url=$("#website").val();
var fb=$("#fb").val();
var lkdn=$("#lkdn").val();
$.ajax({
type:"post",
url:"process2.php",
data:"size="+size+"&industry="+industry+"&country="+country+"®ion="+region+"&url="+url+"&fb="+fb+"&lkdn="+lkdn,
success:function(data){
$("#theform").hide();
$("#info").html(data);
//$("#partone").css();
$("#partone").show();
alert("Hello");
}
});
});
});
</script>
<?php include 'js/js.html'; ?>
<?php include 'css/css.html'; ?>
</head>
<body class="w3-blue r_login_corp_body">
<div id="info" style="color:white"></div>
<div class="r_login_corp_body"></div>
<div class="w3-content w3-white r_siu r_centered_div">
<header class="w3-camo-black w3-container">
<div class="w3-container ">
<span class="w3-xlarge r_caption">eRecruiter</span> <span class="large">Corporate Login</span>
</div>
<div class="w3-black">
<a href="javascript:void(0)" onclick="selectForm('register');">
<div class="w3-half tablink w3-hover-text-yellow w3-padding w3-center w3-padding-16">Register</div>
</a>
</div>
</header>
<!-- Register -->
<div id="register" role="form" class="r_form_elements">
<form name="formone" class="form" autocomplete="off">
<div id="profed" class="w3-container w3-padding-16">
<div class="alert alert-error"></div>
<label>Company Industry</label>
<input class="w3-input" name="industry" id="industry" type="text" placeholder="Your Industry" >
<label>Company Size</label>
<input class="w3-input" name="size" id="size" type="integer" placeholder="Your Company Size" >
<label >Country:</label>
<select name="country" id="country" class="demoInputBox" onChange="getState(this.value);" >
<option value="">Select Country</option>
<?php
$sql1="SELECT * FROM pentagonal_country";
$results=$mysqli->query($sql1);
while($rs=$results->fetch_assoc()) {
?>
<option value="<?php echo $rs["country_code"]; ?>"><?php echo $rs["country_name"]; ?></option>
<?php
}
?>
</select>
<label>State:</label>
<select id="region" name="region" onKeyup="checkform()">
<option value="">Select State</option>
</select>
<label>Website</label>
<input class="w3-input" name="website" id="website" type="url" placeholder="Your Website-Address" >
<label>Facebook</label>
<input class="w3-input" name="fb" id="fb" type="url" placeholder="https://facebook.com/" >
<label>Linkedin</label>
<input class="w3-input" name="lkdn" id="lkdn" type="url" placeholder="https://linkedin.com/in/">
</div>
<div class="w3-row">
<button type="submit" id="submit" class="w3-button w3-black w3-half w3-hover-yellow" >Add</button>
<button class="w3-button w3-black w3-half w3-hover-pale-yellow">Forgot Password</button>
</div>
</form>
</div>
<!-- Register -->
<div id="partone" style="display:none">
<form>
name : <input type="text" name="name" id="name">
</br>
message : <input type="text" name="message" id="message">
</br>
</br>
name : <input type="text" name="url" id="url">
</br>
message : <input type="text" name="fb" id="fb">
</br>
name : <input type="text" name="lkdn" id="lkdn">
</br>
</br> </br>
Send;
</form>
</div>
</div>
</body>
</html>
and the PHP-file to insert data is:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "remotejobs";
session_start();
// Check if user is logged in using the session variable
if ( $_SESSION['logged_in'] != 1 ) {
$_SESSION['message'] = "You must log in before viewing your profile page!";
header("location: error.php");
}
else {
// Makes it easier to read
$id = $_SESSION['id'];
$name = $_SESSION['name'];
$email = $_SESSION['email'];
$active = $_SESSION['active'];
$hash = $_SESSION['hash'];
}
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$industry=$_POST["industry"];
$size=$_POST["size"];
$country=$_POST["country"];
$region=$_POST["region"];
$website=$_POST["url"];
$fb=$_POST["fb"];
$lkdn=$_POST["lkdn"];
$usrid=$id;
$sql = "INSERT INTO corp_user_profile (id, industry, size, nation, region, url, facebook, linkedin)
VALUES ('$usrid', '$industry','$size', '$country', '$region', '$website', '$fb', '$lkdn')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
I used to work with the previous file I've worked with just to be sure that everything's right after a week of bug fixing.
Can somebody tell me where the problem is, probably why it is a mistake to avoid future problems like this?
The most obvious bug (aside from the SQL injection stuff mentioned above) is that
<button type="submit" will cause the form to submit normally via postback, unless you prevent it using script. Add event.preventDefault() to the first line of your "click" handler.
$("#submit").click(function(event){
event.preventDefault(); //prevent default postback behaviour
var size=$("#size").val();
//...etc
You're seeing the data in the URL because the form is posting normally (before the ajax has chance to run) and doing a GET because there's no other method specified in the form's markup, and GET is the default..
You may want to prevent the default behavior by passing the event to your click function and calling event.preventDefault().
I have created dynamic button and i need to pass the button ID to another page when my button is clicked. I have pass it but it didn't work
Please give any solution
Here is my code for dash.php:
<?php
session_start();
function dash () {
include 'config.php';
$sql = "SELECT RoomNumber FROM roommaster ";
if ($result = mysqli_query($db, $sql)) {
$str = '';
while ($row = mysqli_fetch_array($result)) {
// generate array from comma delimited list.
$rooms = explode(',', $row['RoomNumber']);
//create the dynamic button and set the value.
foreach ($rooms as $v) {
$str .= "<a href = 'booking.php'?btn='btn'><input type='button' name='b1' id='btn' value='" . $v . "' /></a>";
}
}
return $str;
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($db);
}
mysqli_close($db);
}
Here is my booking.php page:
<?php
if (isset($_POST['btn'])) {
$btn = $_POST['btn'];
echo $btn;
}
$sql = "SELECT RoomNumber FROM roommaster where RoomId=' " . $_GET['btn'] . " '";
if ($result = mysqli_query($db, $sql)) {
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$RoomNumber = $row['RoomNumber'];
// $RoomType=$row['RoomType'];
// $Location=$row['Location'];
// $ChargesPerDay=$row['ChargesPerDay'];
}
// Free result set
mysqli_free_result($result);
} else {
echo "No records matching your query were found.";
}
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($db);
}
mysqli_close($db);
?>
HTML:
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Customer book Form</title>
<!-- Bootstrap -->
<link href="css/bootstrap1.min.css" rel="stylesheet">
<link href="css/book.css" rel="stylesheet">
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
</style>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="js/jquery-1.12.4.js"></script>
<script src="js/book1.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="head" id="link">
<div class="panel panel-primary" style="margin:20px;">
<div class="panel-heading">
<center><h3 class="panel-title"> Customer booking Form</h3></center>
</div>
<div class="panel-body">
<form method="post" action="">
<div class="col-md-12">
<div class="form-group col-md-12 ">
<label for="roomno">Room Number* </label>
<input type="text" class="form-control input-sm" name="RoomNumber" value="<?=$_GET['btn'];?>"required>
</div>
<div class="form-group col-md-6">
<label for="type">Room Type*</label>
<input type="text" class="form-control input-sm" name="RoomType" required >
</div>
<div class="form-group col-md-6">
<label for="location">Location*</label>
<input type="text" class="form-control input-sm" name="Location" required>
</div>
<div class="form-group col-md-12">
<label for="charges">Facilities*</label>
<input type="text" class="form-control input-sm" name="Facilities" required>
</div>
<div class="form-group col-md-12">
<label for="charges">ChargesPerDay*</label>
<input type="text" class="form-control input-sm" name="ChargesPerDay" required>
</div>
<div class="form-group col-md-4">
<label for="customer name">First Name*</label>
<input type="text" class="form-control input-sm" name="FirstName" required>
</div>
</div>
</form>
</div>
</body>
</html>
Try to use $_GET instead of $_POST
if (isset($_GET['btn'])) {
$btn = $_GET['btn'];
echo $btn;
}
Try linking using a form. BUTTONID should be the value to pass. $str should be:
<form action='booking.php' method='POST'>
<input type='hidden' value='BUTTONID' name='bttn'>
<input type='submit' value='".$v."'>
</form>
And then get the value of the hidden field as you already did...
$if (isset($_POST['bttn'])) {
$btn = $_POST['bttn'];
echo $btn;
}
i have modified script of dash.php and booking.php files. Please copy and paste this script.
dash.php file
<?php
session_start();
function dash(){
include 'config.php';
$sql = "SELECT RoomNumber FROM roommaster ";
if($result = mysqli_query($db, $sql))
{
$str = '';
while($row = mysqli_fetch_array($result))
{
// generate array from comma delimited list
$rooms = explode(',', $row['RoomNumber']);
//create the dynamic button and set the value
foreach ( $rooms as $v )
{
$str .= "<input type='button' name='b1' id='btn' value='".$v."' />";
}
}
return $str;
}
else {
echo "ERROR: Could not able to execute $sql. " .mysqli_error($db);
}
mysqli_close($db);
booking.php file
$sql = "SELECT RoomNumber FROM roommaster where RoomId=' " .$_GET['btn']." '";
if($result = mysqli_query($db, $sql)){
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
$RoomNumber=$row['RoomNumber'];
//$RoomType=$row['RoomType'];
// $Location=$row['Location'];
// $ChargesPerDay=$row['ChargesPerDay'];
}
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($db);
}
mysqli_close($db);
To pass little data from one page to another page use parameters in the URL as below is parameter with the value you want to pass to next page as:
Click Button
Then on the anotherpage.php use $_GET to get the value passed by the URL as:
$val = isset($_GET['parameter']) ? $_GET['parameter'] : NULL;
Then use the $val for other processing. I think this may can help you to understand how to pass data from one page to another page simply.
Try to use $_REQUEST by that you can get both GET and POST values.In booking.php print the array like below:
print_r($_REQUEST);
if (isset($_REQUEST['btn'])) {
$btn = $_REQUEST['btn'];
echo $btn;
}
Need quick help, if anyone can...
I have a quite simple html one page with form
and I'm trying to validate it with php (check blanks and verify email)
for some reason something going wrong and it doesn't show me anything
on action form
anyone have any idea? will really help me a lot.
the icons present the obvious (the text is hebrew)
(if someone knows how to validate phone, bless you as well)
the html:
<!DOCTYPE html>
<html lang="he" dir="rtl">
<head>
<title>Safari Company</title>
<meta charset="utf-8"/>
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="js/script.js"></script>
</head>
<body>
<div id="top-wrapper">
<div id="top-background">
<p class="image-text">.אפריקה. נקודת מבט חדשה</p>
<p class="credit-english">Ziv Koren</p>
</div>
</div>
<div id="costumer-wrapper">
<div id="info-for-client">
<p class="secondary-text">הדרך לאפריקה מתחילה בטיסה ישירה לטנזניה</p>
<p class="offer-text">פסח 2015 <span>|</span> 9 ימים מלאים</p>
<p class="ratz-border-above">ספארי קומפני בטיסת (סאנדור) אל-על ישירה לטנזניה וחזרה ישירות מזנזיבר. מבחר תוכניות ספארי מותאמות באופן אישי.</p>
<p class="strong">תמיד אמרתם שפעם תעשו את זה. עכשיו זה הזמן</p>
<p class="secondary-text">למידע נוסף, התאמת ספארי אישי </br> והזמנות 03-5617021</p>
</div>
<form method="post" action="confirmation.php" name="myForm" onsubmit="return validate();">
<input type="text" class="name" name="Name" placeholder="שם">
<input type="text" class="email" name="Email" placeholder="דוא״ל" >
<input type="text" class="phone" name="Phone" placeholder="טלפון" >
<textarea placeholder="הערות"></textarea>
<input type="checkbox" > ארצה לקבל עדכונים וחדשות
<button type="submit"> שלח</button>
</form>
<p class="hebrew-credit">זהות ושפה - מוסנזון פורת</p>
</div>
<div id="bottom-background">
<div id="bottom-image"> </div>
<p class="credit-english"></p>
</div>
<div id="footer-wrapper">
<footer>
<p>ספארי, בשפה הסווהילית, פירושו מסע, בשפה שלנו, מסע פירושו יציאה לדרך של גילויים חדשים, מראות, ריחות, טעמים.</br>
תחושה שאין דומה לה. לגלות את אפריקה, בכל פעם מחדש, כבר 20 שנה. נשמח להיות הדרך שלכם לאפריקה.</p>
<p class="adress-border-above"> סעדיה גאון 24, תל אביב טל. 03-5617021 פקס. 15335468614 <span> | www.safaricompany.co.il | info#safaricompany.co.il</span></p>
<img src="images/logo.png">
</footer>
</div>
</body>
<script>
function validate(){
if( document.myForm.Name.value == "" )
{
alert( "Please provide your name" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.Email.value == "" )
{
alert( "Please provide your Email" );
document.myForm.Email.focus() ;
return false;
}
if( document.myForm.Phone.value == "" )
{
alert( "Please provide your Phone" );
document.myForm.Phone.focus() ;
return false;
}
return true;
}
</script>
</html>
the php:(confirmation.php)
<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){
$name = trim($_POST["Name"]);
$email = trim($_POST["Email"]);
$phone = trim($_POST["Phone"]);
if( $name == "" || $email=="" || $phone==""){
echo "Please fill name, email and phone";
exit;
}
require_once("Inc/phpmailer/class.phpmailer.php");
$mail = new PHPMailer();
if(!$mail -> ValidateAddress($email)){
echo "You must specify a valid email.";
exit;
}
?>
<html>
<body>
Welcome <?php echo $_POST["Name"]; ?><br>
Your email address is: <?php echo $_POST["Email"]; ?>
</body>
</html>
It probably is overkill to use a custom library just to verify an email address. You could use https://secure.php.net/filter_var with the FILTER_VALIDATE_EMAIL filter. As far as I know, there is no real way of validating phone numbers.
That being said, your PHP error is that you do not close the if statement started on line 2. That causes an unexpected end, as the compiler still wants a closing accolade for your if statement.
EDIT: There is a very good SO answer for validating phone numbers.
There are a few things going on with the approach to your script.
Here is what I came up with that works on the script page.
<?php
if($_SERVER["REQUEST_METHOD"] == "POST") {
$name = trim($_POST["Name"]);
$email = trim($_POST["Email"]);
$phone = trim($_POST["Phone"]);
if( $name == "" || $email=="" || $phone==""){
$error = "Please fill name, email and phone";
}
}
else {
$error = "ERROR if someone came here directly";
}
?>
<html>
<body>
<?php if(isset($error)): ?>
<p><?php echo $error; ?></p>
<?php else: ?>
Welcome <?php echo $_POST["Name"]; ?><br>
Your email address is: <?php echo $_POST["Email"]; ?>
<?php endif; ?>
</body>
</html>
EDIT: To address the email validation you would use this to check if true or false:
This method checks if the email is NOT valid.
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailError = "Invalid email";
}
The following contact form is not validating when submitting from an iphone...
It can be previewed here: loaistudio.com/contact
When I tried to submit the form without felling the fields, it opened a new blank page showing number 1 only on the top left side "which is not suppose to do at all" and actually sent the form empty... It does not do that on desktop.
I played around with the code trying to find the issue but no idea where is the problem! please help.
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
ob_start();
if(isset($_POST['name'])
&& isset($_POST['email'])
&& isset($_POST['message'])
&& isset($_POST['token'])){
if($_SESSION['token'] != $_POST['token']){
$response = "0";
} else {
$_SESSION['token'] = "";
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$to = "EMAIL GOES HERE";
$subject = "New Message From: $name";
$message = "$message";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$headers .= 'From: '.$email . "\r\n";
$mailed = ( mail($to, $subject, $message, $headers) );
if( isset($_POST['ajax']))$response = ($mailed) ? "1" :
"0"; else $response = ($mailed) ? "<h2>Success!</h2>" :
"<h2>Error! There was a problem with sending.</h2>";
echo $response;
}
} else {
echo "Form data error!";
}
ob_flush();
die();
}
?>
<!DOCTYPE html>
<html class="no-js">
<head>
<title>Contact us | Website</title>
</head>
<body>
<div class="wrapper" id="contactPage">
<div class="content">
<?php
$token = md5(uniqid(rand(), TRUE));
$_SESSION['token'] = $token;
?>
<!--Contact Form-->
<form action="contact.php" id="contactForm" method="post" name="contactForm">
<input name="token" type="hidden" value="<?php echo $token; ?>">
<input name="ajax" type="hidden" value="1">
<div class="name">
<p>Your Name</p>
<input name="name" placeholder="Enter Name" required="" type="text">
</div>
<div class="email">
<p>Email Address</p>
<input name="email" placeholder="Enter Email" required="" type="email">
</div>
<div class="message">
<p>Message</p>
<textarea name="message" required=""></textarea>
</div>
<button id="submit" type="submit">Send</button>
</form>
<script type="text/javascript">
$("#contactForm").submit(function(event) {
event.preventDefault();
$submit = $(this).find('button[id="submit"]');
var posting = $.post($(this).attr('action'), $('#contactForm').serialize());
posting.done(function(data) {
$('span.error').remove();
if (data == "1") {
$submit.text('Sent. Thank You!');
$submit.addClass("sent");
$submit.attr('disabled', 'disabled');
} else {
$submit.after('<span style="display: inline-block; padding: 15px 5px; color: #bd3d3d">Failed to send the message, please try again later.</span>');
$submit.text('Try Again');
}
});
});
</script>
</body>
</html>
you are adding jquery at the end of the html but you are using jquery before that, so javascript breaks with Uncaught ReferenceError: $ is not defined.
try moving this line to header:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$("#contactForm").submit(function(event) {
event.preventDefault();
$submit = $(this).find('button[id="submit"]');
var posting = $.post($(this).attr('action'), $('#contactForm').serialize());
posting.done(function(data) {
$('span.error').remove();
if (data == "1") {
$submit.text('Sent. Thank You!');
$submit.addClass("sent");
$submit.attr('disabled', 'disabled');
} else {
$submit.after('<span style="display: inline-block; padding: 15px 5px; color: #bd3d3d">Failed to send the message, please try again later.</span>');
$submit.text('Try Again');
}
});
});
</script>
This is code You have added AND THEN INCLUDED JQUERY, :) SO USE JQUERY IN HEADER !