My form cant send to my email, its say ERROR 500 at form/contact.php , anyone can help me where the problem?
this is my form:
this is my form/contact.php
this is my assets/vendor/php-email-form/php-email-form.php
<?php
// receive form submission data
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
// set the email details
$to = 'example#example.id';
$headers = "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";
// send the email and check for errors
if (mail($to, $subject, $message, $headers)) {
// email sent successfully
echo "Email sent!";
} else {
// email sending failed
echo "Error: Unable to send email";
}
?>
this is my assets/vendor/php-email-form/validate.js
(function () {
"use strict";
let forms = document.querySelectorAll('.php-email-form');
forms.forEach( function(e) {
e.addEventListener('submit', function(event) {
event.preventDefault();
let thisForm = this;
let action = thisForm.getAttribute('action');
let recaptcha = thisForm.getAttribute('data-recaptcha-site-key');
if( ! action ) {
displayError(thisForm, 'The form action property is not set!')
return;
}
thisForm.querySelector('.loading').classList.add('d-block');
thisForm.querySelector('.error-message').classList.remove('d-block');
thisForm.querySelector('.sent-message').classList.remove('d-block');
let formData = new FormData( thisForm );
if ( recaptcha ) {
if(typeof grecaptcha !== "undefined" ) {
grecaptcha.ready(function() {
try {
grecaptcha.execute(recaptcha, {action: 'php_email_form_submit'})
.then(token => {
formData.set('recaptcha-response', token);
php_email_form_submit(thisForm, action, formData);
})
} catch(error) {
displayError(thisForm, error)
}
});
} else {
displayError(thisForm, 'The reCaptcha javascript API url is not loaded!')
}
} else {
php_email_form_submit(thisForm, action, formData);
}
});
});
function php_email_form_submit(thisForm, action, formData) {
fetch(action, {
method: 'POST',
body: formData,
headers: {'X-Requested-With': 'XMLHttpRequest'}
})
.then(response => {
if( response.ok ) {
return response.text()
} else {
throw new Error(`${response.status} ${response.statusText} ${response.url}`);
}
})
.then(data => {
thisForm.querySelector('.loading').classList.remove('d-block');
if (data.trim() == 'OK') {
thisForm.querySelector('.sent-message').classList.add('d-block');
thisForm.reset();
} else {
throw new Error(data ? data : 'Form submission failed and no error message returned from: ' + action);
}
})
.catch((error) => {
displayError(thisForm, error);
});
}
function displayError(thisForm, error) {
thisForm.querySelector('.loading').classList.remove('d-block');
thisForm.querySelector('.error-message').innerHTML = error;
thisForm.querySelector('.error-message').classList.add('d-block');
}
})();
i dont know where the problem, can anyone help me?
Related
I am new to PHP and would really love some help... I'm banging my head against a wall at this point. All I am trying to do is get a working contact form done... using php-mailer. Emails are coming through as they should, however the problem lies with the the message displayed after clicking submit. As the emails are being sent successfully, the message should read "Your message has been sent to us.", if it doesnt go through the message should read "error, there was an error sending your message." The message after the submission displays the error message no matter what. I tried combing the internet to figure it out to no avail, hopefully you guys can help out.
I included the JS, PHP, and Form.
Thanks in advance.
<form class="contact-form" action="php/contact-form.php" method="POST">
<div class="contact-form-success alert alert-success d-none mt-4">
<strong>Success!</strong> Your message has been sent to us.
</div>
<div class="contact-form-error alert alert-danger d-none mt-4">
<strong>Error!</strong> There was an error sending your message.
<span class="mail-error-message text-1 d-block"></span>
</div>
<!-- ...... -->
</form>
<?php
namespace PortoContactForm;
session_cache_limiter('nocache');
header('Expires: ' . gmdate('r', 0));
header('Content-type: application/json');
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'php-mailer/src/PHPMailer.php';
require 'php-mailer/src/SMTP.php';
require 'php-mailer/src/Exception.php';
// Step 1 - Enter your email address below.
$email = 'alex#alexleloup.com';
// If the e-mail is not working, change the debug option to 2 | $debug = 2;
$debug = 1;
// If contact form don't has the subject input change the value of subject here
$subject = ( isset($_POST['subject']) ) ? $_POST['subject'] : 'Define subject in php/contact-form.php line 29';
$message = '';
foreach($_POST as $label => $value) {
$label = ucwords($label);
// Use the commented code below to change label texts. On this example will change "Email" to "Email Address"
// if( $label == 'Email' ) {
// $label = 'Email Address';
// }
// Checkboxes
if( is_array($value) ) {
// Store new value
$value = implode(', ', $value);
}
$message .= $label.": " . htmlspecialchars($value, ENT_QUOTES) . "<br>\n";
}
$mail = new PHPMailer(true);
try {
$mail->SMTPDebug = $debug; // Debug Mode
// Step 2 (Optional) - If you don't receive the email, try to configure the parameters below:
//$mail->IsSMTP(); // Set mailer to use SMTP
//$mail->Host = 'mail.alexleloup.com'; // Specify main and backup server
//$mail->SMTPAuth = true; // Enable SMTP authentication
//$mail->Username = ''; // SMTP username
//$mail->Password = ''; // SMTP password
//$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
//$mail->Port = 587; // TCP port to connect to
$mail->AddAddress($email); // Add another recipient
//$mail->AddAddress('person2#domain.com', 'Person 2'); // Add a secondary recipient
//$mail->AddCC('person3#domain.com', 'Person 3'); // Add a "Cc" address.
//$mail->AddBCC('person4#domain.com', 'Person 4'); // Add a "Bcc" address.
// From - Name
$fromName = ( isset($_POST['name']) ) ? $_POST['name'] : 'Website User';
$mail->SetFrom($email, $fromName);
// Reply To
if( isset($_POST['email']) ) {
$mail->AddReplyTo($_POST['email'], $fromName);
}
$mail->IsHTML(true); // Set email format to HTML
$mail->CharSet = 'UTF-8';
$mail->Subject = $subject;
$mail->Body = $message;
$mail->Send();
$arrResult = array ('response'=>'success');
} catch (Exception $e) {
$arrResult = array ('response'=>'error','errorMessage'=>$e->errorMessage());
} catch (\Exception $e) {
$arrResult = array ('response'=>'error','errorMessage'=>$e->getMessage());
}
if ($debug == 0) {
echo json_encode($arrResult);
}
Name: View - Contact
Written by: Okler Themes - (http://www.okler.net)
Theme Version: 8.0.0
*/
(function($) {
'use strict';
/*
Custom Rules
*/
// No White Space
$.validator.addMethod("noSpace", function(value, element) {
if( $(element).attr('required') ) {
return value.search(/[a-zA-Z0-9À-žа-яА-ЯёЁα-ωΑ-Ω\s\u0621-\u064A\u0660-\u0669 ]/i) == 0;
}
return true;
}, 'Please fill this empty field.');
/*
Assign Custom Rules on Fields
*/
$.validator.addClassRules({
'form-control': {
noSpace: true
}
});
/*
Contact Form: Basic
*/
$('.contact-form').each(function(){
$(this).validate({
submitHandler: function(form) {
var $form = $(form),
$messageSuccess = $form.find('.contact-form-success'),
$messageError = $form.find('.contact-form-error'),
$submitButton = $(this.submitButton),
$errorMessage = $form.find('.mail-error-message'),
submitButtonText = $submitButton.val();
$submitButton.val( $submitButton.data('loading-text') ? $submitButton.data('loading-text') : 'Loading...' ).attr('disabled', true);
// Fields Data
var formData = $form.serializeArray(),
data = {};
$(formData).each(function(index, obj){
data[obj.name] = obj.value;
});
// Google Recaptcha v2
if( data["g-recaptcha-response"] != undefined ) {
data["g-recaptcha-response"] = $form.find('#g-recaptcha-response').val();
}
// Ajax Submit
$.ajax({
type: 'POST',
url: $form.attr('action'),
data: data
}).always(function(data, textStatus, jqXHR) {
$errorMessage.empty().hide();
if (data.response == 'success') {
// Uncomment the code below to redirect for a thank you page
// self.location = 'thank-you.html';
$messageSuccess.removeClass('d-none');
$messageError.addClass('d-none');
// Reset Form
$form.find('.form-control')
.val('')
.blur()
.parent()
.removeClass('has-success')
.removeClass('has-danger')
.find('label.error')
.remove();
if (($messageSuccess.offset().top - 80) < $(window).scrollTop()) {
$('html, body').animate({
scrollTop: $messageSuccess.offset().top - 80
}, 300);
}
$form.find('.form-control').removeClass('error');
$submitButton.val( submitButtonText ).attr('disabled', false);
return;
} else if (data.response == 'error' && typeof data.errorMessage !== 'undefined') {
$errorMessage.html(data.errorMessage).show();
} else {
$errorMessage.html(data.responseText).show();
}
$messageError.removeClass('d-none');
$messageSuccess.addClass('d-none');
if (($messageError.offset().top - 80) < $(window).scrollTop()) {
$('html, body').animate({
scrollTop: $messageError.offset().top - 80
}, 300);
}
$form.find('.has-success')
.removeClass('has-success');
$submitButton.val( submitButtonText ).attr('disabled', false);
});
}
});
});
/*
Contact Form: Advanced
*/
$('#contactFormAdvanced').validate({
onkeyup: false,
onclick: false,
onfocusout: false,
rules: {
'captcha': {
captcha: true
},
'checkboxes[]': {
required: true
},
'radios': {
required: true
}
},
errorPlacement: function(error, element) {
if (element.attr('type') == 'radio' || element.attr('type') == 'checkbox') {
error.appendTo(element.closest('.form-group'));
} else {
error.insertAfter(element);
}
}
});
/*
Contact Form: reCaptcha v3
*/
$('.contact-form-recaptcha-v3').each(function(){
$(this).validate({
submitHandler: function(form) {
var $form = $(form),
$messageSuccess = $form.find('.contact-form-success'),
$messageError = $form.find('.contact-form-error'),
$submitButton = $(this.submitButton),
$errorMessage = $form.find('.mail-error-message'),
submitButtonText = $submitButton.val();
$submitButton.val( $submitButton.data('loading-text') ? $submitButton.data('loading-text') : 'Loading...' ).attr('disabled', true);
var site_key = $('#google-recaptcha-v3').attr('src').split("render=")[1];
grecaptcha.execute(site_key, {action: 'contact_us'}).then(function(token) {
// Fields Data
var formData = $form.serializeArray(),
data = {};
$(formData).each(function(index, obj){
data[obj.name] = obj.value;
});
// Recaptcha v3 Token
data["g-recaptcha-response"] = token;
// Ajax Submit
$.ajax({
type: 'POST',
url: $form.attr('action'),
data: data
}).always(function(data, textStatus, jqXHR) {
$errorMessage.empty().hide();
if (data.response == 'success') {
// Uncomment the code below to redirect for a thank you page
// self.location = 'thank-you.html';
$messageSuccess.removeClass('d-none');
$messageError.addClass('d-none');
// Reset Form
$form.find('.form-control')
.val('')
.blur()
.parent()
.removeClass('has-success')
.removeClass('has-danger')
.find('label.error')
.remove();
if (($messageSuccess.offset().top - 80) < $(window).scrollTop()) {
$('html, body').animate({
scrollTop: $messageSuccess.offset().top - 80
}, 300);
}
$form.find('.form-control').removeClass('error');
$submitButton.val( submitButtonText ).attr('disabled', false);
return;
} else if (data.response == 'error' && typeof data.errorMessage !== 'undefined') {
$errorMessage.html(data.errorMessage).show();
} else {
$errorMessage.html(data.responseText).show();
}
$messageError.removeClass('d-none');
$messageSuccess.addClass('d-none');
if (($messageError.offset().top - 80) < $(window).scrollTop()) {
$('html, body').animate({
scrollTop: $messageError.offset().top - 80
}, 300);
}
$form.find('.has-success')
.removeClass('has-success');
$submitButton.val( submitButtonText ).attr('disabled', false);
});
});
}
});
});
}).apply(this, [jQuery]);
The issue seems to be that near the top of your PHP script you are setting:
$debug = 1;
Then at the end you say:
if ($debug == 0) {
echo json_encode($arrResult);
}
Which results in the script not sending any response, or at least not the {"'response": "success"} json you expect which then causes this js check to fail:
if (data.response == 'success')
You'll need to either set $debug = 0;, remove the if ($debug == 0) check, or otherwise resolve this logic issue.
I'm using Prestashop version 1.6.1.17 .
I have a module called "Blockcallmeback". This module adds the option to the customer to leave his/her telephone number so you can call him/her back.
The problem is that after submitting the form, there is an error that says:
"An error occured. Please check your data."
Which means, the ajax function returns success = false, but I don't know why.
This is the js code:
<script type="text/javascript">
var blockcallme_url = "/casannabis/modules/blockcallme/ajax.php";
var blockcallme_text_please = "Please enter";
var blockcallme_text_please_phone = "your phone number";
var blockcallme_text_thanks = "Thank you. We will call you soon.";
var blockcallme_text_error = "An error occured. Please check your data.";
var blockcallme_mask = "+56 (9) 9999-9999";
$(function () {
$("a.blockcallme_button").fancybox({
'hideOnContentClick': false,
'hideOnOverlayClick': true,
'overlayOpacity': 0.4,
'padding': 0,
afterShow: function () {
$('#blockcallme_phone').focus();
$('#blockcallme_phone').inputmask({
'mask': blockcallme_mask,
"clearMaskOnLostFocus": false
});
}
});
$('.blockcallme_form').on('submit', function () {
debugger;
$('#blockcallme_loader').show();
var form = $(this);
$('.blockcallme_errors').html('').hide();
$('.blockcallme_success').html('').hide();
var success = true;
var blockcallme_phone_input = $(this).find('#blockcallme_phone');
if (!blockcallme_phone_input.val() || !blockcallme_phone_input.inputmask('isComplete')) {
blockcallme_phone_input.css('outline', '1px solid red');
setTimeout(function () {
blockcallme_phone_input.css('outline', '');
}, 1000);
$(this).find('.blockcallme_errors').append(blockcallme_text_please + ' <span style="font-weight: bold;">' + blockcallme_text_please_phone + '</span>.<br>').show();
success = false;
}
if (!success) {
$('#blockcallme_loader').hide();
return false;
}
$.ajax({
type: 'POST',
url: blockcallme_url + '?ajax=1&rand=' + new Date().getTime(),
async: true,
cache: false,
dataType : "json",
data: form.serialize(),
success: function(jsonData) {
debugger;
$('#blockcallme_loader').hide();
if (jsonData['success'] == 1) {
form.find('.blockcallme_success').html(blockcallme_text_thanks).show();
}
else {
form.find('.blockcallme_errors').html(blockcallme_text_error).show();
}
}
});
return false;
});
});
</script>
And this is the php code:
<?php
include_once(dirname(__FILE__) . '/../../config/config.inc.php');
include_once(dirname(__FILE__) . '/../../init.php');
if(Tools::getValue('ajax') == 1)
{
$name = pSQL(trim(Tools::getValue('blockcallme_name', '')));
$phone = pSQL(trim(Tools::getValue('blockcallme_phone', '')));
$blockcallme = Module::getInstanceByName('blockcallme');
$success = 0;
if(!empty($phone))
{
Context::getContext()->cookie->blockcallme_phone = $phone;
Context::getContext()->cookie->blockcallme_name = $name;
$template = 'blockcallme';
$template_vars = array(
'{name}' => $name,
'{phone}' => $phone,
);
$email = Configuration::get('CALLME_EMAIL') ? Configuration::get('CALLME_EMAIL') : Configuration::get('PS_SHOP_EMAIL');
$to = array(
$email,
);
$send = Mail::Send(
Configuration::get('PS_LANG_DEFAULT'),
$template,
$blockcallme->l('Callback request', 'ajax'),
$template_vars,
$to,
null,
Configuration::get('PS_SHOP_EMAIL'),
Configuration::get('PS_SHOP_NAME'),
null,
null,
dirname(__FILE__).'/mails/'
);
if($send)
$success = 1;
}
if($success)
die(json_encode(array('success' => 1)));
else
die(json_encode(array('success' => 0)));
}
I am trying to send an email with PHP and AJAX, and it finally works, but it won't display validation errors returned from the server. I guess I'm doing something wrong in iterating through that data, or just don't understand something with connecting PHP and jQuery with JSON.
PHP mail script on server:
$to = "mymail#gmail.com";
if (isset($_POST['name'], $_POST['mail'], $_POST['text'])) {
if (empty($_POST['name'])) {
$errors[] = "Molimo unesite Vaše ime";
} else {
$contact_name = htmlentities($_POST['name']);
}
if (empty($_POST['mail'])) {
$errors[] = "Molimo unesite Vašu email adresu.";
} else if (strlen($_POST['mail']) > 60) {
$errors[] = "Vaša email adresa je predugačka.";
} else if (filter_var($_POST['mail'], FILTER_VALIDATE_EMAIL) === false ) {
$errors[] = "Unesite validnu email adresu.";
} else {
$contact_mail = "<" . htmlentities($_POST['mail']) . ">";
}
if (empty($_POST['text'])) {
$errors[] = "Molimo unesite poruku.";
} else {
$contact_text = htmlentities($_POST['text']);
}
}
if (empty($errors) === true) {
if(isset($contact_text, $contact_name, $contact_mail)) {
$subject = "Mail from " . $contact_name ." via www.mysite.com";
$headers = "From: " . $contact_mail;
$sent = mail($to, $subject, $contact_text, $headers);
if ($sent) {
die("true");
} else {
return json_encode($errors);
}
}
}
Relevant jQuery:
var mailBroker = {
send : function() { //initial validation and sending to server
var contact_name = $('input[name="contact-name"]').val();
var contact_mail = $('input[name="contact-mail"]').val();
var contact_text = $('textarea[name="contact-text"]').val();
var status = ""; //send success status
if (contact_name === "" || contact_mail === "" || contact_text === "") {
//form not complete
} else {
$.post("includes/mail.php", { //post form data to server
name : contact_name,
mail : contact_mail,
text : contact_text
}, function(data) {
var response = data;
if (data === "true") { //succesful
mailBroker.setStatus('Poruka poslata.');
} else {
var parsedData = $.parseJSON(data);
$.each(parsedData, function() {
var that = $(this);
setStatus(that);
});
}
});
}
},
setStatus : function(status) {
$('textarea[name="contact-text"]').after('<span>' + status + '</span>');
}
}
And inside $(document).ready():
$('#contact-us form').submit(function(event) {
event.preventDefault();
mailBroker.send();
$(this).trigger('reset');
});
Can somebody point out what I am doing wrong?
Of course, I know that I could just do it on the client-side, but that it is bad practice. So I left that part out for now and assumed that invalid or no data got through for required form fields.
Answer form is easier to explain this. The logic in your code never gives your script a chance to output the errors to the AJAX. You'd need to change the logic so it will. Ie.
if (empty($errors) === true) {
if(isset($contact_text, $contact_name, $contact_mail)) {
$subject = "Mail from " . $contact_name ." via www.mysite.com";
$headers = "From: " . $contact_mail;
$sent = mail($to, $subject, $contact_text, $headers);
if ($sent) {
die("true");
} else {
die("false"); // with json_encode here, $errors will always be empty
}
}
} else {
die(json_encode($errors)); //$errors wasn't empty, this is where you need to hand it back to the JS.
}
This is why firebug or another tool would help. You'd see that the information you were wanting given to your JS wasn't there - that way you know to look at the PHP (server-side) since it isn't outputting as expected. If it was, you'd check in to the JS code to see why that isn't processing it as expected.
EDIT: Your javascript doesn't allow the PHP to execute when a field is empty, but you are wanting the feedback PHP will give if one is empty, so you'd want to change your JS to something like:
var mailBroker = {
send : function() { //initial validation and sending to server
var contact_name = $('input[name="contact-name"]').val();
var contact_mail = $('input[name="contact-mail"]').val();
var contact_text = $('textarea[name="contact-text"]').val();
var status = ""; //send success status
$.post("includes/mail.php", { //post form data to server
name : contact_name,
mail : contact_mail,
text : contact_text
}, function(data) {
var response = data;
if (data === "true") { //succesful
mailBroker.setStatus('Poruka poslata.');
} else {
var parsedData = $.parseJSON(data);
$.each(parsedData, function() {
var that = $(this);
setStatus(that);
});
}
});
},
setStatus : function(status) {
$('textarea[name="contact-text"]').after('<span>' + status + '</span>');
}
}
A little modification of Jon's answer because you will still need to extract the messages from the returned JSON:
var mailBroker = {
'send' : function() { //initial validation and sending to server
var contact_name = $('input[name="contact-name"]').val();
var contact_mail = $('input[name="contact-mail"]').val();
var contact_text = $('textarea[name="contact-text"]').val();
var status = ""; //send success status
$.post("includes/mail.php", { //post form data to server
name : contact_name,
mail : contact_mail,
text : contact_text
}, function(data) {
var response = data;
if (data === "true") { //succesful
mailBroker.setStatus('Poruka poslata.');
$('#contact-us form').trigger('reset');
} else { //validation failed
var parsedData = $.parseJSON(data);
var msg = '';
$.each(parsedData, function() {
var that = $(this);
for (var i = 0; i < that.size(); i++) {
msg += that[i];
}
mailBroker.setStatus(msg); //msg used to be 'that'
msg = '';
});
}
});
},
'setStatus' : function(status) {
$('#validation-msgs').prepend('<p class="validation-msg">' + status + '</p>');
}
}
Essentially - you will need to pass through parsed data to get each of the messages. The problem is that they are also stored as arrays - of characters. So you will need to pass through those, too, and append those characters to a message String.
Then, you should prepend those messages to some container for warnings so they are in the right order. If you don't do that, you will get [Object] instead of the message text.
Hope this helps.
Hi I think you messed up on your line 3 mail script.
if (isset($_POST['name'], $_POST['mail'], $_POST['text'])) {
because you will use comparison operators for that.
Like this below.
if (isset($_POST['name'] && $_POST['mail'] && $_POST['text'])) {
how to return URL built in php as json object to ajax to open it in the new tab?
so far all my attempts to do so were unsuccessful. Please help
here is my JS file
$(document).ready ( function() {
$('.promoCode').click(function() {
// Store values in variables
var form = $(this).closest('form');
var name = form.find('input[name=name]');
var id = form.find('input[name=id]');
var submitted = form.find('input[name=submitted]');
var visitor = form.find('input[name=visitor]');
// Organize data
var data = 'name=' + name.val() + '&id=' + id.val() + '&submitted=' + submitted.val() + '&visitor=' + visitor.val();
var request = $.ajax({
type: "POST",
url: "/includes/_db_get_promo_code.php",
data: data,
cache: false,
success: function (html) {
myWindow = window.open(encodeURIComponent(true),
"_blank");
myWindow.focus();
if (html == "true") {
} else {
form.find('.error').fadeIn(500).delay(4000).fadeOut(500);
}
},
error: function(jqXHR, textStatus, error) {
alert("Form Error: " + error);
}
});
return false;
});
});
and here is my PHP file
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/includes/sitewide-variables.php");
// Check if form was submitted
if ($_POST['submitted'] && $_POST['visitor'] == '') {
// Check if all required fields are filled in
if (empty($_POST['name']) && empty($_POST['id'])) {
echo "Error: You must fill in all required fields.";
// If not, exit!
exit();
}
// If valid, store values in variables
$id = stripslashes($_POST['id']);
$name = stripslashes($_POST['name']);
if($name){
$query = 'SELECT * FROM files_paid WHERE parentpageID = :promoproductID';
$res = $db->prepare($query);
$res->execute(array(':promoproductID' => $id));
foreach ($res as $info);
if($info['promoCode'] == $_POST['name']){
$redirect_link = 'http://'.$info['promobuylinkID'].'.myid.pay.clickbank.net';
$todayis = date("l, F j, Y, g:i a") ;
$to = "My Email Address";
$subject = "Promotional Purchase";
$message = "$todayis [EST] \n
Promo Code: $name \n
";
// Send email
$sent = mail($to, $subject, $message);
if($sent) {
echo json_encode($redirect_link);
} else {
echo "Error: Mail could not be send.";
exit();
}
} else {
echo "Error: There was a problem with submitting the form";
exit();
}
}
}
?>
I am only getting true in the new window.
Thanks in advance
I have have found the problem.
First, I was missing dataType: "json", in ajax.
and after that I only had to return html to get to the point where I needed to get.
So the JS file now looks like this
$(document).ready ( function() {
$('.promoCode').click(function() {
// Store values in variables
var form = $(this).closest('form');
var name = form.find('input[name=name]');
var id = form.find('input[name=id]');
var submitted = form.find('input[name=submitted]');
var visitor = form.find('input[name=visitor]');
// Organize data
var data = 'name=' + name.val() + '&id=' + id.val() + '&submitted=' + submitted.val() + '&visitor=' + visitor.val();
var request = $.ajax({
type: "POST",
url: "/includes/_db_get_promo_code.php",
data: data,
dataType: "json",
cache: false,
success: function (html) {
if (html) {
window.open(decodeURIComponent(html),"_blank").focus();
} else {
form.find('.error').fadeIn(500).delay(4000).fadeOut(500);
}
},
error: function () {
alert("Your Coupon Code is not valid");
}
});
return false;
});
});
All works just fine.
I'm using jQuery's AJAX function to send a message from a contact form -
$('form button').click(function () {
$("input").removeClass("error");
$("textarea").removeClass("error");
var name = $("#name").val();
if (name == "" || name == "Name" || name == "Namn") {
$("#name").addClass("error");
$("#name").focus();
return false;
}
var email = $("#email").val();
if (email == "" || email == "Email" || email == "Epost") {
$("#email").addClass('error');
$("#email").focus();
return false;
}
var message = $("#message").val();
if (message == "") {
$("#message").addClass('error');
$("#message").focus();
return false;
}
// Non-verifying fields
var phone = $("input#phone").val();
// Gather data
var post = 'name=' + name + '&email=' + email + '&phone=' + phone + '&message=' + message;
// Disable form
var limit = document.forms[0].elements.length;
for (i = 0; i < limit; i++) {
document.forms[0].elements[i].disabled = true;
}
// Send data
$.ajax({
type: "POST",
url: "form_handler.php",
data: post,
success: function () {
$('div.contact form').animate({
opacity: 0.25
}, function () {
$('div.contact div.confirm').fadeIn(200);
});
},
error: function () {
$('div.contact form').animate({
opacity: 0.25
}, function () {
$('div.contact div.deny').fadeIn(200);
});
}
});
return false;
});
I know this is not the safest method considering I reveal the Mail file in my JS code but nevertheless I want this to work before I decide to try anything else. In my contact form I have the above fields (name, email, phone and message) and in "form_handler.php" the settings look like this -
<?php
header('Content-type: text/html; charset=UTF-8');
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$to = "staffan.estberg#gmail.com";
$subject = "Meddelande från x.se";
$body = "------------------------------------------------------------------------------------------------------------------------\n\n";
$body .= "Meddelande från $name:\n\n";
$body .= "$message\n\n";
$body .= "Avsändarens epost: $email\n";
$body .= "Avsändarens telefonnummer: $phone\n\n";
$body .= "------------------------------------------------------------------------------------------------------------------------";
$headers = "From: $email";
mail($to,$subject,$body,$headers);
?>
When I combine the scripts I manage to generate a message though it doesn't contain any form data. Have I missed out on something?
I think you'll actually want to pass a JSON array as the data parameter instead of the GET-style string.
Something like:
post = { 'name' : name, ... }