Message successfully sent with ajax and php but no email - php

I found a template and everything works fine, but I don't know what is going on..
here is HTML code
<form action="#" id="contactform" class="animform"><!-- Contact form -->
<ul>
<li>
<label for="name" class="flabel">Name</label>
<input type="text" name="name" value="" id="name" />
<div class="indicate-name"></div>
</li>
<li>
<label for="email" class="flabel">E-mail</label>
<input type="text" name="email" value="" id="email" />
<div class="indicate-email"></div>
</li>
<li>
<label for="message" class="flabel">Enter your message</label>
<textarea name="message" cols="88" rows="6" id="message"></textarea>
<div class="indicate-message"></div>
</li>
<li>
<button type="submit" name="submit" value="Send your message" class="submit">Send your message</button>
</li>
</ul>
</form><!-- /Contact form -->
and here's jQ code
$(function () {
'use strict';
(function () {
var MIN_NAME_LENGTH = 2,
MIN_TEXT_LENGTH = 5,
NAME_ERROR_TEXT = 'Minimum 2 characters',
EMAIL_ERROR_TEXT = 'Please enter correct e-mail',
MSG_ERROR_TEXT = 'Minimum 5 characters',
ERROR_CLASS_NAME = 'error',
SUCCESS_CLASS_NAME = 'ok',
$contactForm = $('#contactform'),
$formSuccess = $('.form-success'),
$nameField = $contactForm.find('#name'),
$emailField = $contactForm.find('#email'),
$textField = $contactForm.find('#message');
function init() {
_bindEvents();
}
function _bindEvents() {
$('.new-message').click(function() {
$contactForm.delay(600).slideDown(1000);
$formSuccess.slideUp(500);
});
$nameField.live('blur', _nameValidate);
$emailField.live('blur', _emailValidate);
$textField.live('blur', _textValidate);
$contactForm.live('submit', function () {
var status = _nameValidate(true) & _emailValidate(true) & _textValidate(true);
if (!!status) {
_submitForm();
}
return false;
});
}
function _submitForm() {
var data = {
name: $("#form_name").val(),
email: $("#form_email").val(),
message: $("#msg_text").val()
};
$.ajax({
type: "post",
url: "contact.php",
data:{
'name': $nameField.val(),
'email': $emailField.val(),
'message': $textField.val()
},
success: function (msg) {
if (msg === 'SEND') {
$contactForm.slideUp(1000);
$formSuccess.delay(1000).slideDown(500);
setTimeout( function() {
// clear form value, shown labels
$nameField.val('');
$emailField.val('');
$textField.val('');
$contactForm.find( 'label[for="'+$nameField.attr( 'id' )+'"]').css( 'display', 'block').css( 'opacity', 1 );
$contactForm.find( 'label[for="'+$emailField.attr( 'id' )+'"]').css( 'display', 'block').css( 'opacity', 1 );
$contactForm.find( 'label[for="'+$textField.attr( 'id' )+'"]').css( 'display', 'block').css( 'opacity', 1 );
}, 1000 );
}
else {
$contactForm.prepend( '<div class="error">' + msg + '</div>' );
}
},
error: function( t, errorStatus ) {
$contactForm.prepend( '<div class="error">' + errorStatus + '</div>' );
},
beforeSend: function() {
$(".error,.success").remove();
}
});
}
function _nameValidate(errIfEmpty) {
var $memo = $contactForm.find('.indicate-name'),
val = $nameField.val().replace(/\s+$/g, ''),
result = false;
errIfEmpty = errIfEmpty === true ? true : false;
if (!errIfEmpty && val.length === 0) {
$memo
.text('')
.removeClass(SUCCESS_CLASS_NAME)
.removeClass(ERROR_CLASS_NAME);
} else {
if (val.length >= MIN_NAME_LENGTH) {
$memo
.text('')
.removeClass(ERROR_CLASS_NAME)
.addClass(SUCCESS_CLASS_NAME);
result = true;
} else {
$memo
.text(NAME_ERROR_TEXT)
.removeClass(SUCCESS_CLASS_NAME)
.addClass(ERROR_CLASS_NAME);
}
}
return result;
}
function _emailValidate(errIfEmpty) {
var $memo = $contactForm.find('.indicate-email'),
val = $emailField.val().replace(/\s+$/g, ''),
regExp = /^.+#.+\..{2,6}$/i,
result = false;
errIfEmpty = errIfEmpty === true ? true : false;
if (!errIfEmpty && val.length === 0) {
$memo
.text('')
.removeClass(SUCCESS_CLASS_NAME)
.removeClass(ERROR_CLASS_NAME);
} else {
if (regExp.test(val)) {
$memo
.text('')
.removeClass(ERROR_CLASS_NAME)
.addClass(SUCCESS_CLASS_NAME);
result = true;
} else {
$memo
.text(EMAIL_ERROR_TEXT)
.removeClass(SUCCESS_CLASS_NAME)
.addClass(ERROR_CLASS_NAME);
}
}
return result;
}
function _textValidate(errIfEmpty) {
var $memo = $contactForm.find('.indicate-message'),
val = $textField.val().replace(/\s+$/g, ''),
result = false;
errIfEmpty = errIfEmpty === true ? true : false;
if (!errIfEmpty && val.length === 0) {
$memo
.text('')
.removeClass(SUCCESS_CLASS_NAME)
.removeClass(ERROR_CLASS_NAME);
} else {
if (val.length >= MIN_TEXT_LENGTH) {
$memo
.text('')
.removeClass(ERROR_CLASS_NAME)
.addClass(SUCCESS_CLASS_NAME);
result = true;
} else {
$memo
.text(MSG_ERROR_TEXT)
.removeClass(SUCCESS_CLASS_NAME)
.addClass(ERROR_CLASS_NAME);
}
}
return result;
}
init();
})();
});
and this is the php code:
<?php
$to = 'myEmail#anyEmail.com';
$from = $_POST['email'];
$name = $_POST['name'];
$subject = "Message from site";
$theMessage = $_POST['message'];
$message = "This message from \n\n Name: " . $name . "\n\n";
$message .= "Enquiries: " . $theMessage . "\n\n";
$headers = "From: $from\r\n";
$headers .= "Reply-To: $from\r\n";
if (mail($to, $subject, $message, $headers)) {
echo "SEND";
}else{
echo "Error";
}
//print_r(error_get_last());?>
The form does say success, but still not receiving the emails! any ideas?
P.S. I tried two different Emails "hotmail" and "ymail", but the two of them didn't receive anything..
thanks

