Confirmation message not showing after form submission - jQuery/Ajax - php

I'm working with the tutorial here: http://designwoop.com/2012/07/tutorial-coding-a-jquery-popup-modal-contact-form/ and the form sending the data correctly. However, after clicking submit, the form just shows the "sending" message rather than showing the confirmation message. This happens when I test locally and on my development environment. I don't see any error messages in my console.
This is my first time working with ajax and I am a newbie with jQuery/JavaScript. Not sure what the problem is here. It seems that it is not reading the data as true. I changed True to False to see what would happen and it still doesn't work. Can anyone help, please?
FYI I am implementing this on a site that already calls the 1.3.2 jQuery library and can not remove the reference, so I have to use noConflict. This doesn't work when I reference only the older library.
My goal is to create a modal that pops up when a user enters the website, but not if a cookie is set or if there is already a specific div on the page they enter through.
Here are the scripts:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="/wcsstore/CVWEB/images/home/js/jquery.fancybox.js?v=2.0.6"></script>
<script type="text/javascript">
var jQuery_1_7_2 = jQuery.noConflict(true);
function validateEmail(email) {
var reg = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return reg.test(email);
}
jQuery_1_7_2(document).ready(function(){
var emailFormExists = jQuery_1_7_2('#e2ma_signup_form');
if (document.cookie.indexOf('visited=true') == -1 && !(emailFormExists.length)){
var fifteenDays = 1000*60*60*24*15;
var expires = new Date((new Date()).valueOf() + fifteenDays);
document.cookie = "visited=true;expires=" + expires.toUTCString();
jQuery_1_7_2.fancybox({width:"100%", inline:true, href:"#inline"});
}
else
{
jQuery_1_7_2('#e2ma_signup_form').length
var fifteenDays = 1000*60*60*24*15;
var expires = new Date((new Date()).valueOf() + fifteenDays);
document.cookie = "visited=true;expires=" + expires.toUTCString();
}
jQuery_1_7_2("#contact").submit(function() { return false; });
jQuery_1_7_2("#send").on("click", function(){
var emailval = jQuery_1_7_2("#email").val();
var mailvalid = validateEmail(emailval);
if(mailvalid == false) {
jQuery_1_7_2("#email").addClass("error");
}
else if(mailvalid == true){
jQuery_1_7_2("#email").removeClass("error");
}
if(mailvalid == true) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
jQuery_1_7_2("#send").replaceWith("<em>sending...</em>");
jQuery_1_7_2.ajax({
type: 'POST',
url: 'http://lcoawebservices.com/scripts/email-opt-in.php',
data: jQuery_1_7_2("#contact").serialize(),
success: function(data) {
if(data == "true") {
jQuery_1_7_2("#contact").fadeOut("fast", function(){
jQuery_1_7_2(this).before("<p><strong>Thanks for opting in!</strong></p>");
setTimeout("jQuery_1_7_2.fancybox.close()", 1000);
});
}
}
});
}
});
});
</script>
and here is the HTML:
<div id="inline">
<h2>Join the our mailing list!</h2>
<form id="contact" name="contact" action="#" method="post">
<label for="email">Your E-mail</label>
<input type="email" id="email" name="email" class="txt">
<button id="send">Send E-mail</button>
</form>
</div>
here is the php (which i am also new to)
<?php
$sendto = "llantz#lecreuset.com";
$usermail = $_POST['email'];
$content = nl2br($_POST['msg']);
$subject = "New Feedback Message";
$headers = "From: " . strip_tags($usermail) . "\r\n";
$headers .= "Reply-To: ". strip_tags($usermail) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html;charset=utf-8 \r\n";
$msg = "<html><body style='font-family:Arial,sans-serif;'>";
$msg .= "<h2 style='font-weight:bold;border-bottom:1px dotted #ccc;'>New User Feedback</h2>\r\n";
$msg .= "<p><strong>Sent by:</strong> ".$usermail."</p>\r\n";
$msg .= "<p><strong>Message:</strong> ".$content."</p>\r\n";
$msg .= "</body></html>";
if(#mail($sendto, $subject, $msg, $headers)) {
echo "true";
} else {
echo "false";
}
?>

