I have a success message that is displayed no matter if the user data is valid or not. I have an error message but I'm having trouble getting it to display. I'm not the best coder so be nice :)
Also, for some reason when I receive an email via the form the user's email comes up as user#MISSING_DOMAIN. My first issue takes priority, so you don't have to help me with this one if its too much.
Form Code
<form action="contactformprocess3.php" method="post" class="myForm" >
<input name="name" type="text" id="f1" class="name-textinput"/><br />
<script type="text/javascript">
var f1 = new LiveValidation('f1');
f1.add( Validate.Presence );
</script>
<input name="email" type="text" id="f21" class="email-textinput"/><br />
<script type="text/javascript">
var f21 = new LiveValidation('f21');
f21.add( Validate.Presence );
f21.add( Validate.Email );
f21.add( Validate.Length, { minimum: 10, maximum: 35 } );
</script>
<textarea name="message" rows="9" cols="34" id="field3" class="message-textinput"></textarea>
<span class="underform">
<input type="reset" class="reset" />
<input type="submit" value="submit" class="submit" />
</span>
</form>
AJAX
$(function() {
$('.myForm').submit(function(e) {
e.preventDefault();
var form = $(this);
var post_url = form.attr('action');
var post_data = form.serialize();
$.ajax({
type: 'POST',
url: post_url,
data: post_data,
success: function(msg) {
$('.success-box').fadeIn("slow").delay(3000).fadeOut("slow");
},
error: function(xhr, status, error, req) {
$('.failure-box').fadein("slow").delay(3000).fadeOut("slow");
}
});
});
});
PHP EMAIL
<?php
$to = 'wj#pieceofmedesigns.com';
$subject = 'Piece of Me Designs';
$from = $_POST['email'];
$name = $_POST['name'];
$message = $_POST['message'];
if (mail($to, $subject, $message, 'From: '.$name.' <'.$from.'>')) {
echo 'Message was sent successfully.';
} else {
echo 'There was a problem sending your message.';
}
?>
What said Ed is totally correct. It means that you are waiting in the "error:" part of the ajax block what is for you a business rule disfunction (email not sent), while only technical errors will show up in this block.
A business error still returns "success" regarding to the technical point of view; it is just a different "success" answer that your application has to handle.
So, basically for you the solution is to check the echo:
success: function(msg) {
if (msg == 'Message was sent successfully.') {
$('.success-box').fadeIn("slow").delay(3000).fadeOut("slow");
} else {
$('.failure-box').fadein("slow").delay(3000).fadeOut("slow");
}
},
error: function(xhr, status, error, req) {
//alert the user there was a technical problem
}
I may recommend you return XML based echos from your php services, then you could manage tags and normalized responses way easier.
The AJAX error condition occurs when it is not possible to either contact the server or the server returns a status code that is not 200. Such things are file not found, script errors or network problems,
So to get the correct message you need to validate the data. You can do this before using AJAX to ensure that the data you send to the servers script has been validated.
Also you need to get your PHP script to do validation. This is a good policy to ensure security.
Related
I've created a contact form so that users can send us an email. However, every time I click to send the email it also refreshes the page when clicked. This is a one page website.
I've attempted the fixes suggested in: How do I make an HTML button not reload the page
by using either the <button> element or use an <input type="button"/>. and also the fixes suggested in: prevent refresh of page when button inside form clicked
by adding onclick="return false;".
Both of these fixes stop the button from refreshing the page when it is clicked, however, it also stops the contact form from actually working and no longer sends an email to us.
I also updated my PHP to reflect the name changes of the type.
My PHP is:
<?php
if(isset($_POST['submit'])){
$to = "example#example.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$name = $_POST['name'];
$subject = "Form submission";
$subject2 = "Copy of your form submission";
$message = $name . " wrote the following:" . "\n\n" . $_POST['message'];
$message2 = "Here is a copy of your message " . $name . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
echo "Mail Sent. Thank you " . $name . ", we will contact you shortly.";
}
?>
My HTML is:
<form action="" method="post" id="contactForm">
<input type="text" name="name" id="name" placeholder="Name...">
<input type="text" name="email" id="email" placeholder="Email...">
<p><br></p>
<textarea name="message" id="message" cols="40" rows="3" spellcheck="true" placeholder="Message..."></textarea>
<p><br></p>
<button type="submit" id="submit" name="submit" onclick="return false;">Send Message</button>
</form>
This currently works for sending the email, but does not stop it from refreshing the page. Would appreciate any help as to why it is doing this..
EDIT:
I've tried a few different options using AJAX since it was suggested this was the best route to take. All successfully stopped the page from refreshing, but all the options once again, stopped my contact form from working. I tried:
1:
$(function() {
$('#contactForm').on('submit', function(e) {
$.post('index.php', $(this).serialize(), function (data) {
// This is executed when the call to mail.php was succesful.
// 'data' contains the response from the request
}).error(function() {
// This is executed when the call to mail.php failed.
});
e.preventDefault();
});
});
2:
$("#contactForm").submit(function(e) {
e.preventDefault();
});
3:
I also tried the answer offered to me by Harsh Panchal.
You can try using jquery ajax method
Create New File for send Email and in form attribute to give any id
<script>
$('#main-contact-form').submit(function(event){
event.preventDefault();
$.ajax({
type:'post',
url:'sendememail.php',
data:$(this).serialize(),
success:function(response){
if(response==1)
{
setInterval(function(){$('.review_form').html('<h5><center><div class="alert alert-success">Review Successfully Submited......</div></center></h5>');},5);
}
else
{
setInterval(function(){$('.review_form').html('<h5><center><div class="alert alert-danger">Sorry Your Review Not Submit......</div></center></h5>');},5);
}
}
});
});
</script>
#thickguru, don't expect to receive a working solution - with or without ajax - if you maintain your mail sending php code on the SAME page with the <form>...</form>. Even if the page does not refresh, then even if you are using ajax, the page must be rebuilded from the ajax results (which is a BAD option). So, you must separate the two tasks in DIFFERENT pages and only after that use ajax. In this way you achieve a beautiful "separation of concerns" (see Separation of concerns - at least the first paragraph).
Here are two options of submitting the form by using ajax.
1. Submit the form using 'json' data type (recommended):
Page "send_mail.php":
NOTA BENE: No more if(isset($_POST['submit'])){...}. If you use this validation it will fail, because, by default, the submit button will NOT be sent as part of the POST variables. You would have to manually assign it as property in the sent data object if you'd want to still validate the $_POST array.
Notice the use of the json encoding function json_encode.
<?php
$to = "example#example.com"; // this is your Email address
//...
$message = "Mail Sent. Thank you " . $name . ", we will contact you shortly.";
echo json_encode($message);
?>
Page "index.html":
NOTA BENE: No onclick attribute on submit button!
<div id="results"></div>
<form id="contactForm" name="contactForm" action="send_mail.php" method="post">
<!-- ... The form inputs ... -->
<button type="submit" id="submit" name="submit">Submit</button>
</form>
Page "index.js" (e.g your file with the js scripts):
/**
* On document ready.
*
* #return void
*/
$(document).ready(function () {
sendEmail();
});
/**
* Send email.
*
* #return void
*/
function sendEmail() {
var contactForm = $('#contactForm');
var results = $('#results');
contactForm.submit(function (event) {
var ajax = $.ajax({
method: 'post',
dataType: 'json',
url: 'send_mail.php',
data: contactForm.serialize()
});
ajax.done(function (response, textStatus, jqXHR) {
results.html(response);
});
ajax.fail(function (jqXHR, textStatus, errorThrown) {
results.html('Email sending failed!');
});
ajax.always(function (response, textStatus, jqXHR) {
// ...
});
return false;
});
}
NOTA BENE: If you decide to use form submit validation, you have to handle ALL situations. For example, when you use it like this, you will receive an error:
if (isset($_POST['submit'])) {
//...
$message = "Mail Sent. Thank you " . $name . ", we will contact you shortly.";
echo json_encode('Hello, World!');
}
The solution is to handle the not-is-set POST 'submit' as well:
if (isset($_POST['submit'])) {
//...
$message = "Mail Sent. Thank you " . $name . ", we will contact you shortly.";
echo json_encode('Hello, World!');
} else {
echo json_encode('Submit button not recognized');
}
2. Submit the form using 'html' data type:
Page "send_mail.php":
NOTA BENE: dito.
<?php
$to = "example#example.com"; // this is your Email address
//...
$message = "Mail Sent. Thank you " . $name . ", we will contact you shortly.";
echo $message;
?>
Page "index.html":
NOTA BENE: dito.
<div id="results"></div>
<form id="contactForm" name="contactForm" action="send_mail.php" method="post">
<!-- ... The form inputs ... -->
<button type="submit" id="submit" name="submit">Submit</button>
</form>
Page "index.js":
/**
* On document ready.
*
* #return void
*/
$(document).ready(function () {
sendEmail();
});
/**
* Send email.
*
* #return void
*/
function sendEmail() {
var contactForm = $('#contactForm');
var results = $('#results');
contactForm.submit(function (event) {
var ajax = $.ajax({
method: 'post',
dataType: 'html',
url: 'send_mail.php',
data: contactForm.serialize()
});
ajax.done(function (response, textStatus, jqXHR) {
results.html(response);
});
ajax.fail(function (jqXHR, textStatus, errorThrown) {
results.html('Email sending failed!');
});
ajax.always(function (response, textStatus, jqXHR) {
// ...
});
return false;
});
}
I suggest you to not use the short-hand ajax version of post or get. You have more flexibility with a normal ajax call.
Good luck!
For doing it in ajax, remove the form.action="" because it will reload the page.
Try
remove the action attribute from form.
remove the type=submit from button.
add the click event handler to button instead of adding it to form.submit.
The code will look like this
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form id="contactForm">
<input type="text" name="name" id="name" placeholder="Name...">
<input type="text" name="email" id="email" placeholder="Email...">
<p><br></p>
<textarea name="message" id="message" cols="40" rows="3" spellcheck="true" placeholder="Message..."></textarea>
<p><br></p>
<button id="submit" name="submit">Send Message</button>
</form>
jQuery
$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
$.post('index.php', $("form#contactForm").serialize(), function(data) {}).error(function(xhr) {alert(xhr)});
});
});
Use jQuery AJAX form submit and also Event.preventDefault(), so that page is not refreshed further.
for more help here is the link https://api.jquery.com/jquery.post/
I think jQuery and AJAX is the way to go. I have a couple suggestions:
Try moving the e.preventDefault() to before you do $.post. This should stop the event before it can reload the page and then send the email.
Try using e.stopPropagation() in addition to or instead of e.preventDefault(). This will stop the event from bubbling up the DOM so that other elements won't trigger the reload.
Try adding return false; to the end of the function. There was a similar question where this worked: Prevent form redirect OR refresh on submit?
The goal is that once a the submit button is clicked, instead of going to send.php, it will just keep the page, I don't even want the page reloaded. If you guys have another way of doing this, that would be perfectly fine too.
My Ajax code
$("#sendtxt").click(function(e) {
e.preventDefault();
var phonenum = $("#phonenum").val();
var provider = $("#provider").val();
var message = $("#message").val();
$.ajax({
type : 'POST',
data : dataString,
url : 'send.php',
success : function(data) {
alert(data);
}
});
});
My Form code
<form name="reqform" action="" method="post">
<h1>Phone Number:
<input name="phonenum" id="phonenum" type="text" class="txtbox-style" onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')" required/>
<select name = "provider" id ="provider" class="txtbox-style" required>
<option value="#sms.mycricket.com">Cricket Wireless</option>
</select>
<br/>
Message:
<input name="message" id="message" type="text" class="txtbox-style"/>
<br/>
How many times?
<input name="amount" id="amount" type="number" min="1" max="20" class="txtbox-style" required/>
<br />
<input type="submit" id="sendtxt" name="sendtxt" class="btn-style" value="Start Sending" />
</h1>
</form>
My send.php
<?php
$to = $_POST["phonenum"];
$provider = $_POST["provider"];
$subject = 'Hi';
$message = $_POST["message"];
$headers = 'From: Hello' . phpversion();
mail($to . $provider, $subject, $message, $headers);
?>
Your data attribute wasn't correct, there was nothing being sent. You can try it like this, this will work:
You have to have jQuery included in your page, you can do this with this line and place it above your script:
<script>
$(document).ready(function(){
$('input[name="phonenum"]').keyup(function(e) {
if (/\D/g.test(this.value)) {
// Filter non-digits from input value.
this.value = this.value.replace(/\D/g, '');
}
});
$("#sendtxt").click(function(e) {
e.preventDefault();
var phonenum = $("#phonenum").val();
var provider = $("#provider").val();
var message = $("#message").val();
$.ajax({
type : 'POST',
data : {
provider : provider,
// ^key that appears in post
message : message,
// ^var you fetched before from the input
phonenum : phonenum
},
url : 'send.php',
success : function(data) {
alert(data);
console.log('Success');
},
error : function(xhr, err) {
console.log("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
console.log("responseText: " + xhr.responseText);
}
});
});
});
</script>
EDIT:
Check your console for errors (F12 in chrome), if there's an error, it will look like this, or similar:
If ajax succeeds, there will be at least "Success"
ANOTHER EDIT:
Put your form out of the <h1> tag, use it like this:
<h1>Phone Number:</h1>
and delete the </h1> at the end of your form...
I prefer binding form's submit event (Because user may hit enter on focused <input> element, not submitting by clicking <input type="submit">), additionally there is an easier data colletion approach:
$("form").submit(function(e) {
e.preventDefault();
$.ajax({
type : 'POST',
data : $(this).serialize(),//Here we collect all entered data
url : 'send.php',
success : function(data) {
alert(data);
}
});
});
I think that the best Approach is to use the jquery $.post method
$("form").submit(function(e) {
e.preventDefault();
$.post('send.php', $( this ).serialize()).done(function(data){
alert(data);
});
}
http://api.jquery.com/serialize/
http://api.jquery.com/jQuery.post/
** update **
example js fiddle:
http://jsfiddle.net/de71ju0r/1/
I have a simple html form where I will send a mail and there is another file named as ajax-form-submit.php where the file process will do. Now I want to show the success or failure message in the html file through ajax.
So my html form with jQuery goes like this
<form name="ajaxform" id="ajaxform" action="ajax-form-submit.php" method="POST">
First Name: <input type="text" name="fname" value ="Ravi"/> <br/>
Last Name: <input type="text" name="lname" value ="Shanker" /> <br/>
Email : <input type="text" name="email" value="xx#xxx.com"/> <br/>
<input type="button" id="simple-post" value="Run Code" name="submit"/>
</form>
<div id="simple-msg"></div>
<script>
jQuery(document).ready(function() {
jQuery("#simple-post").click(function() {
jQuery("#ajaxform").submit(function(e) {
jQuery("#simple-msg").html("<img src='loading.gif'/>");
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax( {
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR) {
jQuery("#simple-msg").html('<pre><code class="prettyprint">'+data+'</code></pre>');
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#simple-msg").html('<pre><code class="prettyprint">AJAX Request Failed<br/> textStatus='+textStatus+', errorThrown='+errorThrown+'</code></pre>');
}
});
e.preventDefault(); //STOP default action
});
$("#ajaxform").submit(); //SUBMIT FORM
});
});
</script>
Now the php file where the mail will go will be like this
<?php
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$ToEmail = 'test#demo.com';
$MESSAGE_BODY = "Name: ".$_POST["name"]."<br>";
$MESSAGE_BODY .= "Email: ".$_POST["email"]."<br>";
$mail = mail($ToEmail, $MESSAGE_BODY);
if($mail) {
echo "Mail sent successfully";
}
else {
echo "oops there is some error";
}
}
?>
I want the success message or the error message should be shown in html page.
Its showing only any message is written outside the if (isset($_POST['submit'])) { function but by doing this I can't show the success message or error message. So can someone kindly tell me how to do this? Any help will be really appreciable. Thanks.
HTML
<form name="ajaxform" id="ajaxform" action="ajax-form-submit.php" method="POST">
First Name: <input type="text" name="fname" id="fname" value ="Ravi"/> <br/>
Last Name: <input type="text" name="lname" id="lname" value ="Shanker" /> <br/>
Email : <input type="text" name="email" id="email" value="xx#xxx.com"/> <br/>
<input type="button" id="simple-post" value="Run Code" name="submit"/>
</form>
<div id="simple-msg"></div>
<script type="text/javascript">
jQuery("#simple-post").click(function() {
jQuery("#simple-msg").html("<img src='loading.gif'/>");
var formURL = $(this).attr("action");
var fname = $("#fname").val();
var lname = $("#lname").val();
var email = $("#email").val();
$.ajax({
url : formURL,
type: "POST",
data : {
aFname: fname,
aLname: lname,
aEmail: email,
aSubmit:"submit"
},
success:function(data, textStatus, jqXHR) {
jQuery("#simple-msg").html('<pre><code class="prettyprint">'+data+'</code></pre>');
},
error: function(jqXHR, textStatus, errorThrown){
$("#simple-msg").html('<pre><code class="prettyprint">AJAX Request Failed<br/> textStatus='+textStatus+', errorThrown='+errorThrown+'</code></pre>');
}
});
});
</script>
PHP
if (isset($_POST['aSubmit'])) {
$name = $_POST['aFname'];
$lname = $_POST['aLname'];
$email = $_POST['aEmail'];
$ToEmail = 'test#demo.com';
$MESSAGE_BODY = "Name: ".$_POST["aFname"].' '.$_POST["aLname"]."<br/>";
$MESSAGE_BODY .= "Email: ".$_POST["aEmail"]."<br/>";
$mail = mail($ToEmail, $MESSAGE_BODY);
if($mail) {
echo "Mail sent successfully";
}
else{
echo "oops there is some error";
}
}
Note:_I would like to mention here that i have not shown any efforts to prevent SQL injection or any other kind of vulnerability-prevention here just because that can increase the complexity for you. But, make sure that before posting such code to live sites, you incorporate all efforts to prevent your site._
I would suggest to send the status (success or error) back to the client using JSON (using PHP json_encode()). For that, you will also need to add a JSON listener in your page using JQuery script.
<input type="text" user" id="nick" />
<input type="text" user" id="message" />
Send
Lets keep it simple. I have two input boxes and a send link. I want to send the nick and message to shoutbox.php, where i will insert these values in database and want to get all the results from the database and show it on the front end.
Now i have implemented the saving in database part but i cant get back the values from database to front end.
I am desperately in need of an jquery function in which i can just send the parameters and it will do all the job for me. I hope you guys might have such a function for yourselves.
Use the jQuery Ajax method to send data to the shoutbox.php:
$.ajax({
type: "POST",
url: "shoutbox.php",
data: { nick: "val_of_nick", msg: "val_of_msg" },
success: function(data) {
alert('Loaded: ' + data);
}
});
Now in your shoutbox.php:
//read the sended data
$nickname = $_POST['nick'];
$msg = $_POST['msg'];
//to send data back, just use echo/print
echo 'You sended nickname: ' . $nickname . ' and msg: "' . $msg . '"';
If you run this code, then your js alert will show the echo line from shoutbox.php.
Hope this helps!
More info about jQuery ajax: info
Just an example:
HTML
<form id="myform">
<input type="text" user" id="nick" name="nickname" /> <!-- use name ->
<input type="text" user" id="message" name="message"/> <!-- use name -->
Send
</form>
jQuery
$('#send').on('click', function(e) {
e.preventDefault(); // prevent page reload on clicking of anchor tag
$.ajax({
type: 'POST',
url: 'url_to_script',
data: $('#myform').serialize(),
dataType: 'json', // if you want to return JSON from php
success: function(response) {
// you can catch the data send from server within response
}
});
});
Now in your PHP side you can catch the send value via ajax like:
<?php
...
$nickname = $_POST['nickname'];
$message = $_POST['message'];
......
?>
Related refs:
.serialize()
.ajax()
I'm new to jQuery / AJAX.
I'm trying to send single input with jquery/ajax/php.
LIVE EXAMPLE
But, after pressing submit nothing is happening, where is my error?
Any help much appreciated.
HTML:
<form action="submit.php">
<input id="number" name="number" type="text" />
<input id="submit" name="submit" type="submit" />
</form>
JQUERY / AJAX:
$(document).ready(function(e) {
$('input#submit').click(function() {
var number = $('input[name=number]');
var data = 'number=' + number.val();
$.ajax({
url: "submit.php",
type: "GET",
data: data,
cache: false,
success: function(html) {
if (html == 1) {
alert('wyslane');
}
else {
alert('error');
}
}
});
return false;
});
});
PHP:
<?php
$mailTo = 'email#gmail.com';
$mailFrom = 'email#gmail.com';
$subject = 'Call Back';
$number = ($_GET['number']) ? $_GET['number'] : $_POST['number'];
mail($mailTo, $subject, $number, "From: ".$mailFrom);
?>
HTML:
<form id=submit action="">
<input id="number" name="number" type="text" />
<input name="submit" type="submit" />
</form>
The action URL is irrelevant as you want to submit your data via AJAX. Add the submit id to the form and override the default submit behavior, instead of overriding the onclick handler of the submit button. I'll explain in the JS section.
JS:
var number = $('input[name="number"]');
Quotes were missing.
$(document).ready(function(e) {
$('#submit').submit(function() {
var number = $('input[name=number]');
var data = 'number=' + number.val();
$.ajax({
url: "submit.php",
type: "GET",
data: data,
cache: false,
success: function(html) {
if (html == 1) {
alert('wyslane');
}
else {
alert('error');
}
}
});
return false;
});
});
I don't really understand your success callback, why do you expect that html should be equal to 1?
Atleast I got 404 error when pressed your submit button:
Not Found
The requested URL /index.php was not found on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
When you get it to work, remember to add mysql_real_escape_string function to avoid SQL injections http://php.net/manual/en/function.mysql-real-escape-string.php
Since you are also using ID for number, you could just use: var data = 'number=' + $('#number').val()
Also if you add ID to your form, you can use:
$('#formId').submit(function(){
});
instead of that click. This function will launch when that form is submitted. This is better way because users can submit the form with other ways aswell than just clicking the submit button (enter).
var number = $('input[name=number]');
is wrong. It's
var number = $('input[name="number"]');