Send email trought php need a smtp configuration.
The mail() function return true if he successfull order to the system to send the mail.
But if you have trouble with your smtp, the mail will never arrive.
Then you will have to format your headers correctly http://php.net/manual/fr/function.mail.php

Related

$_Post data returns blank Ajax

I have a form. I would like to get the input information and send it to the database via 'update_user_meta', however $_POST['this-user'] is giving a blank entry in the database.
The '$user_id' and '$meta_key' are posting to the database but the '$meta_value' is blank.
When I console log $_POST through ajax I get a blank entry in console. When I run .val() in jQuery I also get a blank entry not undefined or NULL.
I have tried having the data section of the code be
data: {
'action': 'hide_this',
'this-user': this-user,
'hidebtn2': hidebtn2
},
However a dash can't be in function i.e 'function doAjaxRequest4(hidebtn2,this-user)' is not allowed.
Insight is appreciated.
PHP
add_action('wp_ajax_hide_this', 'hide_this_by_id');
add_action('wp_ajax_nopriv_hide_this', 'hide_this_by_id');
function hide_this_by_id()
{
global $wpdb;
$labelID4 = 0;
$postdVlaue2 = $_POST['hidebtn2'];
$this_user = $_POST['this-user'];
$alredyclick3 = 0;
$not_loggedin = 0;
$userlvlMeta2 = 0;
if (is_user_logged_in()) {
$member_id = SwpmMemberUtils::get_logged_in_members_id();
$query = "SELECT * FROM " . $wpdb->prefix . "swpm_members_tbl WHERE member_id = %d";
$userData = $wpdb->get_row($wpdb->prepare($query, $member_id));
$membership_levels = $userData->membership_level;
$labelID4 = $membership_levels;
} else {
$not_loggedin = 1;
}
if ($labelID4 == 10 ) {
$userlvlMeta2 = 1;
$alredyclick3 = get_user_meta($member_id, 'hidden-info', true);
if (empty($alredyclick3) && $postdVlaue2 == 1) {
update_user_meta($member_id, 'hidden-info', $postdVlaue2);
update_user_meta($member_id, 'this-user', $this_user);
$alredyclick3 = 1;
}
}
if ($alredyclick3 == 1) {
$this_hide2 = 1;
} else {
$this_hide2 = 0;
}
if ($userlvlMeta2 == 1) {
$this_Meta2 = 1;
} else {
$this_Meta2 = 0;
}
$return4 = array(
'hIdethis2' => $this_hide2,
'userlvlMeta2' => $this_Meta2,
'userlvlNolog' => $not_loggedin,
'levelid4' => $labelID4,
'test' =>$this_user
);
echo json_encode($return4);
die();
}
jQuery
function doAjaxRequest4(hidebtn2,getthisInfo) {
var getthisInfo = jQuery('.this-user > input').val();
console.log(getthisInfo);
jQuery.ajax({
url: ajax_sib_front_object.ajax_url,
data: {
'action': 'hide_this',
'this-user': getthisInfo,
'hidebtn2': hidebtn2
},
dataType: 'JSON',
type: "post",
success: function (data) {
console.log(data.test);
var input = jQuery('.this-user > input');
var input2 = jQuery('.this-number > input');
var is_name = input.length > 3;
var is_name2 = input2.length > 3;
if (!data.thisdisc2 == 1 && data.userlvlMeta2 == 1) {
jQuery("#this_col_1").addClass("enable_this");
} else if (data.thisdisc2 == 1 && is_name && is_name2 ) {
jQuery("#this_col_1").removeClass("enable_this");
jQuery("#this_col_2").addClass("enable_this");
}
}
});
}
Function Called by
if ($('body').is('.page-id-9999') || $('body').is('.page-id-1111')) {
var thisbtn = document.querySelector('#this_verf_form > div > .wpcf7');
thisbtn.addEventListener('wpcf7submit', function (event) {
var status = event.detail.status;
console.log(status);
if (status === 'mail_sent') {
jQuery('#this_submtID').val("Submitted");
}
setTimeout(function () {
doAjaxRequest4(1);
}, 3500);
}, false);
}
HTML
<div role="form" class="wpcf7" id="wpcf7-f9999-p9999-o1" lang="en-US" dir="ltr">
<div class="screen-reader-response"><p role="status" aria-live="polite" aria-atomic="true"></p> <ul></ul></div>
<form action="/mysite/#wpcf7-f9999-p9999-o1" method="post" class="wpcf7-form init" novalidate="novalidate" data-status="init">
<div class="vc_row" id="this_row">
<div class="vc_col-sm-5">
<span class="wpcf7-form-control-wrap this-user"><input type="text" name="this-user" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" aria-required="true" aria-invalid="false" placeholder="placeholder"></span>
</div>
<input type="submit" value="Submit" class="wpcf7-form-control has-spinner wpcf7-submit" id="sub_id">
</div>