I figured it out - this is due to a cross-domain access problem. I do not have the answer on how to solve it yet but wanted to post this so no one else spends time looking at my code, trying to fix it.

Related

jQuery AJAX reaches memory stack limit upon just 18 args

So I have a form that is submitted through jQuery AJAX and around 18 arguments are passed to a php file. Now whenever I try to submit the form, stack limit is reached with that many arguments. But the moment I cut off like half the arguments, the forms works fine and email is received. But the email I receive does not have any body.
AJAX:
$.ajax({
url: "sendemail.php",
method: "post",
data: {
name: name,
email: email,
number: number,
username: username,
country: country,
cname: cname,
ctype: ctype,
ctheme: ctheme,
domainname: domainname,
webhosting: webhosting,
seo: seo,
gadvertising: gadvertising,
cmarketing: cmarketing,
ptech: ptech,
details: details,
description: description
},
success: function () {
alert("Hey brotha");
}
}).fail(function () {
$("#confdiv").html("<p class='alert alert-danger'>There was an error submitting your form. Please try again later or contact us at <a href='mailto:sobanr4#gmail.com'>EMAIL</a></p>");
window.scrollTo(0, 100);
});
the php script is:
<?php
if (isset($_POST['name']) && $_POST['name'] != "") {
$to = "sobanr4#gmail.com";
$subject = "Website Order Request";
$headers = "From: <".$_POST['email'].">\r\n";
$headers .= "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$body = "<html>
<head>
<title>Order Request - ".$_POST['name']."</title>
</head>
<body>
<p>NAME: ".$_POST['name']."</p>
<p>EMAIL: ".$_POST['email']."</p>
<p>NUMBER: ".$_POST['number']."</p>
<p>USERNAME: ".$_POST['username']."</p>
<p>COUNTRY: ".$_POST['country']."</p>
<p>COMPANY NAME: ".$_POST['cname']."</p>
<p>TYPE: ".$_POST['ctype']."</p>
<p>THEME: ".$_POST['ctheme']."</p>
<p>DOMAIN NAME: ".$_POST['domainname']."</p>
<p>WEB HOSTING: ".$_POST['webhosting']."</p>
<p>SEO: ".$_POST['seo']."</p>
<p>GOOGLE ADVERTISING: ".$_POST['gadvertising']."</p>
<p>CONTENT MARKETING: ".$_POST['cmarketing']."</p>
<p>PERMANENT TECHNICIAN: ".$_POST['ptech']."</p>
<br><br><br>
<p>DETAILS: ".$_POST['details']."</p>
<br><br><br>
<p>DESCRIPTION: ".$_POST['description']."</p>
</body>
</html>";
if (mail($to,$subject,$$body,$headers)) {
echo 1;
} else {
echo 0;
};
}
?>
The form can be found here: http://www.henryspike.tk/testform
Ok, I think it must be the radio buttons.
You get their value like this:
var seo = $("#seo").val();
var gadvertising = $("#gadvertising").val();
var cmarketing = $("#cmarketing").val();
var ptech = $("#ptech").val();
But it should be like this:
var seo = $("#seo:checked").val();
var gadvertising = $("#gadvertising:checked").val();
var cmarketing = $("#cmarketing:checked").val();
var ptech = $("#ptech:checked").val();
I have not tested this... but it is easy for you to try.
SOLUTION:
All this mess and in the end the problem was that one of the variables in my javascript were misspelled as 'ctheme' instead of 'theme'.
And the blank email issue was resolved because I typed '$$body' instead of '$body'.
Anyways, thanks every one for help, especially #KIKOSoftware
P.S: I guess its a welcome to the world of programming.

