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, ... }
Related
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?
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 want to go directly to my problem: My application shows data from an mysql database and the user can select those items and save them into an javascript list. After he has selected his items we want that he write his name in an inputfield and with the click on an button the "javascript-list" (contains only strings) should be send to our mailForm.php via post & ajax.
The problem is that our mailForm.php works perfectly fine (trying to access via Java and sending Post data) but we are not able to post the data via ajax and javascript (have a look:)
mailForm.php
<?
if ($_POST) {
$message = "";
while (list ($key, $val) = each ($_POST)) {
if ($key == "mailAn") {
$mymail = $val;
} elseif ($key == "subject") {
$subject = $val;
} elseif ($key == "mailVon") {
$email = $val;
} elseif ($key == "message") {
$message = $val;
}
}
//array_walk ($_POST, "GetValues");
if (mail($mymail,$subject,$message,"From: $email")) {
header ("");
} else {
header ("Location: form_notok.htm");
//echo "Fehler beim Senden des Formulars!";
}
}
?>
As you can see wie have 4 keys (mailAn, subject, mailVon, message).. Any idea how this goes via js/jquery? (getting the Strings (javascriptlist) as message and the name (from inputfield) into mailVon)
Javascript:
$("#contact").submit(function(e){
e.preventDefault();
var name = $("#name").val(); //Inputfield with Name
var email = $("#email").val(); // Inputfield with email
var text = $("#text").val(); //should be list
var dataString = 'mailVon=' + name + '&mailAn=' + email + '&message=' + text;
$.ajax({
type: "POST",
url: "./mailForm.php",
data: dataString,
success: function(){
$('.success').fadeIn(1000);
}
});
return false;
});
EDIT:
I now added the subject post param:
var dataString = 'mailVon=' + name + '&subject' + 'Test via javascript' + '&mailAn=' + email + '&message=' + text;
I still get an success message but no mail...
I would setup some echos and debug it with firebug.
if (isset($_POST['mailAn'])){
echo "Phase 1";
foreach($_POST as $key => $value)
{
switch ($key){
case "mailAn":
$mymail = $value;
echo "Phase 2";
break;
}
}
}else{
echo "FAILED";
}
I would add headers to the mail function.
`
<?
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
$headers .= 'To: ' . $to . "\r\n";
$headers .= 'From: ' . $from . "\r\n";
$headers .= 'Cc: ' . "\r\n";
$headers .= 'Bcc: ' . "\r\n";
// Mail it
mail($to, $subject, $message, $headers);
?>
`
The code above works perfectly fine - problem was the settings of the test host we used. Using our business webspace it will work. Good Look.
MailForm.php
<?
if ($_POST) {
$message = "";
while (list ($key, $val) = each ($_POST)) {
if ($key == "mailAn") {
$mymail = $val;
} elseif ($key == "subject") {
$subject = $val;
} elseif ($key == "mailVon") {
$email = $val;
} elseif ($key == "message") {
$message = $val;
}
}
//array_walk ($_POST, "GetValues");
if (mail($mymail,$subject,$message,"From: $email")) {
header ("");
} else {
header ("Location: form_notok.htm");
//echo "Fehler beim Senden des Formulars!";
}
}
?>
JavaScript with fixed mail & javascript-list as dataString:
// Contact Form
$("#contact").submit(function(e){
e.preventDefault();
var name = $("#name").val();
var email = 'your#email.com';
var message = '';
for (var i = 0; i < musicList.length; i++) {
message += musicList[i];
if(i < (musicList.lenght-1)){
message += ', ';
}
}
var dataString = 'mailVon=' + name + '&subject=' + 'Betreff: Music' + '&mailAn=' + email + '&message=' + message;
$.ajax({
type: "POST",
url: "./mailForm.php",
data: dataString,
success: function(data) {
if(data.status == 'success')
$('.success').fadeIn(1000);
else if(data.status == 'error')
$('.error').fadeIn(1000);
}
});
return false;
});
Hope it will help someone else too
-Domi
I cannot seem to find the problem in my code. I want the validation in php file to trigger the jquery notification plugin 'toastr', however, the php echo keeps publishing the php file message status to a new tab, instead. What am I doing wrong and how can I make the message appear in the notification, instead? The live version of my school site is here: Wright State University BMES Site and the problem can be replicated when submitting the Contact Us form. Thank you in advance :)
HTML:
<form action=send-contact.php method=post data-show-errors="true" class=contact-form id=contact-form-id data-parsley-validate>
<p class=half>
<input autofocus parsley-trigger="change" name=name required id=name placeholder="Type your name" class="testBox label_better" data-new-placeholder="Example: Sir Humphrey Charleston III" parsley-required="true">
</p>
<p class=half>
<input name=email id=email placeholder="Type your e-mail address" class="testBox label_better" data-new-placeholder="Example: humphrey.charleston#wright.edu" parsley-type="email" parsley-trigger="change" required parsley-required="true">
</p>
<p>
<select class="contactselect required" name=subject id=subject parsely-required="true" required parsley-trigger="change">
<option value="" parsley-trigger="change">Please select one topic:</option>
<option value="1" parsley-trigger="change">Information about BMES Chapter</option>
<option value="2" parsley-trigger="change">Information about upcoming events</option>
<option value="3" parsley-trigger="change">Other</option>
</select>
</p>
<p>
<textarea name=message id=message rows=12 cols=20 class="label_better_text" placeholder="Tell us what's on your mind." parsley-trigger="keyup" parsley-rangelength="[1,300]" required parsley-required="true"></textarea>
</p>
<p>
<button name=send type=submit onclick="$( '#contact-form-id' ).parsley('validate')" id=submit value=1>Send message</button>
<span class="color-red"><button onclick="$( '#contact-form-id' ).parsley( 'destroy' ); $('#contact-form-id').parsley();" name=reset type=reset value=1>Reset</button></span>
</p>
</form>
<script type=text/javascript>
jQuery(document).ready(function(c){
$('#contact-form').parsley();
$('#contact-form-id').submit(function(e) {
e.preventDefault();
if ( $(this).parsley('validate') ) {
$.post("send-contact.php", $(this).serialize());
toastr.success('Thank you, we will attend to your message shortly.');
$( '#contact-form-id' ).parsley( 'destroy' );
}
}); });
</script>
PHP:
<?php
$name = '';
$subject = '';
$email = '';
$message = '';
function getIp()
{if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
$ip_address=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
if (!isset($ip_address)){
if (isset($_SERVER['REMOTE_ADDR']))
$ip_address=$_SERVER['REMOTE_ADDR'];
}
return $ip_address;
}
//taking the data from form
$name = addslashes(trim($_POST['name']));
$subject = addslashes(trim($_POST['subject']));
$email = addslashes(trim($_POST['email']));
$message = addslashes(trim($_POST['message']));
//form validation
$errors = array();
$fields = array();
if(!$name) {
$errors[] = "Please enter your name.";
$fields[] = "name";
}
$email_pattern = "/^[a-zA-Z0-9][a-zA-Z0-9\.-_]+\#([a-zA-Z0-9_-]+\.)+[a-zA-Z]+$/";
if(!$email) {
$errors[] = "Please enter your e-mail address.";
$fields[] = "email";
} else if(!preg_match($email_pattern, $email)) {
$errors[] = "The e-mail address you provided is invalid.";
$fields[] = "email";
}
if(!$subject) {
$errors[] = "Please choose the subject of your message.";
$fields[] = "subject";
}
if(!$message) {
$errors[] = "Please enter your message.";
$fields[] = "message";
}
//preparing mail
if(!$errors) {
//taking info about date, IP and user agent
$timestamp = date("Y-m-d H:i:s");
$ip = getIp();
$host = gethostbyaddr($ip);
$user_agent = $_SERVER["HTTP_USER_AGENT"];
$headers = "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=utf-8\n";
$headers .= "Content-Transfer-Encoding: quoted-printable\n";
$headers .= "From: $email\n";
$content = 'Subject: '.$subject.'<br>'.
'Name: '.$name.'<br>'.
'E-mail: '.$email.'<br>'.
'Message: '.$message.'<br>'.
'Time: '.$timestamp.'<br>'.
'IP: '.$host.'<br>'.
'User agent: '.$user_agent;
//sending mail
$ok = mail("my-email-address-normally-goes-here","BMES Website Contact Us ", $content, $headers);
if($ok) {
$response['msgStatus'] = "ok";
$response['message'] = "Thank you for contacting us. We will attend to your inquiry as soon as possible.";
} else {
$response['msgStatus'] = "error";
$response['message'] = "An error occured while trying to send your message. Please try again.";
}
} else {
$response['msgStatus'] = "error";
$response['errors'] = $errors;
$response['errorFields'] = $fields;
}
header('Content-type: application/json');
echo json_encode($response);
?>
Javascript:
$("form.contact-form").each(function(){
var form = $(this);
var button = form.find("button[type=submit]");
var buttonText = button.html();
button.click(function(e){
e.preventDefault();
var formTop = form.offset().top;
var url = form.attr("action");
var data = form.serialize();
form.find("input, select, textarea, span").removeClass("error");
form.find(".msg").remove();
button.html("Sending...");
$.post(url, data, function(response){
var status = response.msgStatus;
var msg = response.message;
if(status == "ok") {
form.prepend('<p class="msg success"><a class="hide" href="#">hide this</a>' + msg + '</p>');
form.find("input, select, textarea").val("");
var valField = form.find(".select .value");
var selectField = valField.siblings("select");
var selectedText = selectField.find("option").eq(0).html();
valField.html(selectedText);
} else if(status == "error") {
if(response.errorFields.length) {
var fields = response.errorFields;
for (i = 0; i < fields.length; i++) {
form.find("#" + fields[i]).addClass("error");
form.find("select#" + fields[i]).parents(".select").addClass("error");
}
var errors = response.errors;
var errorList = "<ul>";
for (i = 0; i < errors.length; i++) {
errorList += "<li>" + errors[i] + "</li>";
}
errorList += "</ul>";
form.prepend('<div class="msg error"><a class="hide" href="#">hide this</a><p>There were errors in your form:</p>' + errorList + '<p>Please make the necessary changes and re-submit your form</p></div>');
} else form.prepend('<p class="msg error"><a class="hide" href="#">hide this</a>' + msg + '</p>');
}
$(".msg a.hide").click(function(e){
e.preventDefault();
$(this).parent().slideUp();
});
button.html(buttonText);
window.scrollTo(0, formTop);
}, 'json');
})
});
Have you tried playing with your jquery a bit more? for instance, ajax instead of post.
something like this?
button.click(function () {
$.ajax({
url: url,
type: 'POST',
data: form.serialize(),
contentType: "application/json;charset=utf-8",
success: function (data) {
if (data.msgSTatus == "ok"){
alert(data.message);
// play with html here once you know the page stays.
}
},
error: function (data) {
alert('Fail.');
}
});
});
As far as html appending goes, I would personally have an empty on the page already with an id, and just set the content of the div to the data that you receive, would make the js look much cleaner maybe..
Try including jquery before your other scripts. Also, use Firebug or build-in browser JS debugging tools to troubleshoot Javascript errors.
I have managed to solve the issue. Alterations are listed below for comparative purposes to not only help others but to also close this issue. A special thank you to #WhiteRuski for pointing me in the right direction. The PHP and HTML remain unchanged. Here is the new Javascript:
$("form.contact-form").each(function(){
var form = $(this);
var button = form.find("button[type=submit]");
var buttonText = button.html();
button.click(function(e){
e.preventDefault();
var url = form.attr("action");
var data = form.serialize();
// button.html("Sending...");
button.html('<i class="fa fa-cog fa-lg fa-spin"></i>' + ' Sending ... ');
$.post(url, data, function(response){
var status = response.msgStatus;
var msg = response.message;
if(status == "ok") {
toastr.success('<p>' + msg + '</p>');
var valField = form.find(".select .value");
var selectField = valField.siblings("select");
var selectedText = selectField.find("option").eq(0).html();
valField.html(selectedText);
} else if(status == "error") {
if(response.errorFields.length) {
var fields = response.errorFields;
for (i = 0; i < fields.length; i++) {
form.find("#" + fields[i]).addClass("error");
form.find("select#" + fields[i]).parents(".select").addClass("error");
}
var errors = response.errors;
var errorList = "<ul>";
for (i = 0; i < errors.length; i++) {
errorList += "<li>" + errors[i] + "</li>";
}
errorList += "</ul>";
// toastr.error('<p>There were errors in your form:</p>' + errorList + '<p>Please make the necessary changes and re-submit your form</p>'); This lists the specific errpr in the field
toastr.error('<p>There were a few errors in your form. Please resubmit with corrections.</p>');
} else toastr.error('<p>' + msg + '</p>');
}
button.html(buttonText);
}, 'json');
})
});