Prestashop module error "An error occured. Please check your data."

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)));
}

php echo keeps opening in new tab, not in jquery notification toastr.js

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');
})
});

Ajax Call and Returned Response

I'm trying to add an address to a list in dotmailer (which for those not familiar is a service like mailchimp) I can get the address added but am struggling to get any sort of returned status via Ajax.
I've got the following in my form page in php
var emailEntered;
$(document).ready(function() {
$.fn.search = function() {
return this.focus(function() {
if( this.value == this.defaultValue ) {
this.value = "";
}
}).blur(function() {
if( !this.value.length ) {
this.value = this.defaultValue;
}
});
};
$("#email").search();
$("#sendButton").click(function() {
$(".error").hide();
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailaddressVal = $("#email").val();
if(emailaddressVal == '') {
$("#message").html('<span class="error">Enter your email address before submitting.</span>');
return false;
}
else if(!emailReg.test(emailaddressVal)) {
$("#message").html("<span class='error'>Please check your email address.</span>");
return false;
}
else {
emailEntered = escape($('#email').val());
}
});
$('#signup').submit(function() {
$("#message").html("<span class='error'>Adding your email address...</span>");
$.ajax({
url: 'dotmailerInput.php',
data: 'ajax=true&email=' + emailEntered,
success: function(msg) {
$('#message').html(msg);
}
});
return false;
});
});
</script>
<form id="signup" action="dotmailer.php" method="get">
<input type="email" name="email" id="email" class="textinput" value="Enter" />
<input type="submit" id="sendButton" name="submit" class="textinput" value="" />
</form>
<div id="message"> </div>
In the dotmailer.php page that it is referencing I've got the following. I can see it gives me a response "adding your email address" but nothing else after this and the email as I said gets added correctly.
$email = $_GET['email'];
$username = ""; //apiusername
$password = ""; //api password
$addressbookid = ;
$AudienceType = "Unknown";
$OptInType = "Unknown";
$EmailType = "Html";
try {
$client = new SoapClient("http://apiconnector.com/api.asmx?WSDL");
$contact = array("Email" => $email,"AudienceType" => $AudienceType, "OptInType" => $OptInType, "EmailType" => $EmailType, "ID" => -1);
$dotParams = array("username" => $username, "password" => $password, "contact" => $contact, "addressbookId" => $addressbookid);
$result = $client->AddContactToAddressBook($dotParams);
return "Success";
}
catch (Exception $e) {
return "Error";
}
Any helps or tips on what to look at or where to go next would be greatly appreciated.
Chris
Try echo instead of return because you are at the top level in PHP and will do output using this (instead of return gibing a function a value).
echo "Success";
}
catch (Exception $e) {
echo "Error";

Javascript Password Change Form Validation doesn't work on IE8

got this function to validate two fields from a changing password form and it's doesn't seem to work at IE8. FF, Opera, Safari and Chrome work.
function chk_form_pw()
{
if(document.getElementById('new_passwd').value == '')
{
alert("<?php _e('Please enter New Password') ?>");
document.getElementById('new_passwd').focus();
return false;
}
if(document.getElementById('new_passwd').value.length < 5 )
{
alert("<?php _e('Please enter New Password minimum 5 chars') ?>");
document.getElementById('new_passwd').focus();
return false;
}
if(document.getElementById('cnew_passwd').value == '')
{
alert("<?php _e('Please enter Confirm New Password') ?>");
document.getElementById('cnew_passwd').focus();
return false;
}
if(document.getElementById('cnew_passwd').value.length < 5 )
{
alert("<?php _e('Please enter Confirm New Password minimum 5 chars') ?>");
document.getElementById('cnew_passwd').focus();
return false;
}
if(document.getElementById('new_passwd').value != document.getElementById('cnew_passwd').value)
{
alert("<?php _e('New Password and Confirm New Password should be same') ?>");
document.getElementById('cnew_passwd').focus();
return false;
}
}
This is the form:
<form name="registerform" id="registerform" action="<?php echo get_option( 'siteurl' ).'/?page=account&chagepw=1'; ?>" method="post">
<p><label><?php _e('New Password'); ?> <span class="indicates">*</span></label></p>
<p><input type="password" name="new_passwd" id="new_passwd" class="lostpass_textfield" /></p>
<p><label><?php _e('Confirm New Password'); ?> <span class="indicates">*</span></label></p>
<p><input type="password" name="cnew_passwd" id="cnew_passwd" class="lostpass_textfield" /></p>
<p><input type="submit" name="Update" onclick="return chk_form_pw();" value="<?php _e('Update Password') ?>" class="btn grey"/></p>
</form>
And here is the chagepw=1 thing:
<?php
if($_POST)
{
if($_REQUEST['chagepw'])
{
$new_passwd = $_POST['new_passwd'];
if($new_passwd)
{
$user_id = $current_user->data->ID;
wp_set_password($new_passwd, $user_id);
$message1 = "Password Changed successfully.You need to sign back in.";
}
}else
{
$user_id = $userInfo['ID'];
$user_add1 = $_POST['user_add1'];
$user_add2 = $_POST['user_add2'];
$user_city = $_POST['user_city'];
$user_state = $_POST['user_state'];
$user_country = $_POST['user_country'];
$user_postalcode = $_POST['user_postalcode'];
$buser_add1 = $_POST['buser_add1'];
$buser_add2 = $_POST['buser_add2'];
$buser_city = $_POST['buser_city'];
$buser_state = $_POST['buser_state'];
$buser_country = $_POST['buser_country'];
$buser_postalcode = $_POST['buser_postalcode'];
$user_address_info = array(
"user_add1" => $user_add1,
"user_add2" => $user_add2,
"user_city" => $user_city,
"user_state" => $user_state,
"user_country" => $user_country,
"user_postalcode"=> $user_postalcode,
"buser_name" => $_POST['buser_fname'].' '.$_POST['buser_lname'],
"buser_add1" => $buser_add1,
"buser_add2" => $buser_add2,
"buser_city" => $buser_city,
"buser_state" => $buser_state,
"buser_country" => $buser_country,
"buser_postalcode"=> $buser_postalcode,
);
update_usermeta($user_id, 'user_address_info', serialize($user_address_info)); // User Address Information Here
$userName = $_POST['user_fname'].' '.$_POST['user_lname'];
$updateUsersql = "update $wpdb->users set user_nicename=\"$userName\", display_name=\"$userName\" where ID=\"$user_id\"";
$wpdb->query($updateUsersql);
$message = "Information Updated successfully.";
}
}
$userInfo = $General->getLoginUserInfo();
$user_address_info = unserialize(get_user_option('user_address_info', $user_id));
$user_add1 = $user_address_info['user_add1'];
$user_add2 = $user_address_info['user_add2'];
$user_city = $user_address_info['user_city'];
$user_state = $user_address_info['user_state'];
$user_country = $user_address_info['user_country'];
$user_postalcode = $user_address_info['user_postalcode'];
$display_name = $userInfo['display_name'];
$display_name_arr = explode(' ',$display_name);
$user_fname = $display_name_arr[0];
$user_lname = $display_name_arr[2];
$buser_add1 = $user_address_info['buser_add1'];
$buser_add2 = $user_address_info['buser_add2'];
$buser_city = $user_address_info['buser_city'];
$buser_state = $user_address_info['buser_state'];
$buser_country = $user_address_info['buser_country'];
$buser_postalcode = $user_address_info['buser_postalcode'];
$bdisplay_name = $user_address_info['buser_name'];
$display_name_arr = explode(' ',$bdisplay_name);
$buser_fname = $display_name_arr[0];
$buser_lname = $display_name_arr[2];
if($_SESSION['redirect_page'] == '')
{
$_SESSION['redirect_page'] = $_SERVER['HTTP_REFERER'];
}
if(strstr($_SESSION['redirect_page'],'page=checkout'))
{
$login_redirect_link = get_option( 'siteurl' ).'/?page=checkout';
}
?>
A smoother solution would be jQuery. There you can load a loading-animation, put color like red/green on wrong/correct and simplified print out text depending on what happening to the form.
Download jQuery from: http://docs.jquery.com/Downloading_jQuery
Then you insert it in the html code like this:
<script type="text/javascript" src="jquery.js">
</script>
Then you can have a valid.js like this:
$(document).ready(function () {
var validatefield = $('#validatefield');
$('#validatefield').keyup(function () {
var t = this;
if (this.value != this.lastValue) {
if (this.timer) clearTimeout(this.timer);
validatefield.html('<img src="images/Here_you_can_put_your_gif_animation"
alt="Loading..."
height="16" width="16"/>');
this.timer = setTimeout(function () {
$.ajax({
url: 'check_field.php',
data: 'action=check_field&field=' + encodeURIComponent(t.value),
dataType: 'json',
type: 'post',
success: function (j) {
if (j.ok) {
validatefield.html(j.msg);
}
else if ($("#validatefield").val() == "")
{
validatefield.html('');
}
else {
validatefield.html(j.msg);
}
}
});
}, 200);
this.lastValue = this.value;
}
});
});
Then in the check_field.php, have this;
echo json_encode(check_field($_POST['field']));
function check_field($field) {
$fieldSum = stripslashes(strip_tags(trim(htmlspecialchars($field))));
$response = array();
if (strlen($fieldSum) > 15) {
$response = array(
'ok' => false,
'msg' => "The field characters were over 15!");
}
else
{
$response = array(
'ok' => true,
'msg' => "Correct");
}
return $response;
}
The id #validatefield is an id inside the html code that you have to create in order to print things out.
Example:
<div id="validatefield">Here comes the text etc, from the valid.js</div>
Finally got it done using the JQuery script posted before:
http://code.google.com/p/form-validation-engine/downloads/list
It's been really easy to fit into my previous code and works flawlessly through every browser tested.
Thank you all for your help!

Categories