Send info with ajax to submit.php - php

Heys guys, I've been playing around with this ajax call for a few days now. I had it posting an email with no variables earlier, but now I can't get the call to submit the form with a variable or without. Here is my code:
<form id="contactform" method="post" action="submit.php">
<input type="text" placeholder="Name" name="username" id="username" />
<input type="email" placeholder="Your Email Address" name="email" id="email" />
<input type="button" id="submit" class="submit" value="submit"></a>
</form>
AJAX:
<script type="text/javascript">
$("#submit").click(function(event){
var data = $('#contactform').serialize();
event.preventDefault();
$.ajax({
url: "submit.php",
type: "POST",
data: data,
success: function() {
alert("Success!");
}
});
return false;
});
});
</script>
submit.php:
<?php
$from = "info#email.com";
$usersubject = "Thank You!";
$usermessage = "Thank you for signing up!";
$to = $_REQUEST['email'];
$subject = "Form Info";
?>
<?php
$name = $_REQUEST['username'];
$email = $_REQUEST['email'];
$message = "Name: $name
Email: $email";
$headers = "From:" . $from;
//mail($to,$subject,$message,$headers);
mail($email,$usersubject,$usermessage,$headers);
echo 'Success';
?>
submit.php works when you access it directly with the variable (www.website.com/submit.php?username=Dave&email=davesemail#mail.com). Is there an error somewhere here that I'm missing? Any help is appreciated!

This what you want but you should learn about Json.
data={
"name":"James Bond","email":"AGENT007#MI5.gov "
}

If you don't use a document ready block:
$( document ).ready(function() {
// your code here
});
Then make sure you put your javascript code just before the closing body tag ().
Otherwise if you put the javascript in the header without a document ready the javascript code will be executed before the submit button is present on the page and therefor the $('#submit') selector will return zero elements.

HTML:
<form method="post" action="submit.php">
<input type="text" placeholder="Name" name="username" id="username" />
<input type="email" placeholder="Your Email Address" name="email" id="email" />
<input type="button" onClick="submit()" value="submit"></a>
</form>
AJAX:
<script type="text/javascript">
function submit(){
var user = document.getElementById("username").value;
var email = document.getElementById("email").value;
$.ajax({
url: "submit.php",
type: "POST",
data: {uname:user,email:email},
success: function() {
alert("Success!");
}
});
return false;
}
</script>
PHP:
<?php
$from = "info#email.com";
$usersubject = "Thank You!";
$usermessage = "Thank you for signing up!";
$to = $_POST['email'];//one that assigned to data in ajax
$subject = "Form Info";
?>
<?php
$name = $_POST['uname']; //one that assigned to data in ajax
$email = $_POST['email'];//one that assigned to data in ajax
$message = "Name: $name
Email: $email";
$headers = "From:" . $from;
//mail($to,$subject,$message,$headers);
mail($email,$usersubject,$usermessage,$headers);
echo 'Success';
?>

Related

XAMPP on windows 10 is not running php

Project structure is as follows
C:\xampp\htdocs\myProject\Documentation
C:\xampp\htdocs\myProject\HTML\css
C:\xampp\htdocs\myProject\HTML\images
C:\xampp\htdocs\myProject\HTML\js
C:\xampp\htdocs\myProject\HTML\videos
C:\xampp\htdocs\myProject\HTML\404.html
C:\xampp\htdocs\myProject\HTML\contact.php
C:\xampp\htdocs\myProject\HTML\index.html
C:\xampp\htdocs\myProject\PSD
I have a contact form in index.html that is controlled by a javascript file. This code stops default form submit, performs error checks and then uses ajax to make a post request to contact.php. The javascript code runs, it detects the php (see the alert in the code below just after the axjax funtion call. The value of d is the php script in the alert, but none of the debug lines in the php code get called and it never returns 'success'.
Here is the form
<form class="form-horizontal" id="phpcontactform">
<div class="control-group">
<input class="input-block-level" type="text" placeholder="Full Name" name="name" id="name">
</div>
<div class="control-group">
<input class="input-block-level" type="email" placeholder="Email ID" name="email" id="email">
</div>
<div class="control-group">
<input class="input-block-level" type="text" placeholder="Mobile Number" name="mobile" id="mobile">
</div>
<div class="control-group">
<textarea class="input-block-level" rows="10" name="message" placeholder="Your Message" id="message"></textarea>
</div>
<div class="control-group">
<p>
<input class="btn btn-danger btn-large" type="submit" value="Send Message">
</p>
<span class="loading"></span> </div>
</form>
here is the javascript
// JavaScript Document
$(document).ready(function() {
$("#phpcontactform").submit(function(e) {
e.preventDefault();
var name = $("#name");
var email = $("#email");
var mobile = $("#mobile");
var msg = $("#message");
var flag = false;
if (name.val() == "") {
name.closest(".control-group").addClass("error");
name.focus();
flag = false;
return false;
} else {
name.closest(".control-group").removeClass("error").addClass("success");
} if (email.val() == "") {
email.closest(".control-group").addClass("error");
email.focus();
flag = false;
return false;
} else {
email.closest(".control-group").removeClass("error").addClass("success");
} if (msg.val() == "") {
msg.closest(".control-group").addClass("error");
msg.focus();
flag = false;
return false;
} else {
msg.closest(".control-group").removeClass("error").addClass("success");
flag = true;
}
var dataString = "name=" + name.val() + "&email=" + email.val() + "&mobile=" + mobile.val() + "&msg=" + msg.val();
$(".loading").fadeIn("slow").html("Loading...");
$.ajax({
type: "POST",
data: dataString,
url: "http://localhost/myProject/HTML/contact.php",
cache: false,
success: function (d) {
alert("d: "+d);
$(".control-group").removeClass("success");
if(d == 'success') // Message Sent? Show the 'Thank You' message and hide the form
$('.loading').fadeIn('slow').html('<font color="green">Mail sent Successfully.</font>').delay(3000).fadeOut('slow');
else
$('.loading').fadeIn('slow').html('<font color="red">Mail not sent.</font>').delay(3000).fadeOut('slow');
}
});
return false;
});
$("#reset").click(function () {
$(".control-group").removeClass("success").removeClass("error");
});
})
And finally here is the php
<?php
echo "<script>console.log('Debug Objects:' );</script>";
$name = $_REQUEST["name"];
$email = $_REQUEST["email"];
$mobile = $_REQUEST["mobile"];
$msg = $_REQUEST["msg"];
echo "<script>";
echo "alert('this also works');";
echo "</script>";
$to = "myemail#gmail.com";
if (isset($email) && isset($name) && isset($msg)) {
$subject = $name."sent you a message via Raaga";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= "From: ".$name." <".$email.">\r\n"."Reply-To: ".$email."\r\n" ;
$msg = "From: ".$name."<br/> Email: ".$email ."<br/> Mobile: ".$mobile." <br/>Message: ".$msg;
echo "<script>alert('this maybe works');</script>";
$mail = mail($to, $subject, $msg, $headers);
if($mail)
{
echo 'success';
}
else
{
echo "<script>alert('name:'+$name);</script>";
echo 'failed';
}
}
echo "<script>alert('this finally works');</script>";
?>
I tried moving contact.php to the htdocs root but that didnt work. Have turned off all antivirus and firewalls but that didnt work either. Am at a loss. Thought php was supposed to work out of the box with xampp?
Okay so thanks to ADyson for the help. The issue was not that php isn't running, its that the mail server was not properly configured.

PHP mail sending doesn't works with this ajax code but works fine without ajax code, with echo in my php.I want response in same page

My HTML code. Here above the form I want to show the response like Email is sending, and after that Thankyou message.
<form id="main-contact-form" name="contact-form" method="post" action="sendemail.php">
<div class="form-group">
<input type="text" name="name" class="form-control" required="required" placeholder="Name"</div>
<div class="form-group">
<input type="email" name="email" class="form-control" required="required" placeholder="Email Id"></div>
<div class="form-group">
<textarea name="message" id="message" required="required" class="form-control" rows="8" placeholder="Your text here"></textarea></div>
<div class="form-group">
<input type="submit" name="submit" class="btn btn-submit" value="Submit"></div>
</form>
My PHP code. When I am using echo and without the ajax its working fine. But The response is coming in sendmail.php page. I want ajax response above the form in html page..
<?php
if(isset($_POST['submit'])){
$to = "sample#gmail.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.";
die();
}
?>
My Ajax code
var form = $('#main-contact-form');
form.submit(function(event){
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url: $(this).attr('action'),
beforeSend: function(){
form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn() );
}
}).done(function(data){
form_status.html('<p class="text-success">Thank you for contact us. As early as possible we will contact you</p>').delay(3000).fadeOut();
});
});
Your code doesn't send any data to the server and will perform a GET request, so your if(isset($_POST['submit'])) will always return false when an AJAX request is made. You need to update your JavaScript so the form data is serialised:
var form = $('#main-contact-form');
form.submit(function(event){
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url: $(this).attr('action'),
data: $(this).serialize(),
method: 'post',
beforeSend: function(){
form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn() );
}
}).done(function(data){
form_status.html('<p class="text-success">Thank you for contact us. As early as possible we will contact you</p>').delay(3000).fadeOut();
});
});
You could improve your PHP too, by changing the if to something like this so it just detects the post request:
if($_SERVER['REQUEST_METHOD'] === 'POST'){
// ...
}