PHP Mail not sending mail with AJAX [duplicate]

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 6 years ago.
Good day, so I've stumbled upon this very easy problem for you pros out there. To note, I have been researching for this problem but I just don't understand why this is not working. So what I'm doing is I'm trying to make a review form successfully send a mail to my email. So here's my code:
HTML
<input type="text" id="his-name" name="his-name" placeholder="His name*">
<input type="text" id="her-name" name="her-name" placeholder="Her name*">
<input type="text" id="location" name="location" placeholder="Location of honeymoon*">
<textarea id="fav-moment" name="fav-moment" placeholder="Favorite moment during the trip"></textarea>
<textarea id="review" name="review" placeholder="Please write a short review of your experience*"></textarea>
<p>Upload few pictures from your honeymoon <span style="display: block; font-size:.7em">Please upload only a maximum of 4 photos</span></p><br/>
<form action="<?php echo get_template_directory_uri(); ?>/upload.php?sessionid=<?php echo $_SESSION['sessionid'] ?>"
class="dropzone" id="my-awesome-dropzone"></form>
JS
$(document).ready(function () {
showMenu();
$('#submit-feedback').click(function (e) {
e.preventDefault();
ajax_send_feedback();
});
function ajax_send_feedback() {
$('#contact-msg-f').html('<i style="font-size:2em;" class="fa fa-spinner fa-spin"></i>');
var errors = new Array();
errors = validate_feedback_form();
if (errors.length != 0) {
display_feedback_errors(errors);
feedbackDelivered(0);
return;
}
else {
// Send data for server validation
$.get("http://atravelduet.com/process-review-form.php", {
hisname: $('#his-name').val(),
hername: $('#her-name').val(),
location: $('#location').val(),
favmoment: $('#fav-moment').val(),
review: $('#review').val(),
url: $('#url').val()
}).done(function (response) {
if (!response) {
feedbackDelivered(1);
clearFields(); **//THIS IS NOT WORKING TOO :(**
}
else {
var errros = new Array();
errors = $.parseJSON(response);
if (errors.length != 0) {
display_feedback_errors(errors);
feedbackDelivered(0);
}
}
});
}
}
function feedbackDelivered(res) {
if (res == 1) {
$('#contact-msg-f').html('<span style="color:#00ff00;">Message Sent!</span>');
}
else {
$('#contact-msg-f').html('<span style="color:#ff0000;">Please correct the fields marked red!</span>');
}
}
PHP
<?php
$email0 = 'codeaxiscom#gmail.com';
$email1 = 'jjmaranga05#gmail.com';
$his_name = $_POST['hisname'];
$her_name = $_POST['hername'];
$location = $_POST['location'];
$fav_moment = $_POST['favmoment'];
$review = $_POST['review'];
$body = <<< EOD
<br><hr><br>
His Name: $his_name<br>
Her Name: $her_name<br>
Location: $location<br>
Favorite Moment: $fav_moment<br>
Review: $review<br>
EOD;
$headers = "From: calcutt5#box996.bluehost.com\r\n";
$headers .= "Content-type: text/html\r\n";
$emailSubject = "$his_name and $her_name Honeymoon Review";
$emailTo = $email1;
if(mail($emailTo, $emailSubject, $body, $headers))
echo "Successful";
else
echo "Unsuccessful";
?>
At first you have an error because the mail() function returns FALSE. So no email is send.
Try to put "From" header after content-type like this
$headers = "Content-type: text/html\r\n";
$headers .= "From: calcutt5#box996.bluehost.com\r\n";
And check if it is working now. If it is not try completely comment the line with From header and check if it returns success and if you get an email.
The problem maybe that you are using bad "From" header. In most cases the email should be like the domain were the mail is sent from.
In addition i suggest you use for example a PHPMailer which is not hard to configure and it works much better and you have an error log so you can easily debug it.

Cant get google recaptcha v2 to prevent form submission

So I can successfully get the captcha to validate, using the following code.
</p>
<?php
if(isset($_POST['g-recaptcha-response'])){
echo verify($_POST['g-recaptcha-response']);
}
function verify($response) {
$ip = $_SERVER['blank']; //server Ip
$key="secretkey"; // Secret key
//Build up the url
$url = 'https://www.google.com/recaptcha/api/siteverify';
$full_url = $url.'?secret='.$key.'&response='.$response.'&remoteip='.$ip;
//Get the response back decode the json
$data = json_decode(file_get_contents($full_url));
//Return true or false, based on users input
if(isset($data->success) && $data->success == true) {
return True;
}
return False;
}
?>
<p style="text-align: justify;">
<script type="text/javascript">
function verify(){
var serializedValues = jQuery("#infoForm").serialize();
jQuery.ajax({ type: 'POST',url:"verify.php",data: serializedValues,success:function(result){
if(result){
$('#show').html('Your Form Successfully Submitted');
$('.formwrap').hide(result);
return true;
}
}});
$('#show').html('Please Enter Valid Captcha');
return false;
}
var onloadCallback = function() {
grecaptcha.render('captcha_ele', {
'sitekey' : 'Enter Your Site Key Here', // Site key
});
};
</script>
However, when I click submit, regardless of what the captcha says, form will still submit. My email form process is as follows...
<!-- language: lang-css -->
$("#blank").submit(function() {
$.post('assets/php/email-process.php', {name: $('#name').val(), email: $('#email').val(), message: $('#message').val(), myFormSubmitted: 'yes'},
function(data) {
$("#formResponse").html(data).fadeIn('100');
$('#name, #email, #message').val(''); /* Clear the inputs */
}, 'text');
return false;
});
<?php
if ($_POST['leaveblank'] != '' or $_POST['dontchange'] != 'http://') {
// display message that the form submission was rejected
}
else {
// accept form submission
$to = 'info#blank'; // Replace with your email
$subject = 'Message from website visitor'; // Replace with your $subject
$headers = 'From: ' . $_POST['email'] . "\r\n" . 'Reply-To: ' . $_POST['email'];
$message = 'Name: ' . $_POST['name'] . "\n" .
'E-mail: ' . $_POST['email'] . "\n" .
'Subject: ' . $_POST['subject'] . "\n" .
'Message: ' . $_POST['message'];
mail($to, $subject, $message, $headers);
if( $_POST['copy'] == 'on' )
{
mail($_POST['email'], $subject, $message, $headers);
}
echo 'Thank you for your Email. We will get in touch with you very soon.';
}
?>
I use this which works for me. Put a js function in your form submit to validate the re-captcha:
<form action="/sign-visitors-log/" method="post" id="VisitorsLogForm" onsubmit="return validateRecaptcha();">
Then some js to stop the form submit if the user didn't tick the check box:
function validateRecaptcha() {
var response = grecaptcha.getResponse();
if (response.length === 0) {
alert("not validated");
return false;
} else {
alert("validated");
return true;
}
}
You can swap out the alerts for toast or as you are doing some elements on the page.
HTH
In a separate js file (at least: no inline call to a function), you have to check if the captcha can validate. Like so:
jquery('form').on('submit',function(e){
if(grecaptcha.getResponse() === "") {
e.preventDefault();
alert('Error: \n please validate the Captcha test');
}
});
You don't have to check if the test passive as true, you have already prevented the form to be sent with this method.
This is a simpler model that does the job
document.querySelector(".form").addEventListener("submit", (event)=>{
const response = grecaptcha.getResponse();
if (response.length === 0) {
event.preventDefault();
alert("Please verify that you are human!");
}
})
<!--reCAPTCHA v2 -->
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<form action="/" method="POST" class"form">
<!--Please register as a developer and add "your_site_key" you will find it on https://www.google.com/recaptcha/admin/create-->
<div class="g-recaptcha" data-sitekey="your_site_key"></div>
</form>

Post error report by pressing a button jQuery not working

Small problem here, I need to place a button on my 404 page to ask people to submit an error.
The problem is that nothing is actually happens, I mean no mail is received and no errors are displayed, so I am confused.
My report is very basic, it collects all data of what my user did before getting 404
$site = "mySite.com";
$email = "donotreply#mySite.com";
$http_host = $_SERVER['HTTP_HOST'];
$server_name = $_SERVER['SERVER_NAME'];
$remote_ip = $_SERVER['REMOTE_ADDR'];
$request_uri = $_SERVER['REQUEST_URI'];
$cookie = $_SERVER["HTTP_COOKIE"];
$http_ref = $_SERVER['HTTP_REFERER'];
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$error_date = date("D M j Y g:i:s a T");
$subject = "404 Alert";
$headers = "Content-Type: text/plain"."\n";
$headers .= "From: ".$site." <".$email.">"."\n";
$message = "404 Error Report for ".$site."\n";
$message .= "Date: ".$error_date."\n";
$message .= "Requested URL: http://".$http_host.$request_uri."\n";
$message .= "Cookie: ".$cookie."\n";
$message .= "Referrer: ".$http_ref."\n";
$message .= "User Agent: ".$user_agent."\n";
$message .= "IP Address: ".$remote_ip."\n";
$message .= "Whois: http://ws.arin.net/cgi-bin/whois.pl?queryinput=".$remote_ip;
this is my form, all fields are hidden that are placed in the same file along with php code above
<form name="form" method="POST" id="report-form">
<div class="form">
<input type="hidden" name="message" value="$message">
<div class="done">
<p><strong>Thank you!</strong></p>
</div>
<div class="error">
<p><strong>Error!</strong> Sorry, something went wrong, please try again.</p>
</div>
<input type="hidden" name="visitor" value="">
<input type="hidden" name="submitted" value="submitted">
<input type="submit" name="submit" value="Submit" class="formSubmit" />
</div>
</form>
<script type="text/javascript" src="js/report_validation.js"><\/script>
here is my jQuery validation script, which I am trying to use, which is in the separate file named report_validation.js in js folder
$(document).ready ( function() {
$('.formSubmit').click(function() {
// Store values in variables
var form = $(this).closest('form');
var message = form.find('input[name=message]');
var submitted = form.find('input[name=submitted]');
var visitor = form.find('input[name=visitor]');
// Organize data
var data = 'message=' + message.val() + '&submitted=' + submitted.val() + '&visitor=' + visitor.val();
var request = $.ajax({
type: "POST",
url: "includes/report_form_mail.php",
data: data,
cache: false,
success: function (html) {
if (html == "true") {
form.find('.done').fadeIn(500).delay(4000).fadeOut(500);
}
},
error: function(jqXHR, textStatus, error) {
alert("Form Error: " + error);
}
});
return false;
});
});
here is my mailing script, which is also placed in the separate file and named report_form_mail.php in my incudes folder
// Check if form was submitted
if ($_POST['submitted'] && $_POST['visitor'] == '') {
// If valid, store values in variables
$site = "mySite.com";
$email = "donotreply#mySite.com";
$mes = stripslashes($_POST['message']);
$subject = "404 Alert";
$headers = "Content-Type: text/plain"."\n";
$headers .= "From: ".$site." <".$email.">"."\n";
$message = "Message: $mes";
// Send email
$sent = mail($email, $subject, $message, $headers);
if($sent) {
echo json_encode(true);
} else {
echo "Error: Mail could not be send.";
exit();
}
} else {
echo "Error: There was a problem with submitting the form";
exit();
}
Please help me to figure it all out
I have actually found an error myself.
The jQuery was not loaded to the page correctly so I have corrected it and my form works perfectly fine.
Thanks to all

jQuery Mobile PHP Form - Get Checked Radio Button Value

I am using a jQuery Mobile Form script I found online. Everything is working fine, except the input="radio" buttons. I am not a jQuery expert by any means, so I am hoping someone here can help me.
THE SETUP
The form script contains 3 files: send.php, contact.js, and the mobile markup. Examples of the problematic pieces of code are below:
Mobile Markup:
<div data-role="fieldcontain">
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Doctor Type:</legend>
<input type="radio" name="doctortype" id="dmd" value="dmd"/>
<label for="dd">D.D.</label>
<input type="radio" name="doctortype" id="dds" value="dds" />
<label for="do">D.O.</label>
</fieldset>
</div>
Contact.js
$('#send-feedback').live("click", function() {
var url = 'api/send.php';
var error = 0;
var $contactpage = $(this).closest('.ui-page');
var $contactform = $(this).closest('.contact-form');
$('.required', $contactform).each(function (i) {
if ($(this).val() === '') {
error++;
}
}); // each
if (error > 0) {
alert('Please fill in all the mandatory fields. Mandatory fields are marked with an asterisk *.');
} else {
var doctortype = $contactform.find('input[name="doctortype"]').val();
var firstname = $contactform.find('input[name="firstname"]').val();
var surname = $contactform.find('input[name="surname"]').val();
var dob = $contactform.find('input[name="dob"]').val();
var zip = $contactform.find('input[name="zip"]').val();
var how = $contactform.find('select[name="how"]').val();
var email = $contactform.find('input[name="email"]').val();
var message = $contactform.find('textarea[name="message"]').val();
//submit the form
$.ajax({
type: "GET",
url: url,
data: {doctortype:doctortype, firstname:firstname, surname:surname, dob:dob, zip:zip, how:how, email:email, message:message},
success: function (data) {
if (data == 'success') {
// show thank you
$contactpage.find('.contact-thankyou').show();
$contactpage.find('.contact-form').hide();
} else {
alert('Unable to send your message. Please try again.');
}
}
}); //$.ajax
}
return false;
});
Send.php
<?php
header('content-type: application/json; charset=utf-8');
if (isset($_GET["firstname"])) {
$doctortype = strip_tags($_GET['doctortype']);
$firstname = strip_tags($_GET['firstname']);
$surname = strip_tags($_GET['surname']);
$dob = strip_tags($_GET['dob']);
$zip = strip_tags($_GET['zip']);
$how = strip_tags($_GET['how']);
$email = strip_tags($_GET['email']);
$message = strip_tags($_GET['message']);
$header = "From: ". $firstname . " <" . $email . ">";
$ip = $_SERVER['REMOTE_ADDR'];
$httpref = $_SERVER['HTTP_REFERER'];
$httpagent = $_SERVER['HTTP_USER_AGENT'];
$today = date("F j, Y, g:i a");
$recipient = 'MYEMAIL#gmail.com';
$subject = 'Contact Form';
$mailbody = "
Doctor Type: $doctortype
First Name: $firstname
Last Name: $surname
Date of Birth: $dob
Zip Code: $zip
How Did You Learn About Us: $how
Message: $message
IP: $ip
Browser info: $httpagent
Referral: $httpref
Sent: $today
";
$result = 'success';
if (mail($recipient, $subject, $mailbody, $header)) {
echo json_encode($result);
}
}
?>
THE RUB
The form works fine by itself. User fills out info, clicks "Send", and I receive an email with the information. However, I am not able to get the value of the checked radio to parse and send.
I've spent numerous hours trying to get the checked radio value to pass through the necessary steps.
And therein lies the problem. I've looked at countless similar posts on SO and other various places online, including the jQuery Mobile documentation. To no avail.
Any help is much appreciated!
What is your jQuery doing? It seems unnecessary to do any jQuery/JavaScript. The form should send the value of your radio button to $_GET['doctortype'] without it (assuming your form method is get).

Categories