Some help needed here, I'm building a one page wordpress theme and I don't really know how to make the contact form submit without loading. Basically all my code is on index.php.
This is the form submission php code above the get_header(); It works just fine but I can't really make it submit without loading the page.
if(isset($_POST['user_submit'])) {
$parse_uri = explode( 'wp-content', $_SERVER['SCRIPT_FILENAME'] );
require_once( $parse_uri[0] . 'wp-load.php' );
$name = esc_html($_POST['user_name']);
$email = esc_html($_POST['user_email']);
$comment = esc_html($_POST['user_message']);
$website = esc_html($_POST['user_url']);
$msg = esc_attr('Name: ', 'silver') . $name . PHP_EOL;
$msg .= esc_attr('E-mail: ', 'silver') . $email . PHP_EOL;
$msg .= esc_attr('Website: ', 'silver') . $website . PHP_EOL;
$msg .= esc_attr('Message: ', 'silver') . $comment;
$to = get_option( 'admin_email' );
$sitename = get_bloginfo('name');
$subject = '[' . $sitename . ']' . ' New Message';
$headers = 'From: ' . $name . ' <' . $email . '>' . PHP_EOL;
wp_mail($to, $subject, $msg, $headers);
}
This is the jQuery post I'm using for that:
$( "#contact_form" ).submit(function( event ) {
event.preventDefault();
var $form = $( this ),
name = $form.find( "input[name='user_name']" ).val(),
email = $form.find( "input[name='user_email']" ).val(),
website = $form.find( "input[name='user_url']" ).val(),
comment = $form.find( "input[name='user_message']").val();
$.post( templateDir + "/index.php", { website : website, comment : comment, name : name, email : email, submit : "yes" } );
});
This is the site http://silviuandrei.eu/themes/bornagain/
You're checking for the user_submit POST variable:
if(isset($_POST['user_submit']))
But sending a different variable via $.post
$.post( templateDir + "/index.php", { website : website, ..... submit : "yes" } );
Change it to user_submit : "yes"
I recommend doing it at functions.php using the init action:
add_action('init','form_submits');
function form_submits() {
if( isset($_REQUEST['user_submit']) ){
require("process_post.php");
exit;//prevents the default blog output
}
}
Note that using require is just a suggestion to keep functions.php clean.
Related
I want to redirect the user to another page only after displaying a success message. The code below redirects to the another page even if the page is refreshed without submitting any data.
Code Snippet
<?php
// We will store our status message later
$message = '';
// Let's check form submitted
if( isset( $_POST['action'] ) && $_POST['action'] == 'submit' ) {
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['number'];
$message_text = $_POST['address'];
if (isset($_POST['action']))
{
// Validate required fields
if( $name == '' || $email == '' || $message_text == '' ){
$message = "<p class=\"error\">Please fill out all required fields.</p>";
}
// send email after validation
else {
// Email will be sent at this email
$mailto = 'nepstarditsolutions#gmail.com';
// Let's create html email format
// (You can use html in this email format)
// Email headers
$headers = "From: " . strip_tags( $email ) . "\r\n";
$headers .= "Reply-To: ". strip_tags( $email ) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
// Email body
$message = "<html><body>";
$message .= "<h3>Contact Info: </h3>";
$message .= "<p><strong>Name: </strong> ". strip_tags( $name ) . "</p>\r\n";
$message .= "<p><strong>Email: </strong> ". strip_tags( $email ) . "</p>\r\n";
$message .= "<p><strong>Contact Number: </strong> ". strip_tags( $phone ) . "</p>\r\n";
$message .= "<p><strong>Alternate Email: </strong> ". strip_tags( $_POST['altemail'] ) . "</p>\r\n";
$message .= "<p><strong>Hosting Package: </strong> ". strip_tags( $_POST['cradio'] ) . "</p>\r\n";
$message .= "<p><strong>Address: </strong>". strip_tags( $message_text ) . "</p>\r\n";
$message .= "</body></html>";
// Email subject
$subject = "Contact Info from ".$name;
// Send email
$mail_status = #mail( $mailto, $subject, $message, $headers );
if( $mail_status ){
$message = '<div class="alert alert-success">Quotation submitted Successfully ! </div>';
}
else {
$message = '<div class="alert alert-danger">Error in sending the Quotation ! </div>';
}
}
}
}
?>
I need help in 2 things
Success message should be displayed for 2 seconds (before the redirect).
How to redirect using JS in php?
Standard "vanilla" JavaScript way to redirect a page
You can use the code below to redirect the user after form submission code.
if( $mail_status ){
echo "
<script>
setTimeout(function() {
window.location = 'http://www.example.com/newlocation';
}, 2000);
</script>
";
}
MDN web docs on how setTimeout works
Hope it helps!
I have designed the following slick Form and using it with PhP & ajax to submit ... its working fine including sending email to the targeted email ID .. There are total Seven (07) fields which suppose to be filled by the visitor. the problem is that when Someone submit the form with all fields I can only receive three (03) fields (Name, Email & Message).... the rest of the Four (04) fields (Phone,country,Budget & Select) are not showing in email... I am sure there must be some problem with my Php. Please tell me where I am mistaking in the following Php.
<?php
// Define some constants
define( "RECIPIENT_NAME", "John Smith" );
define( "RECIPIENT_EMAIL", "example#example.com" );
define( "EMAIL_SUBJECT", "Visitor Message" );
// Read the form values
$success = false;
$senderName = isset( $_POST['senderName'] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/", "", $_POST['senderName'] ) : "";
$senderEmail = isset( $_POST['senderEmail'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['senderEmail'] ) : "";
$senderPhone = isset( $_POST['senderPhone'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['senderPhone'] ) : "";
$senderCountry = isset( $_POST['senderCountry'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['senderCountry'] ) : "";
$senderBudget = isset( $_POST['senderBudget'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['senderBudget'] ) : "";
$senderSelect = isset( $_POST['senderSelect'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['senderSelect'] ) : "";
$message = isset( $_POST['message'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['message'] ) : "";
// If all values exist, send the email
if ( $senderName && $senderEmail && $senderPhone && $senderCountry && $senderBudget && $senderSelect && $message ) {
$recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
$headers = "From: " . $senderName . " <" . $senderEmail . ">";
$success = mail( $recipient, EMAIL_SUBJECT, $message, $headers );
}
// Return an appropriate response to the browser
if ( isset($_GET["ajax"]) ) {
echo $success ? "success" : "error";
} else {
?>
<html>
<head>
<title>Thanks!</title>
</head>
<body>
<?php if ( $success ) echo "<p>Thanks for sending your message! We'll get back to you shortly.</p>" ?>
<?php if ( !$success ) echo "<p>There was a problem sending your message. Please try again.</p>" ?>
<p>Click your browser's Back button to return to the page.</p>
</body>
</html>
<?php
}
?>
You have not added phone, country, budget and select fields while mailing. Try this:
if ( $senderName && $senderEmail && $senderPhone && $senderCountry && $senderBudget && $senderSelect && $message ) {
$msgToSend = "Name: ".$senderName."\r\n";
$msgToSend .= "Email: ".$senderEmail."\r\n";
$msgToSend .= "Phone: ".$senderPhone."\r\n";
$msgToSend .= "Sender Country: ".$senderCountry."\r\n";
$msgToSend .= "Sender Budget: ".$senderBudget."\r\n";
$msgToSend .= "Sender Select: ".$senderSelect."\r\n";
$msgToSend .= "Message: ".$message;
$recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
$headers = "From: " . $senderName . " <" . $senderEmail . ">";
$success = mail( $recipient, EMAIL_SUBJECT, $msgToSend, $headers );
}
Firstly, thanks because viewing my question here. My problem is i cannot send email through my ajax request. Actually, my ajax request to post email is in another ajax request.
Here is my code for my ajax :
$.ajax({
url: 'creating_bill.php',
data: {
paid_amount : JSON.stringify(jumlah_semua),
email : emel,
name : nama
},
type: "POST",
dataType: "json",
success: function (data) {
id = data.id;
url = data.url;
confirm('Terima Kasih ! Sila membuat pembayaran dengan segera.');
window.open(data.url, '_blank');
setTimeout(checkBillStatus, 1000);
$('li#progress2').removeClass('active').next().addClass("active");
$('.container_waiting').fadeIn();
$('#cara_pembayaran_form').fadeOut();
var name =$('input#nama').val();
var phone =$('input#phone').val();
var negeri =$('input#negeri').val();
var bandar =$('input#bandar').val();
var poskod = $('input#poskod').val();
var alamat =$('input#alamat').val();
var emel = $('input#emel').val();
var jumlah = $('input#jumlah_semua').val();
var bill_url = url;
// Here is my ajax request to send email
$.ajax({
type: "POST",
url: "send_bill_email.php",
data: {
name : name,
phone : phone,
negeri : negeri,
bandar : bandar,
poskod : poskod,
alamat : alamat,
emel : emel,
jumlah : jumlah,
bill_url : bill_url
},
dataType:"json",
success: function(data2){
console.log("Success!");
}
});
},
async: false,
error: function(data) {
handleRequestError(data);
}
})
}
and this is my code in php :
<?php
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['emel'];
$address = $_POST['alamat'];
$poskod = $_POST['poskod'];
$negeri = $_POST['negeri'];
$bandar = $_POST['bandar'];
$jumlah_harga = $_POST['jumlah'];
$bill_url = $_POST['bill_url'];
$to = $email;
// Subject
$subject = 'FROM: Ordering System From - ' . $name;
// Message
$message = '
<html>
<head>
<title>' . $subject . '</title>
</head>
<body>
<p>Nama: ' . $name . '</p>
<p>Telefon: ' . $phone . '</p>
<p>Email: ' . $email . '</p>
<p>Alamat: ' . $address . '</p>
<p>Poskod: ' . $poskod . '</p>
<p>Negeri: ' . $negeri . '</p>
<p>Bandar: ' . $bandar . '</p>
<p>Jumlah Harga: ' . $jumlah_harga . '</p>
<p>Bill url: ' . $bill_url . '</p>
</body>
</html>
';
// To send HTML mail, the Content-type header must be set
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';
// Additional headers
$headers[] = 'From: ' . $name . ' <' . $email . '>';
// Mail it
mail($to, $subject, $message, implode("\r\n", $headers));
?>
Thank you for your time. I hope there is someone that could help me solve this.
Can you try to wrap your entire to php code to this
if($_SERVER['REQUEST_METHOD']=='POST'){
//YOUR CODE GOES HERE
}
also i strongly suggest to use the development window of your browser to see the process.
The problem:
Javascript function( which was premade by template) cleans the form data sent to me by php
The php code:
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'GJ '
);
$name = #trim(stripslashes($_POST['name']));
$phone = #trim(stripslashes($_POST['phone']));
$subject = #trim(stripslashes($_POST['subject']));
$message = #trim(stripslashes($_POST['message']));
$email_to = 'email#email.com';//replace with your email
$body = 'Name: ' . $name . "\n\n" . 'Телефон: ' . $phone . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = #mail($email_to, $subject, $body);
echo json_encode($status);
die;
The javascript function code:
var form = $('.contact-form');
form.submit(function () {'use strict',
$this = $(this);
$.post($(this).attr('action'), function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
return false;
});
When there's no js code php returns white screen with a line but the #mail sends normal message, but when there is this code fade in and out works good, but the data arrives empty. The message in message and name is cyrylic if that is important.
Please help me fix it(i.e. i need both data arriving and success fade-in appearing or at least data arriving with no .php white screen) or just explain what the js code does i don't get it.
Thanks
You haven't provided the data argument for $.post
Try
var form = $('.contact-form');
form.submit(function () {'use strict',
var $this = $(this);
$.post($(this).attr('action'), $this.serialize(), function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
return false;
});
References:
jQuery.post() Docs
jQuery.serialize() Docs
I have PHP code that help me to other people can be in touch with me and send their opinion to me .
here's my PHP code :
<?php
$to = 'ticket.ritaweb#gmail.com';
$subject = 'Your decision/Opinion';
$name = htmlspecialchars($_REQUEST['name']);
$email = htmlspecialchars($_REQUEST['email']);
$site = htmlspecialchars($_REQUEST['site']);
$mobile = htmlspecialchars($_REQUEST['mobile']);
$nazar = htmlspecialchars($_REQUEST['nazar']);
$sqt = '2164854';
$sqtin = htmlspecialchars($_REQUEST['sqtin']);
if ($sqt === $sqtin) {
function clean_string($string) {
$bad = array("content-
type", "bcc:", "to:", "cc:", "href");
return str_replace($bad, "", $string);
}
$email_message .= "name : " . clean_string($name) . "\n";
$email_message .= "email : " . clean_string($email) . "\n";
$email_message .= "address : " . clean_string($site) . "\n";
$email_message .= "number : " . clean_string($mobile) . "\n";
$email_message .= "opinion : " . clean_string($nazar) . "\n";
$headers = 'From: ' . $mobile . "\r\n" . 'Reply-To: ' . $email . "\r\n" . 'X-Mailer:
PHP/' . phpversion();
mail($to, $subject, $email_message, $headers);
}
?>
and I called it with javascript ( ajax ) but I want a code in ajax that help me If my condition in PHP file was FALSE or each of the field was empty , show the message : "Your message was not send, be careful".
and here's my AJAX code :
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function() {
$('#submit').attr('value', 'sending...');
$.post("themes/RitaWeb-v1/send.php", $(".rita_form").serialize(),
function(response) {
$('#submit').attr('value', 'sent.');
});
return false;
});
});
</script>
Use PHP to print messages on the page, like
{'status' : 'success'}
if the mail was sent and
{'status' : 'error'}
Then do something based on the output with js.
EDIT:
If you use jQuery.ajax instead of jQuery.post,you can also use the settings argument to let something happen if there ared errors during the request.
More information: http://api.jquery.com/jquery.ajax/
In your code, it would look like this.
PHP:
...
mail($to, $subject, $email_message, $headers);
print('{"status":"success"}');
}
else{
print('{"status":"error"}');
}
And your js:
$.ajax('themes/RitaWeb-v1/send.php').done(function(data){
status = $.parseJSON(data).status;
if(status == 'success'){
// do something
}
else if(ststus == 'error'){
// do something
}
else{
alert('unknown response');
}
});