PHP email form without Refreshing Page

I am trying to set up my page so that when I a form is submitted it emails and a message is displayed without refreshing the page.
I have tried to do this using jQuery/Ajax however I cannot get any emails sent now
Without the Ajax/jQuery, the PHP works just fine but just doesnt include the refresh feature
Any help would be appreciated
PHP (submitForm.php):
<?php
$name = isset($_POST['name']);
$email = isset($_POST['email']);
$phone = isset($_POST['phone']);
$message = isset($_POST['message']);
$feedback = '';
if($name && $email && $phone && $message) {
$name = ($_POST['name']);
$email = ($_POST['email']);
$phone = ($_POST['phone']);
$message = ($_POST['message']);
}
$to = "arshdsoni#gmail.com";
$subject = 'Soni Repairs - Support Request';
$body = <<<EMAIL
Hi There!
My name is $name.
Message: $message.
My email is: $email
Phone Number: $phone
Kind Regards
EMAIL;
$header = "From: $email";
if($_POST) {
if($name == '' || $email == '' || $phone == '' || $message == '') {
$feedback = "Nothing received!";
}
else {
mail($to, $subject, $body, $header);
$feedback = '*Message Received! You will receive a reply shortly!';
}
}
?>
jQuery/Ajax:
function submitForm() {
var name=document.getElementById('name').value;
var dataString = 'name'+ name;
$.ajax({
type:"post",
url:"submitForm.php",
cache:false,
success: function(html) {
$('#feedback').html(html);
}
});
return false;
}
FORM:
<form id="contact" action="#">
<h3>Get in Touch:</h3>
<h4><span id="star" class="glyphicon glyphicon-asterisk"></span>We aim to reply within 24 hours!</h4>
<fieldset>
<input name="name" placeholder="Your Name" type="text" tabindex="1" required>
</fieldset>
<fieldset>
<input name="email" placeholder="Your Email Address" type="email" tabindex="2" required>
</fieldset>
<fieldset>
<input name="phone" placeholder="Your Phone Number" type="tel" tabindex="3" required>
</fieldset>
<fieldset>
<textarea id="textarea" name="message" placeholder="Describe your problem...." tabindex="5" required></textarea>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="contact-submit submitBtn" data-submit="...Sending" "return submitForm();">Submit</button>
</fieldset>
</form>
Issues:
if you usedocument.getElementById you must use id on your elements
Add the data to your ajax request
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$( "#submitBtn" ).click(function( event ) {
alert('pressed');
//values
var name=document.getElementById('name').value;
var email=document.getElementById('email').value;
var phone=document.getElementById('phone').value;
var message=document.getElementById('message').value;
var dataString = {"name": name, "email":email, "phone": phone, "message":message}
$.ajax({
type:"post",
url:"submitForm.php",
data: dataString,
success: function(html) {
$('#feedback').html(html);
}
});
event.preventDefault();
});
});
</script>
</head>
<body>
<form id="contact" method="POST">
<h3>Get in Touch:</h3>
<h4><span id="star" class="glyphicon glyphicon-asterisk"></span>We aim to reply within 24 hours!</h4>
<fieldset>
<input id="name" placeholder="Your Name" type="text" tabindex="1" required>
</fieldset>
<fieldset>
<input id="email" placeholder="Your Email Address" type="email" tabindex="2" required>
</fieldset>
<fieldset>
<input id="phone" placeholder="Your Phone Number" type="tel" tabindex="3" required>
</fieldset>
<fieldset>
<textarea id="message" placeholder="Describe your problem...." tabindex="5" required></textarea>
</fieldset>
<fieldset>
<button name="submit" id="submitBtn">Submit</button>
</fieldset>
</form>
<div id="feedback"></div>
</body>
</html>
PHP
<?php
if(isset($_POST['name'], $_POST['email'], $_POST['phone'], $_POST['message'])){
//Post data
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
//mail settings
$to = "arshdsoni#gmail.com";
$subject = 'Soni Repairs - Support Request';
$body = <<<EMAIL
Hi There!
My name is $name.
Message: $message.
My email is: $email
Phone Number: $phone
Kind Regards
EMAIL;
if(mail($to, $subject, $body, $header)){
$feedback = '*Message sent! You will receive a reply shortly!';
}else{
$feedback = '*Message failed to send';
}
}else{
$feedback = 'Missing Params';
}
echo $feedback;
This is your ajax, where you went wrong
$.ajax({
type:"post",
url:"submitForm.php",
cache:false,
success: function(html) {
$('#feedback').html(html);
}
});
You forgot to include the data to be posted
$.ajax({
type:"post",
url:"submitForm.php",
cache:false,
data {
name: $('#name').val(),
email: $('#email').val(),
phone: $('#phone').val(),
message: $('#msg').val()
}
success: function(html) {
$('#feedback').html(html);
}
});
The keys name, email, message and phone should be as is; because you used $_POST['name'], $_POST['email'], $_POST['message'] and $_POST['phone'].
The calls$('#name').val(), $('#email').val(), $('#phone').val(), $('#message').val() have been made assuming that your input elements have ids name, email, message and phone respectively. JS uses ids rather than names.
Refer to jQuery Ajax documentation for more details.
I do not see you sending the data to PHP file anywhere in your AJAX code
NOTE: Use serialize() function if you want to send all the form data. Else send it separately like
var formDatas = {name:"name",email:"emailID"};
function submitForm() {
var name=document.getElementById('name').value;
var dataString = 'name'+ name;
var formDatas = $('#formID').serialize(); // Send form data
$.ajax({
type:"post",
url:"submitForm.php",
data : {datas : formDatas }
cache:false,
success: function(html) {
$('#feedback').html(html);
}
});
return false;
}
Your references
jQuery Serialize()
jQuery ajax()

