I have built a contact form for my wordpress site. Four fields are there - name, email, subject, message. For logged in users I want their name and email to be auto-filled in their respective fields in the form and those name, email fields will be disabled for them to edit. And for non-logged in users they will put name, email fields manually. I have put this code in the page template file -
<?php
$current_user = wp_get_current_user();
$user_email = $current_user->user_email;
$user_name = $current_user->user_firstname.' '.$current_user>user_lastname;
if ( 0 != $current_user->ID ) {
echo '<script type="text/javascript">
document.getElementById("curUserName").value = "'.$user_name.'";
document.getElementById("curUserName").disabled = "disabled";
document.getElementById("curUserEmail").value = "'.$user_email.'";
document.getElementById("curUserEmail").disabled = "disabled";
</script>';
}
?>
But this code is disabling name, email fields for both users (logged in and non-logged in). I have controlled the script through if condition. Still the javascript is applying for both users. Please advise where I have gone wrong.
Here is the form html -
<form action="/success.php" method="post">
<label>Name :</label><br>
<input type="text" id="curUserName" name="sender_name" required><br>
<label>Email :</label><br>
<input type="text" id="curUserEmail" name="sender_email" required><br>
<label>Subject :</label><br>
<input type="text" name="sender_sub"><br>
<label>Message</label><br>
<textarea name="sender_msg" rows="4" cols="60" required></textarea><br>
<input type="submit" name="submit" value="Send">
</form>
The source you are going to change has disabled option already.. so just remove it if the user is not logged in :)
<?php
$current_user = wp_get_current_user();
$user_email = $current_user->user_email;
$user_name = $current_user->user_firstname.' '.$current_user>user_lastname;
echo '<script type="text/javascript">';
if ( 0 != $current_user->ID )
{
echo 'document.getElementById("curUserName").value = "'.$user_name.'"
document.getElementById("curUserName").disabled = "disabled"
document.getElementById("curUserEmail").value = "'.$user_email.'"
document.getElementById("curUserEmail").disabled = "disabled"';
}
else
{
echo 'document.getElementById("curUserName").disabled = false;
document.getElementById("curUserEmail").disabled = false;';
}
echo '</script>';
?>
Don't echo javascript with php. It's bad practice.
Try using value tags in your inputs, check if user logged in with a ternary operator, and if so, echo to value tag their credentials.
<?php (is_user_logged_in()) ? $current_user = wp_get_current_user() : $current_user = false; ?>
<label>Name</label>
<input type="text" id="curUserName" name="sender_name" value="<?php ($current_user) ? echo $current_user->user_name : '' ?>" required>
<label>Email</label>
<input type="text" id="curUserEmail" name="sender_email" value="<?php ($current_user) ? echo $current_user->user_email : '' ?>" required>
Related
I'm trying to develop a contact form for a language school website that runs on Wordpress.
Disclaimer: I'm about 6 months into coding, so please forgive me for being new to this. I'm developing my own theme and I wanted to limit usage of plugins to bare minimum for safety reasons - I prefer to learn how to write stuff myself instead on relying on updates of a third-party plus the courses I follow on Wordpress dev listed it as a good practice to avoid unnecessary plugins.
Update: I tried implementing plugins, but they either broke my page or didn't work anyway.
The problem is listed below in bold.
What I want to achieve:
Simple contact form that takes following info: name, email, course, phone (optional) and a message.
Validate the form if user provided correct info - I can't make the
user provide valid info, but at least I want to lock number into
numbers only range and check if email is correct.
Check if user is human (Captcha).
Send the email to my address and provide a copy to the sender.
Inform the user whether the action was a success or a failure.
What I succeeded with:
Mail gets sent.
Captacha seems to be working and filtering out attempts that do not click on it.
What 'kinda works':
The PHP doesn't seem to validate the form. I used HTML type and require instead, but I've read that solution is not ideal. I tried to use JS to write some functions that would prevent unwanted input, but I couldn't get it to work properly. I decided to ask the question first in case it might be a dead end. JS seems to be working on my Wordpress as I'm using Bootstrap and some custom JS for certain features so I'm pretty sure the code gets executed, but I wanted to ask first if that's the correct way of approach it before I invest my time in it.
What I have a problem with:
It is imperative to me that the user gets feedback from the page whether the email has been sent or not for obvious business-client communication reasons. I tried two solutions found on SO:
Injecting JS alert into PHP's echo inside conditional (JS doesn't get executed)
Using header method to redirect into thank-you.page that informs about success or error.page that
informs about a failure and recommends another avenue of contact
What went wrong: the second solution got executed properly, the user gets redirected to site.com/thank-you or site.com/error, however the browser crashes due to 'too many redirects'.
I tried googling, I tried different solutions from tutorials. What would be your recommendation?
My code:
<?php
$nameErr = $emailErr = $courseErr = $phoneErr = "";
$name = $email = $course = $comment = $phone = "";
$thank_you = wp_redirect( '"'.home_url().'/thank-you"', 301 );
$error = wp_redirect( '"'.home_url().'/error', 301 );
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Give name";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Need email";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Email incorrect";
}
}
if (empty($_POST["phone"])) {
$phone = "";
} else {
$phone = test_input($_POST["phone"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!is_numeric($number)) {
$phoneErr = "Bad number";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["course"])) {
$courseErr = "Pick course";
} else {
$course = test_input($_POST["course"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(!empty($_POST['g-recaptcha-response']))
{
$secret = 'mySecretKey';
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
if($responseData->success)
$message = "g-recaptcha verified successfully";
if(isset($_POST['submit'])){
$to = "myEmail#mail.org"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$name = $_POST['name'];
$course = $_POST['course'];
$phone = $_POST['phone'];
$comment = "Form submission";
$comment2 = "Copy of your form submission";
$message = "Name:" . $name . "Interested in " . $course. " Number" . $phone . " " . " Wrote" . "\n\n" . $_POST['comment'];
$message2 = "Copy " . $name ."\n\n" . "Interested in:" . $course . "\n\n" . $_POST['comment'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$comment,$message,$headers);
mail($from,$comment2,$message2,$headers2);
// sends a copy of the message to the sender
header($thank_you);
// This redirects to page thanking for contact.
}
else
header($error);
// This redirects to page informing about failure.
$message = "couldn't verify Captcha. Email not sent.";
echo '<script type="text/javascript">mailNotSent();</script>';
}
?>
<section id="contact" class="contact">
<div class="container pseudonest">
<div class="pseudonest contact__head--nest">
<h1 class="display-5 lh-1 mb-2 contact__head--pseudocircle contact__head--header mx-auto">Enroll now</h1>
</div>
<div class="container m-auto">
<div class="d-flex justify-content-center contact__form">
<div class="col-md-7 col-lg-8">
<form action="" method="post">
<form class="needs-validation" novalidate>
<div class="row g-3">
<div class="col">
<label for="name" id="nameHeader" class="form-label">Name</label>
<input type="text" class="form-control radio__margin" id="name" name="name"
placeholder="" value="<?php echo $name;?>" required>
<div class="invalid-feedback">
<?php echo $nameErr;?>
</div>
<label for="email" class="form-label">Email</label></label>
<input type="email" class="form-control radio__margin" id="email" name="email"
placeholder="you#example.com" value="<?php echo $email;?>" required>
<div class="invalid-feedback">
<?php echo $emailErr;?>
</div>
<label for="phone" class="form-label">Phone</label></label>
<input type="number" class="form-control radio__margin" id="phone" name="phone"
pattern="[0-9]+" placeholder="+48 111 222 333" value="<?php echo $phone;?>">
<div class="invalid-feedback">
<?php echo $phoneErr;?>
</div>
</div>
<div class="col radio__col">
<label for="firstName" class="form-label">Course?</label>
<div class="row radio__section">
<label class="radio__container">English
<input type="radio" name="course"
<?php if (isset($course) && $course=="English") echo "checked";?>
value="English">
<span class="radio__checkmark"></span>
</label>
<label class="radio__container">
<input type="radio" name="course"
<?php if (isset($course) && $course=="Polish") echo "checked";?>
value="Polish">
<span class="radio__checkmark"></span>Polish
</label>
<label class="radio__container">
<input type="radio" name="course"
<?php if (isset($course) && $course=="Italian") echo "checked";?>
value="Italian">
<span class="radio__checkmark"></span>Italian
</label>
<span class="error"> <?php echo $courseErr;?></span>
</div>
</div>
</div>
<div class="col-12 mb-5">
<label for="email-content" class="form-label">Content</label>
<div class="input-group has-validation">
<textarea class="form-control" rows="5" name="comment"
cols="30"><?php echo $comment;?></textarea>
<div class="invalid-feedback">
</div>
</div>
</div>
<form id="frmContact" action="varify_captcha.php" method="POST" novalidate="novalidate">
<div class="g-recaptcha my-3" data-sitekey="mySiteKey">
</div>
<input type="submit" name="submit" value="Send" id="submit"
class="btn btn-primary contact__form--btn">
<div id="fakeSubmit" class="btn btn-primary contact__form--btn hidden">Fill the form
</div>
</form>
</form>
</div>
</div>
</section>
I have the code in Participate.php file which has a form:
<form method="post" action="input.php" id="Form">
<input type="text" class="form-control" name="txtName" maxlength="20" required style="margin-bottom:20px">
<input type="email" class="form-control" name="txtEmail" aria-describedby="emailHelp" required style="margin-bottom:20px">
<input type="submit" class="btn btn-success" id="btnsubmit" value="Zgłoś się" />
</form>
After unsucessful submit (I check if inserted mail already exist in database) and if no exist I want to refill value for form. This is the input.php code:
<?php
$name = $_POST['txtName'];
$mail = $_POST['txtEmail'];
$description = $_POST['txtDescription'];
$connect = new PDO("mysql:host=4*****3;dbname=3*****b", "3***b", "****");
$connect->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
$q=$connect->prepare("SELECT mail FROM konkurs WHERE mail LIKE (?)");
$q->bindValue(1, $mail);
$q->execute();
$row_cnt = $q->rowCount();
if($row_cnt == 0){
$query = $connect->prepare("insert into konkurs(name,mail,description)
values(?, ?, ?)");
$query->bindValue(1, $name);
$query->bindValue(2, $mail);
$query->bindValue(3, $description);
try {
$query->execute();
echo ("<script LANGUAGE='JavaScript'>
window.alert('Sent.');
window.location.href='index.html';
</script>");
exit;
} catch (PDOException $e) {
die($e->getMessage());
}
} else {
echo ("<script LANGUAGE='JavaScript'>
window.alert('This mail already exist.');
window.location.href='Participate.php';
document.getElementById('txtName').value = 'nothing';
</script>");
}
?>
The thing is it's redirecting to Participate.php after unsuccesfull sumbition. But it doesn't refill the form.
First of all, you must change your HTML to include the id attribute, for example:
<form method="post" action="input.php" id="Form">
<input type="text" class="form-control" id="txtName" name="txtName" maxlength="20" required style="margin-bottom:20px">
<input type="email" class="form-control" id="txtEmail" name="txtEmail" aria-describedby="emailHelp" required style="margin-bottom:20px">
<input type="submit" class="btn btn-success" id="btnsubmit" value="Zgłoś się" />
</form>
Then, you must move your logic to the same file as the form container (here Participate.php), and remove the redirection for failures. Otherwise, you'll get no visible results, as the redirection would prevent further JavaScript code from running.
// Updated to prevent syntax errors with multiline strings
echo "<script>"
. "window.alert('This mail already exist.');"
. "document.getElementById('txtName').value = 'nothing';"
. "</script>";
I have only used software like Adobe Muse in the past so I am quite new to coding, but I think I have the basics down.
I am trying to create a form that will alter the content on a template site that will be duplicated.
I created the form:
<form class="pure-form" id="Builder" method="POST" action="scripts\build.php">
<fieldset class="pure-group">
<input type="text" class="pure-input-1" placeholder="Store Name" name="Name">
<textarea class="pure-input-1" placeholder="Description" name="Description"></textarea>
<textarea class="pure-input-1" placeholder="About Paragraph" name="About"></textarea>
<input type="text" class="pure-input-1" placeholder="Store Address" name="Address">
<input type="text" class="pure-input-1" placeholder="Contact Number" name="Number">
<input type="text" class="pure-input-1" placeholder="Email Address" name="Email">
<input type="text" class="pure-input-1" placeholder="Tumblr Username" name="username">
<input type="text" class="pure-input-1" placeholder="Unique ID" name="unique">
<button name="btnbuild" type="submit" class="pure-button pure-input-1 pure-button-primary">Create Website</button>
</fieldset>
The form seems to be functioning alright.
I created a PHP file to get the data from this form:
<?php
$name = $_POST["Name"];
$descrip = $_POST["Description"];
$about = $_POST["About"];
$address = $_POST["Address"];
$number = $_POST["Number"];
$email = $_POST["Email"];
$username = $_POST["Username"];
$unique = $_POST["Unique"];
?>
I am not sure about the code for the images, but the variables should work alright.
In my index.html I used the following method to find and replace the strings that need to be replaced on the page.
<head>
<script>
window.onload = function() {
<?php include 'build.php'; ?>;
document.body.innerHTML = document.body.innerHTML.replace("EHNAME", "<?php echo $name; ?>");
document.body.innerHTML = document.body.innerHTML.replace("EHDESCRIPTION", "<?php echo $descrip; ?>");
document.body.innerHTML = document.body.innerHTML.replace("EHABOUT", "<?php echo $about; ?>");
document.body.innerHTML = document.body.innerHTML.replace("EHADDRESS", "<?php echo $address; ?>");
document.body.innerHTML = document.body.innerHTML.replace("EHNUMBER", "<?php echo $number; ?>");
document.body.innerHTML = document.body.innerHTML.replace("EHEMAIL", "<?php echo $email; ?>");
document.body.innerHTML = document.body.innerHTML.replace("EHUNIQUEID", "<?php echo $unique; ?>");
document.body.innerHTML = document.body.innerHTML.replace("EHUSERNAME", "<?php echo $username; ?>");
document.title = name; }
</script>
</head>
The problem is that it doesn't update the strings at all.
Any help to figure this out would be appreciated.
If I got it right, your initial form post the data to: scripts\build.php and later you are trying to get this data in another page index.html, this seems to be to problem.
Even if you import the build.php in the index.html file, this is another request, so the posted data to the build is already gone. You can solve this problem making the post directly to the index or persisting the data (in the session, for example, or database) and retrieving it in the index.html file.
here's the code guys please help me
if mysqli_num_rows==false Than code works but why num rows doesn't work i can't get it i tried everything but same error appears
<?php
//Start session
session_start();
//Include database connection details
require_once('db.php');
if(isset($_POST['submit'])){
$username=$_POST['username'];
$password=$_POST['password'];
$query="SELECT * FROM users WHERE username='$username' and password='$password'";
$result=mysqli_query($con,$query);
if($row=mysqli_num_rows($result)==1){
mysqli_fetch_array($con,$result);
echo 'Logged in';
header('location:profile.php');
}
else{
echo 'error occured';
}
}
?>
<form method="POST">
<input type="text" name="username" placeholder="username">
<input type="text" name="password" placeholder="password">
<input type="submit" name="submit">
</form>
<form method="POST">
<input type="text" name="username" placeholder="username">
<input type="text" name="password" placeholder="password">
<input type="submit" name="submit">
</form>
<?php
error_reporting(E_ALL); // check all type of error
ini_set('display_errors',1); // display those errors
session_start();
require_once('db.php');
if(!empty(trim($_POST['username'])) && !empty(trim($_POST['password']))){ // check with posetd value
$user_name = trim($_POST['username']);
$password = md5(trim($_POST['password']));
$query = "SELECT * FROM users where username='$username' and password = '$password'"; // don't use plain password, use password hashing mechanism
$result = mysqli_query($con,$query); // run the query
if(mysqli_num_rows($result)>0){ // if data comes
// here do some data assignment into session
header('location:profile.php'); // go to other page
}else{
echo "Login creadentials are not correct"; // else no user is there with the given credentials
}
}else{
echo "please fill the form value";
}
?>
Note:-
Read and use prepared statements to prevent your code from SQL Injection. :-http://us.php.net/manual/en/mysqli-stmt.prepare.php
Above file extension must be .php
Problem
I will try to include as much information as possible without complicating things, but i have a problem where when i submit a form the page refreshes thus closing the tab with the form on. The user then needs to click on the tab again to view the feedback.
Background info.
I have one webpage using JavaScript to open and close "tabs" (divs), on one of these tabs i have a form which POST's the user inputted data to a php script which then sends the data to an email address and then redirects back the the original page. However when the script redirects back to the page the tab is closed thus making the user re-click on the tab to open it again to see the automated feedback from the script.
What i have checked
I have checked and it is not the redirect causing the refreshing as it still happens when the form POST's to itself.
The website in question
Does anyone have any ideas?
Here is the HTML for the form, which is in the enquiry 'tab'.
<div class='content one'>
<div id="contact-form" class="clearfix">
<P>Quick And Easy!</P>
<br/>
<P>Fill out our super swanky contact form below to get in touch with us! Please provide as much information as possible for us to help you with your enquiry.</P>
<br/>
<?php
//init variables
$cf = array();
$sr = false;
if(isset($_SESSION['cf_returndata'])){
$cf = $_SESSION['cf_returndata'];
$sr = true;
}
?>
<ul id="errors" class="<?php echo ($sr && !$cf['form_ok']) ? 'visible' : ''; ?>">
<li id="info">There were some problems with your form submission:</li>
<?php
if(isset($cf['errors']) && count($cf['errors']) > 0) :
foreach($cf['errors'] as $error) :
?>
<li><?php echo $error ?></li>
<?php
endforeach;
endif;
?>
</ul>
<p id="success" class="<?php echo ($sr && $cf['form_ok']) ? 'invisible' : ''; ?>">Now sit back and relax while we go to work on your behalf, we'll keep you updated with information on our results and if you have any questions then we welcome your calls or emails on 078675675446 or isaaclayne#southwestcarfinder.co.uk</p>
<form method="POST" action="process.php">
<label for="enquiry">Make: </label>
<select id="make" name="make">
<option value="Ford" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['make'] == 'Ford') ? "selected='selected'" : '' ?>>Ford</option>
<option value="BMW" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['make'] == 'BMW') ? "selected='selected'" : '' ?>>BMW</option>
<option value="Vauxhall" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['make'] == 'Vauxhall') ? "selected='selected'" : '' ?>>Vauxhall</option>
</select>
<label for="Model">Model: <span class="required">*</span></label>
<input type="text" id="model" name="model" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['model'] : '' ?>" placeholder="Model of Car" required autofocus />
<label for="name">Name: <span class="required">*</span></label>
<input type="text" id="name" name="name" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['name'] : '' ?>" placeholder="John Doe" required autofocus />
<label for="email">Email Address: <span class="required">*</span></label>
<input type="email" id="email" name="email" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['email'] : '' ?>" placeholder="johndoe#example.com" required />
<label for="telephone">Telephone: </label>
<input type="tel" id="telephone" name="telephone" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['telephone'] : '' ?>" />
<label for="Budget">Your Budget: </label>
<select id="enquiry" name="enquiry">
<option value="300 or less" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['enquiry'] == 'General') ? "selected='selected'" : '' ?>>£300 or less</option>
<option value="400 or more" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['enquiry'] == 'Sales') ? "selected='selected'" : '' ?>>£400</option>
<option value="500 or more" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['enquiry'] == 'Support') ? "selected='selected'" : '' ?>>£500 or more</option>
</select>
<label for="message">Additional Info: <span class="required">*</span></label>
<textarea id="message" name="message" placeholder="Your message must be greater than 20 charcters" required data-minlength="20"><?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['message'] : '' ?></textarea>
<span id="loading"></span>
<input type="submit" value="Find My Car!" id="submit-button" />
<p id="req-field-desc"><span class="required">*</span> indicates a required field</p>
</form>
<?php unset($_SESSION['cf_returndata']); ?>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>!window.jQuery && document.write(unescape('%3Cscript src="js/libs/jquery- 1.5.1.min.js"%3E%3C/script%3E'))</script>
<script src="js/plugins.js"></script>
<script src="js/script.js"></script>
<!--[if lt IE 7 ]>
<script src="js/libs/dd_belatedpng.js"></script>
<script> DD_belatedPNG.fix('img, .png_bg');</script>
<![endif]-->
</div>
PHP Script
<?php
if( isset($_POST) ){
//form validation vars
$formok = true;
$errors = array();
//sumbission data
$ipaddress = $_SERVER['REMOTE_ADDR'];
$date = date('d/m/Y');
$time = date('H:i:s');
//form data
$make = $_POST['make'];
$model = $_POST['model'];
$name = $_POST['name'];
$email = $_POST['email'];
$telephone = $_POST['telephone'];
$enquiry = $_POST['enquiry'];
$message = $_POST['message'];
//validate form data
//validate name is not empty
if(empty($name)){
$formok = false;
$errors[] = "You have not entered a name";
}
//validate email address is not empty
if(empty($email)){
$formok = false;
$errors[] = "You have not entered an email address";
//validate email address is valid
}elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$formok = false;
$errors[] = "You have not entered a valid email address";
}
//validate message is not empty
if(empty($message)){
$formok = false;
$errors[] = "You have not entered a message";
}
//validate message is greater than 20 charcters
elseif(strlen($message) < 20){
$formok = false;
$errors[] = "Your message must be greater than 20 characters";
}
//send email if all is ok
if($formok){
$headers = "From: Info#Columbus.com" . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$emailbody = "<p>You have recieved a new message from the enquiries form on your website.</p>
<p><strong>Name: </strong> {$name} </p>
<p><strong>Telephone: </strong> {$telephone} </p>
<p><strong>Email Address: </strong> {$email} </p>
<br/>
<p><strong>Make: </strong> {$make} </p>
<p><strong>Model: </strong> {$model} </p>
<p><strong>Budget: </strong> {$enquiry} </p>
<br/>
<p><strong>Message: </strong> {$message} </p>
<p>This message was sent from the IP Address: {$ipaddress} on {$date} at {$time}</p>";
mail("dancundy#hotmail.com","New Enquiry",$emailbody,$headers);
}
//what we need to return back to our form
$returndata = array(
'posted_form_data' => array(
'name' => $name,
'email' => $email,
'telephone' => $telephone,
'enquiry' => $enquiry,
'message' => $message
),
'form_ok' => $formok,
'errors' => $errors
);
//if this is not an ajax request
if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest'){
//set session variables
session_start();
$_SESSION['cf_returndata'] = $returndata;
//redirect back to form
//header('location:' . $_SERVER['HTTP_REFERER']);
header('Location: index.php#contact-form' );
}
}
?>
You are making a POST request when you submit the form. POST request by default travel through an HTTP request that the browser sends to the server, and therefore the browser needs to load the new data that causes the site to refresh.
If you want the browser to not refresh then you need to do an AJAX request using Javascript on the client side. You can use jQuery to accomplish this.
try this
$('form').submit(function(e)
{
e.preventDefault();
})
Thank you #saman and #gpopoteur,
Your answers are great and do work, just wasn't working on my testing server.
This is what got to work in the end.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script><script>
$('#form1').submit(function(e)
{
event.preventDefault();
$.ajax({
type : 'POST',
url : 'process.php',
data : $(this).serialize(),
success : function(response) {
}
});
});
What i did find is though that nothing is returned from the script. E.I any validation info or returned data? Not too much of a problem and i'll create a work around. Thank again