I have a online quiz by jQuery, I want once the user submit it, to send the results with the contact information's of the users to the moderator.
I make it work, sending the results information correctly, the problem is it doesn't send the user information.
I've been playing around with different solution's, I can manage or to have the user information or the results of the quiz, but not both at the same time !
Here is the "contact form":
<form action="submit.php" method="POST" id="form">
<label>Name</label>
<input name="name" placeholder="Type Here">
<label>Email</label>
<input name="email" type="email" placeholder="Type Here">
<label>Message</label>
<textarea name="message" placeholder="Type Here"></textarea>
<input id="button" type="submit" value="Send" class="btnShowResult">
Here is the jQuery part about the ajax to send the data result of the quiz, the div #resultKeeper being the result I want to receive
$(function() {
$('#form').on('submit',function(e) { e.preventDefault();
$.ajax({
url:'submit.php',
type:'POST',
data:{'results':$('#resultKeeper').html(),'subject':'Subject of your e-mail'},
success:function() {
$('#responseMessage').html()
}
});
return false;
});
});
here is my PHP
<?php $name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$results = $_POST['results'];
$formcontent="From: $name \n Message: $message \n Results: \n $results";
$recipient = "myemail#gmail.com";
$subject = "my subject";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Your email has been send, thank you";
?>
If in the Jquery I change the
$(function() {
$('#form').on('submit',function(e)
by #button instead of #form, I receive the informations from the contact form, but not anymore from the results.
Also by keepin the #form, I receive the result of the quiz, and few value as the form content, but not the informations from the placeholder !, here is what I receive by email:
"
From:
Message:
Results:
<div> Question 1 is true</div><div> Question 2 is false\</div><div> Question 3 is true\</div>\<div> Question 4 is false\</div>\<div> Question 5 is false\</div>\<div class=\"totalScore\">\<br>Your total score is 2 / 5\</div>\<div class=\"totalScore\">\<br>CONGRATULATION, YOUR LEVEL IS A1.1\</div
"
As we can see I have the From: and Message: appearing, but not the proper name and message that the user are writing .. .
Any help will be adorable !!
Here is the allcode of JSFiddle:
http://jsfiddle.net/ccwJJ/
You do not receive your form values in your php file when you make an ajax request, you have to explictly send them in the ajax request.
Consider below form
<form action="submit.php">
<input type="email" name="email" id="email"/>
<input type="submit" value="send"/>
</form>
Case 1 Normal way
When you submit the form normally, say hitting enter or on click you would receive the form values implicitly in your php file as $_POST['email] variable
<?php $email = $_POST['email'] ; // valid ?>
Case 2 Ajax way
When you submit the form using ajax, You do not receive the form values implicitly in your php file since your ajax request does not know about your form elements, You have to send the values explicitly in the ajax request.
$.post('submit.php',function(result){
$('#responseMessage').html(result);
});
<?php $email = $_POST['email'] // error ?>
why? because you have not set the post variable email
Then how to do it?
var uemail = $("#email").val(); // get the email
// Set email and send it through ajax
$.post('submit.php',email:uemail,function(result){
$('#responseMessage').html(result);
});
<?php $email = $_POST['email'] // works perfect ?>
So now change your form to this
<form action="submit.php" method="POST" id="quesForm">
<label>Name</label>
<input name="username" type="text" placeholder="Type Here">
<label>Email</label>
<input name="email" type="email" placeholder="Type Here">
<label>Message</label>
<textarea name="message" placeholder="Type Here"></textarea>
<input id="button" type="submit" value="Send" class="btnShowResult">
</form>
Notice I have changed name='name' to name='username'and I suggest you to change id=form to some other name say id=quesForm. I have seen some browsers does not seem to work as expected when you use tags as id names and attributes as attribute values like you have done name=name and id=form
I suggest you to use $.post instead of $.ajax, It simplifies the things for you when you really require $.post
jQuery
$(function() {
$('#quesForm').on('submit',function(e) {
e.preventDefault();
// I am fetching the form values you could get them by other selectors too
var uname = $("input[name=username]").val();
var uemail = $("input[name=email]").val();
var msg = $("textarea").val()
$.post('submit.php',{username:uname,email:uemail,message:msg,results:$('#resultKeeper').html(),subject:'Subject of your e-mail'},function(result){
// result variable contains your response text
// I guess you trying to update your response
// notice I have used html(result) as you have just used html()
$('#responseMessage').html(result);
});
// you dont require `return false`
// you have already did it using e.preventDefault();
});
});
php
<?php $name = $_POST['username'];
$email = $_POST['email'];
$message = $_POST['message'];
$results = $_POST['results'];
$results = strip_tags($results); // add this to remove html tags and all
$formcontent="From: $name \n Message: $message \n Results: \n $results";
$recipient = "thibault.rolando#gmail.com";
$subject = "my subject";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Your email has been send, thank you";
?>
To remove html tags in php you have function named strip_tags();
You need to send the form data, plus your results string.
Try the following:
$(function() {
$('#form').on('submit',function(e) { e.preventDefault();
//grab the form data into array
var formData = $('#form').serializeArray();
//add your result and subject
formData.push({ results:$('#resultKeeper').html(), subject:'Subject of your e-mail'});
$.ajax({
url:'submit.php',
type:'POST',
data:formData,
success:function() {
$('#responseMessage').html()
}
});
return false;
});
It is better to use following way for getting form input values:
var data = $('#yourformid').serielize();
You will get the data in serielize format and put it on ajax data param.
Related
I have a form that uses an HTML form, http post request, and PHP backend to automatically send me the data that a user inputs into the form. The submission works as expected, but I am not getting an email. My email is also run by outlook. Not sure if it's an encryption thing.
HTML Code
<form action="mail.php" method="POST">
<div class="email-box">
<input class="tbox" id="email_box" name="email" type="email" style="cursor: pointer;" placeholder="Enter your email">
<button class="btn" id="email_btn" type="submit" name="button">Subscribe</button>
</div>
</form>
<!-- Snipped JavaScript validation -->
PHP
<?php
$errors = '';
$myemail = 'me#website.com';
if (empty($_POST['email'])) {
$errors .= "\n Error: all fields are required";
}
$email_address = $_POST['email'];
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address)) {
$errors .= "\n Error: Invalid email address";
}
if (empty($errors)) {
$to = $myemail;
$email_subject = "New Vrify subscription: $email_address";
$email_body = "You have a new subscriber. " .
"Here are the details:\n Email: $email_address \n " .
$headers = "From: subscriber#website.com";
mail($to, $email_subject, $email_body, $headers);
//redirect to the 'thank you' page
header('Location: thank-you.html');
}
?>
This may not be the full solution, but as far as I'm aware
"New Vrify subscription: $email_address"
is not valid. Instead, concatenate them using the . operator
"New Vrify subscription:".$email_address
Do the same to the other variables you have, I had the same issue when working on the following php:
if (($_SERVER["REQUEST_METHOD"] ?? 'GET') == "POST") {
$msg ="New message from mysite!\n".$_POST["message"]."\nReply Email:".$_POST["email"];
mail("me#gmail.com", time(), $msg,"From: contact#mysite");
}
I make this form to send data to a php page in another domain but always it results error. can someone explain my problem
I search in Internet many times but exactly I didnt find my answer
here is my code
html:
<form action="#" id="smail" method="post" class="form">
<input type="text" name="name" value="Your Name *">
<input type="text" name="mailadd" value="Your E-mail *">
<textarea name="message" cols="0" rows="0">Your Message *</textarea>
<input type="submit" value="send message">
</form>
js:
$('#smail').submit(function(event) {
event.preventDefault();
var mail = $("#smail input[name=name]").val();
var message = $("#smail input[name=mailadd]").val()+' '+$("#smail textarea[name=message]").val();
$.ajax({
type: "POST",
url:"http://cofeebeen.dx.am/email.php",
crossDomain: true,
data:{
"mail": mail,
"message": message,
},
dataType: "text",
error: function(){
alert("error")
}
}).success(function(result){
alert(result)
});
});
php:
<?php
$subject = $_POST["mail"];
$msg = $_POST["message"];
mail("someone#example.com",$subject,$msg);
?>
Your PHP code is not correct, we can get data at your PHP page like below.
Correct code:
$subject = $_POST["mail"];
$msg = $_POST["message"]
Incorrect code:
$subject = $_POST["name"];
$msg = $_POST["mailadd"]
I hope it will work now.
Per #mpf82's comment, if this is a cross domain request, that changes things. However, the AJAX request is currently passing 2 PHP post variables:
...
data:{
"mail": mail,
"message": message,
},
...
And you reference 3:
$_POST['name'];
$_POST['mailadd'];
$_POST['message'];
As #Reghbendra pointed out, you are referencing the incorrect variable names. Plus, since you did the concatenation of mailadd and message in Javascript, you can skip that part in PHP.
Therefore, your code would need to reference the two post variables that were passed by their proper indexes.
Result code:
<?php
$subject = $_POST["mail"];
$msg = $_POST["message"];
mail("someone#example.com",$subject,$msg);
?>
You also should consider the headers for the PHP mail function to ensure that it sends properly and is handled correctly. See the documentation for the function here.
Okay I am at a loss for what is going wrong. I am trying to pass the form data to my php script from a simple jQuery script but for some reason when I try to access $_POST data php says that $_POST is empty?
Here we go, so I have the following jQuery and php scripts
jQuery
var post = $('#cform').serialize();
console.log("POST DATA: " + post);
$.post(action, post, function(data){
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#cform img.contact-loader').fadeOut('slow',function(){$(this).remove()});
$('#submit').removeAttr('disabled');
if(data.match('success') != null) $('#cform').slideUp('slow');
});
PHP
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
The console log of var post looks like this
POST DATA: fname=Daniel&lname=Jarvis&email=test%40gmail.com&phone=4444444444&comments=hello
And the var_dump of $_POST says this
array(0) { }
I have no clue why this is giving me so many problems so any help would be greatly appreciated.
P.S
I have also tried simply doing this for the post data but it still was not working.
var post = {fname: $('#fname').val(), lname: $('lname').val(), ...} //you get the idea
The console.log looked like this
{fname: "Dan", lname: "Jarvis", ...}
But when I var_dumped the $_POST variable it still said
array(0) { }
*There are several issues in your code,
1.Add event which will trigger ajax.
2.Your php script does not echo any data.
3.No return false or prevent defaul to stop form submission manually.(I think this is the main issue)
check the solution:*
HTML:
<form id="form">
<input type="text" name="fname">
<input type="text" name="lname">
<input type="text" name="email">
<input type="text" name="phone">
<input type="text" name="comments">
<input type="submit" name="submit" value="submit">
</form>
<span id="message"></span>
Javascript:
$("#form").submit(function(){
var post = $('#form').serialize();
console.log("POST DATA: " + post);
$.post('target.php', post, function(data){
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#cform img.contact-loader').fadeOut('slow',function(){$(this).remove()});
$('#submit').removeAttr('disabled');
if(data.match('success') != null) $('#cform').slideUp('slow');
});
return false;
})
PHP(I assume that your php script is target.php):
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
echo $fname.$lname.$email.$phone.$comments;
Ok I create an ajax form by following a tutorial. Everything is working fine. But my form fields are not clearing after submission. I searched here & found some solution, but not working for me. I've tried:
number 1: $('form#contactform input[type="text"],texatrea, select').val('');
number 2: $("#name").val("");
$("#email").val("");
$("#phone").val("");
number 3: $('#contactform')[0].reset();
but this solutions are not working for me.
My html:
<div id="form-messages"></div>
<form method="post" action="mailer.php" name="contactform" id="contactform">
<fieldset>
<div class="col-sm-3 col-xs-6">
<!-- Name -->
<input name="name" type="text" id="name" size="30" placeholder="Name" value="" />
</div>
<div class="col-sm-3 col-xs-6">
<!-- Email -->
<input name="email" type="text" id="email" size="30" placeholder="Email" value="" />
</div>
<div class="col-sm-3 col-xs-6">
<!-- Phone -->
<input name="phone" type="text" id="phone" size="30" placeholder="Phone" value="" />
</div>
<div class="col-sm-3 col-xs-12">
<!-- Send button -->
<input type="submit" class="submit" id="submit" value="Send message" />
</div>
</fieldset>
</form>
My js:
$(function() {
// Get the form.
var form = $('#contactform');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Clear the form.
$('form#contactform input[type="text"],texatrea, select').val('');
// Set the message text.
$(formMessages).text(response);
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
& My Php
<?php
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$phone = strip_tags(trim($_POST["phone"]));
$phone = str_replace(array("\r","\n"),array(" "," "),$phone);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($phone) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "friday#imransdesign.com";
// Set the email subject.
$subject = "New contact from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n";
$email_content .= "Phone: $phone\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
header("HTTP/1.0 404 Not Found");
echo "Thank You! Your message has been sent.";
$_POST=array();
} else {
// Set a 500 (internal server error) response code.
header("HTTP/1.0 404 Not Found");
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
header("HTTP/1.0 404 Not Found");
echo "There was a problem with your submission, please try again.";
}
?>
What should I do?
live example: http://imransdesign.com/ajax-form/
Your selector for number 1 is wrong. It should be:
$('#contactform').find('input[type="text"], texatrea, select').val('');
I don't know about number 2 and number 3. May be you have duplicate IDs in your page ... let me take a look. Your IDs are good. Something else must be going on.
I tested number two and three in the dev tools console on your page and they work fine:
$('#contactform')[0].reset(); //cleared the whole form
$('#name').val(''); // Cleared the name field.
There seems to be a problem with your server. It's returning a 400/404 --- fail and since you do not clear your form in the .fail callback, your form would not be cleared. The .done callback is not being called:
mailer.php POST 400 text/html jquery-2.1.0.min.js:4 279 B 378 ms
mailer.php POST 400 text/html jquery-2.1.0.min.js:4 279 B 339 ms
mailer.php POST 404 text/html jquery-2.1.0.min.js:4 256 B 343 ms
Somehow the server returns Thank You! Your message has been sent. which is output by the following part in .fail():
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
Try
$('#contactform fieldset div input').val('');
instead of
$('form#contactform input[type="text"],texatrea, select').val('');
I think you need this to clear all input fields inside form tag use this
$("#formid").find('input, textarea').not(":submit").val('');
This FIDDLE will clear all the input fields and textarea inside the form tag on submitting .. change it as you want ..its just example
Just do this:
.done(function(response) {
...
contactform.reset();
}
So I'm having some issues getting my validation which resides in my php action script.
I have the following form:
<form action="contact.php" method ="post" enctype="multipart/form-data" id="contact_form" name="contact_form">
<div class="div_input"><input name="name" type="text" value="Name: " class="input4" /></div>
<div class="div_input"><input name="phone" type="text" value="Phone: " class="input4" /></div>
<div class="div_input"><input name="email" type="text" value="E-mail: " class="input4" /></div>
<textarea name="message" cols="0" rows="0" class="textarea2" >Message: </textarea>
Then I am submitting using the onclick() method. This is where my issue is arising I believe.
<div class="link4"><span>send</span></div>
<div class="link4"><span>clear</span></div>
</form>
And my script...
<?php
$errors = '';
$myemail = 'test#test.com';
$name = $phone = $email = $message ='';
$nameError = $emailError =$phoneError = $messageError = '';
if(empty($_POST['name']))
{$nameError='Name is required!';}
else
{
$name = test_input($_POST['name']);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameError='Only letters and white space allowed';
}
}
if(empty($_POST['email']))
{$emailError='Email is required!';}
else
{
$email = test_input($_POST['email']);
//check to make sure is a valid email format
if(!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailError = "Invalid email format!";
}
}
if(empty($_POST['phone']))
{
'Phone number is required';
}
else
{
$phone = test_input($_POST['phone']);
//Allow only digits in the phone number
if(!preg_match("/^[\d\-]+$/",$phone));
{
$phoneError = 'Phone must be only numbers and dashes';
}
}
if (empty($_POST['message']))
{
$messageError = 'Message is required!';
}
else
{
$message = test_input($_POST['message']);
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n ".
"Email: $email\n Phone Number: $phone\n Message \n $message";
$headers = "From: $email \r\n";
$headers .= "Reply-To: $email";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
//header('Location: index-5.html');
?>
When I test this, no validation runs at all. I can click send with the form empty and no errors appear.
I've seen a couple people having issues with the javascript onclick function and validation in their php script. Could this be it? Or am I missing something in my script or form? I'm thinking maybe I need to add some javascript after the submit() method.
What do you all think?
The main problem is that your PHP script is sending the message regardless of whether or not there's an error.
Try checking whether $nameError, $emailError,$phoneError, and $messageError are all empty strings before submitting.
Other suggested improvements:
Read up on PHP's filter functions and use them instead of your regular expressions.
Take advantage of HTML5 validation in browsers that support it by adding required to all of your input fields.
Use <input type="submit" value="send"> and <input type="reset" value="clear"> instead of onclick. They're a little bit harder to style with CSS, but it's better for accessibility and works even when JavaScript doesn't.
One thing I see is
if(empty($_POST['phone']))
{
'Phone number is required';
}
should be
if(empty($_POST['phone']))
{
$phoneError = 'Phone number is required';
}