PHP Contact Form Status Update in DIV

Sounds like an odd question but here is what I have. The php has a snippet at the end that says success or failure makes a white screen to display this, I really want it to pop up right under the submit button on the same page rather than redirect the entire page.
I assume I could direct that to an empty <div>?
mail.php:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$formcontent=" From: $name \n Phone: $phone \n Message: $message";
$recipient = "art#jamisonsigns.com";
$subject = "Web Contact Form";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Thank You!" . " -" . "<a href='index.html' style='text-decoration:none;color:#ff0099;'> Return Home</a>";
?>
With a simple HTML form on my website as follows:
<form class="contact-form" form action="mail.php" method="POST">
<fieldset>
<input type="text" class="name" id="name" placeholder="Name...">
</fieldset>
<fieldset>
<input type="email" class="email" id="email" placeholder="Email...">
</fieldset>
<fieldset>
<input type="text" class="phone" id="phone" placeholder="Phone...">
</fieldset>
<fieldset>
<textarea name="message" id="message" cols="30" rows="4" placeholder="Message.."></textarea>
</fieldset>
<fieldset>
<input type="submit" class="button" id="button" value="Send Message">
</fieldset>
</form>
You need to submit the form with Ajax. Then on success insert the message in the html.
$('#button').click(function(event) {
event.preventDefault();
var formdata = $('#formID').serializeArray();
var url = '/urltopost.php';
$.ajax(
{
url : url,
type: "POST",
data: formdata,
success:function(data, textStatus, jqXHR)
{
//data: return data from server
console.log("STATUS:" + textStatus + " | jqXHR:" + jqXHR + " | data:" + data);
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
alert("ERROR:" + " -> " +errorThrown);
}
});
});
Here it is a tutorial if you need..

