I have a PHP form ready, with sucesss message after the form is being sent. Thing is that the message shows after the page is redirected to the phpmailer.php
How can I make the message show after the user clicks submit? My final goal is to make the form disappear and show the thank you message instead.
<?php session_start();
if(isset($_POST['Submit'])) {
$youremail = 'email-here#gmail.com';
$fromsubject = 'domain-here.com';
$name = $_POST['name'];
$mail = $_POST['mail'];
$message = $_POST['message'];
$to = $youremail;
$mailsubject = 'Masage recived from'.$fromsubject.' Contact Page';
$body = $fromsubject.'
The person that contacted you is '.$name.'
E-mail: '.$mail.'
Message:
'.$message.'
|---------END MESSAGE----------|';
echo "Thank you fo your feedback.";
mail($to, $subject, $body);
} else {
echo "You must write a message";
}
?>
Here's the PHP code:
Thanks in advance !
Use ajax in your mail page, make the process page is seperate from the write page. After user clicks 'Send', post the data to the process page and respond with a text message or json data, and show the message on the write page
$.ajax({
url: 'your-url-to-send-mail-page',
type: 'POST',
data: maildata,
async: true,
dataType: 'text',
processData: false,
success: function(data) {
alert(data);
},
error: function(data) {
alert('An error occurs!');
}
});
------UPDATE------
write.php :
<form id="mailForm">
<input type="text" name="Submit" value="" />
<label for="title">Title:</label>
<input type="text" name="title" id="title" value="" />
<textarea name="content" rows="30" cols="50"></textarea>
<button id="sendBtn">Send</button>
</form>
<script type="text/javascript">
var maildata = new FormData($("#mailForm")[0]);
$.ajax({
url: 'send.php',
type: 'POST',
data: maildata,
async: true,
dataType: 'text',
processData: false,
success: function(data) {
alert(data);
},
error: function(data) {
alert('An error occurs!');
}
});
</script>
so it should alert "Thank you fo your feedback." after click on the send button.
Related
I am new to jquery and ajax. I have a script here where i need to pass variables to a php file. That php will be then encoded to div#chat-body. I am trying to pass the receiver variable to the load-messages.php via POST but I am getting the following error: "Undefined index: receiver in xxxx/scripts/load_messages.php on line 8". I think there is something wrong with my syntax or im doing this totally wrong.
script.js
$('input#send-message').on('click', function(){
alert("test");
var message = $('input#input-message').val();
var sender= $('input#sender').val();
var receiver= $('input#receiver').val();
if($.trim(message)!=''){
$.post('scripts/messaging.php', {message: message, sender: sender, receiver:receiver}, function(data){
//output after sending message
});
//load message to chat-body div
$.ajax({
url: 'scripts/load_messages.php',
type: "POST",
data: {receiver: receiver},
success: function(data){
$('#chat-body').html(data);
//$('#chat-body').scrollTop($('#chat-body')[0].scrollHeight);
}
});
}});
load-messages.php
<?php
session_start();
require('config.php');
require('chat_functions.php');
$messages = get_msg($_SESSION['user_id'], $_POST['receiver']);
foreach($messages as $message){
if($message['sender'] == $_SESSION['user_id']) {
?><div id = "you_message">
<?php echo '<strong> You: </strong><br />';
echo $message['message'].'<br /><br />';?>
</div><!--you_message-->
<?php
}
else{
?><div id="recipient_message">
<?php echo '<strong>'.get_name($_POST['receiver']).'</strong><br />';
echo $message['message'].'<br /><br />';?>
</div> <!--recipient_message -->
<?php
}
}
?>
It's just simple to pass the values to php file through AJAX call.
Change your AJAX call as shown in below
var message = $('#input-message').val();
var sender= $('#sender').val();
var receiver= $('#receiver').val();
$.ajax({
url: "scripts/load_messages.php",
method: "post",
//data: { "message":$('#input-message').val(),"sender":$('#sender').val(),"receiver":$('#receiver').val()},you can pass the values directly like this or else you can store it in variables and can pass
data: { "message":message,"sender":sender,"receiver":receiver},
success: function(data){
$('#chat-body').html(data);
},
error: function() {
alert('Not OKay');
}
});
and your load-messages.php could be like this`
$receiver = $_POST['receiver'];
echo $receiver;
You're passing an object, not a JSON string :
$.ajax({
type: 'POST',
url: 'scripts/messaging.php',
data: JSON.stringify ({receiver: receiver}),
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
you can try this then adapt it to your needs, as I just made it a little bit more 'basic' :
your form :
<form action="#" id="form" method="post">
<input type="text" id="sender" name="sender" />
<input type="text" id="receiver" name="receiver" />
<input type="text" id="input-message" name="input-message" />
<input type="submit" id="send-message" value="Post" />
</form>
<div id="chat-body" class="regular"></div>
the jQuery part :
$(document).ready(function(){
$("#send-message").click(function(e){
e.preventDefault(); /* to prevent form default action */
var message = $('#input-message').val();
var sender = $('#sender').val();
var receiver = $('#receiver').val();
$.ajax({
url: "load_messages.php",
method: "POST",
data: { message: message, sender: sender, receiver:receiver },
success: function(html){
alert(html); /* checking response */
$('#chat-body').html(html); /* add to div chat */
}
});
});
});
then, load_message.php
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$sender = $_POST['sender'];
$receiver = $_POST['receiver'];
$message = $_POST['message'];
echo"[ $sender / $receiver / $message ]"; /* here, you can only echo $message for instance,
then use response to append message to chat window */
?>
I am trying to implement a modal AJAX form. But when I press "Submit" I only receive empty body emails. I guess I have bugs in PHP code.
HTML:
<form class="form" method="POST">
<input type="text" name="name" placeholder="Name">
<input type="text" name="phone" placeholder="Phone">
<input type="submit" value="Submit" >
</form>
Jquery:
$(".form").submit(function() {
var this1= $(this);
var form_data = $(this).serialize();
if (is_empty(this1)){
$.ajax({
type: "POST",
url: "feedback.php",
data: form_data,
success: function (res) {
swal("Thank you", "very much", "success");
$('.black_layout').fadeOut(200);
$('.main_form_wrapper').fadeOut(200);
this1.trigger('reset');
}
});
}
return false;
});
PHP in feedback.php file:
parse_str($_POST['form_data'], $formdata);
$name = $formdata['name'];
$phone=$formdata['phone'];
$formcontent="From: $name \n Phone: $phone";
$recipient = "email#gmail.com";
$subject = "MAIL HEADER";
mail($recipient, $subject, $formcontent) or die("Error");
EDIT:I am also not getting a "Thank you" message for some reason.
You have an error during sending form data with ajax request. here is your code which is working fine :
JQuery :
$(".form").submit(function() {
var this1= $(this);
var form_data = $(this).serialize();
alert(form_data);
//if (is_empty(this1)){
$.ajax({
type: "POST",
url: "feedback.php",
data: {'form_data' : form_data },
success: function (res) { alert(res);
//swal("Thank you", "very much", "success");
$('.black_layout').fadeOut(200);
$('.main_form_wrapper').fadeOut(200);
this1.trigger('reset');
}
});
//}
return false;
});
I've created a simple AJAX, Jquery, PHP contact form on my website with inputs: Name, Email and Message. The problem is that when you write an actual email into the email field the message never comes to my inbox. It works only when the Email input field contains 1 word with no # sign.
My HTML:
<p class="form">Name</p>
<input type="text" name="userName" id="userName">
<p class="form">Email</p>
<input id="userEmail" type="email" name="userEmail">
<p class="form">Message</p>
<textarea id="msg" name="msg"></textarea><button onClick="sendContact();"></button>
My JavaScript:
function sendContact() {
jQuery.ajax({
url: "contact_me.php",
data:'userName='+$("#userName").val()+'&userEmail='+
$("#userEmail").val()+'&msg='+
$("#msg").val(),
type: "POST",
success:function(){
sendSuccess();
},
error:function (){}
});
};
My PHP:
<?php
$to = "dusset#gmail.com";
$from = $_POST['userEmail'];
$name = $_POST['userName'];
$subject = $name . "has sent you a message from .design";
$message = $name . " wrote the following:" . "\n\n" . $_POST['msg'];
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);?>
Any idea what could be the problem, please?
Try changing how you pass the data to Ajax. An example:
function sendContact() {
jQuery.ajax({
url: "contact_me.php",
data: { userName: $("#userName").val(), userEmail: $("#userEmail").val(), msg: $("#msg").val()},
type: "POST",
success:function(){
sendSuccess();
},
error:function (){}
});
};
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.
I am setting up an opt-in list for a newsletter. Below is my php script, which is working, but when I receive the email, I can't see the email address in the message, only this:
Email:
How can I get the email variable to display in the email message?
Edit: I'm posting the form using jquery/ajax, that's why there's no post and action in the form.
PHP (newsletter.php)
<?php
$to = "newsletter#example.com";
$subject = "Send me the newsletter";
$email = $_POST['email'];
$email = filter_var($email , FILTER_SANITIZE_EMAIL);
$message = "Email: $email";
mail($to, $subject, $message, "From: no-reply#example.com");
?>
HTML
<form id="newsletter_signup">
<input type="text" name="email" id="email" placeholder="Email Address" /><input type="submit" value="Submit" class="submit_button" />
</form>
jQuery
$.ajax({
type: "POST",
url: "newsletter.php",
data: $("input#email").val(),
success: function() {
$('#signup').html("<div id='message'></div>");
$('#message').html("<h3>Blah, blah, blah!</h3>")
.css({color:"#00000", fontFamily: "Arial", fontSize: "12px"})
.hide()
}
});
Try this:
$.ajax({
type: "POST",
url: "newsletter.php",
data: {"email" : $("input#email").val()},
success: function() {
$('#signup').html("<div id='message'></div>");
$('#message').html("<h3>Blah, blah, blah!</h3>")
.css({color:"#00000", fontFamily: "Arial", fontSize: "12px"})
.hide()
}
});
Also check out jQuery serialize method (you can just type data: $("form").serialize()).
http://api.jquery.com/serialize/
Your from should be
<form id="newlsetter_signup" method="POST" action="">