Ajax contact form not working

I am working on a website with an Ajax contact form. Tried a lot, it successfully sends a mail without headers below is my code please help me to fix this
code
<div class="form">
<div class="title">
<h2 class="orange"><span class="orange">Contact</span> US</h2>
</div>
<div class="height15"></div>
<div id="return_message"></div>
<div class="field">
<label>First Name:</label>
<input name="name" type="text" />
</div>
<div class="field">
<label>Phone Number:</label>
<input name="phone" type="text" />
</div>
<div class="field">
<label>Email Address:</label>
<input name="email" type="text" />
</div>
<label>Message:</label>
<textarea name="message" cols="" rows=""></textarea>
<div class="clear"></div>
<a class="org_btn more submit" id="submit" href="#.">Submit</a> </div>
<script language="javascript">
$(document).ready(function() {
$("#menu_btn").click(function(){
$("#sub_menu").slideToggle("slow");
});
//Contact us form validation
$('#return_message').hide();
$('#submit').click(function(event){
var name = $('#name').val();
var phone = $('#phone').val();
var email = $('#email').val();
var message = $('#message').val();
if( (name=='') || (phone=='') || (email=='') || (message=='') )
{
$('#name').addClass('error_active');
$('#phone').addClass('error_active');
$('#email').addClass('error_active');
$('#message').addClass('error_active');
}
else
{
var regex = /^([a-zA-Z0-9_\.\-\+])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(!regex.test(email))
{
alert("Please Enter valid email address");
$('#email').addClass('error_active');
}
else
{
$.ajax(
{
type: 'POST',
data: ({name : name, phone : phone, email : email, message : message}),
url: 'send_mail.php',
success: function(data)
{
if(data)
{
$('#return_message').show('slow').html("<p>Email has been sent...</p>");
$('#name').val('');
$('#phone').val('');
$('#email').val('');
$('#message').val('');
$('#name').removeClass('error_active');
$('#phone').removeClass('error_active');
$('#email').removeClass('error_active');
$('#message').removeClass('error_active');
}
else
{
$('#return_message').show('slow').html("<p>Email has not been sent...</p>");
}
}
});
}
}
});
});
</script>
php code
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$to = "info#kodspider.com"; // Please put your email addres.
$subject = "Marthoman Vidyapeedom"; //Please put subject of your email.
if($phone!='')
{
$message2 = $message.'\r\nPhone:'.$phone;
}
else
{
$message2 = $message;
}
$message = $message.'\r\nPhone:'.$phone;
$headers = "From: ".$email;
$sent = mail( $to, $subject, $message2, $headers );
if($sent)
{
echo "success";
}
else
{
echo "error";
}
?>
you have given
<input name="name" type="text" />
but in jquery your calling
$('#name').val('')
in jquery # selector is used only for id
make change
<input name="name" id="name" type="text" />
for more details in jquery read this

Categories