Vuejs ajax call not working - php

Hey Everyone so I am trying to make a vueapp that makes an ajax call to a php page. On that php page I am running a few mysql statements the most important of which is a insert statement. if that page ajax call is successful and the insert statement runs successfully I want to redirect a page. If the ajax call or the insert statement fails or the user exists I want to redirect them the same page just render the page diffrently based on the result. I've tried doing it with sessions however when i try to use the ajax error function it fires everytime even when its successful. I know this as I get an alert error. But than when it goes to the result.php page I get success. I dont understand. Any help would be great!
<?php ob_start();
session_start();
include('head.php');
include('header.php');
?>
<div id="signUpFormContainer">
<div id="signUpForm">
<div class="inputDiv">
<p>Username*</p>
<input v-model="userName" placeholder="joseChang">
</div>
<div class="inputDiv">
<p>Password*</p>
<input type="password" v-model="password" placeholder="********">
</div>
<div class="inputDiv">
<p>Confirm Password*</p>
<input type="password" v-model="confirmPassword" placeholder="********">
</div>
<div class="inputDiv">
<p>First Name*</p>
<input v-model="firstName" placeholder="Jose">
</div>
<div class="inputDiv">
<p>Last Name*</p>
<input v-model="lastName" placeholder="Chang">
</div>
<div class="inputDiv">
<p>Email*</p>
<input v-model="email" placeholder="jchang#example.com">
</div>
<div class="inputButton">
<input v-on:click.prevent="makeAccount" id="addButton" type="button" value="Sign Up"></input>
</div>
</div>
</div>
<div id="footerContainer"></div>
<script>
var app = new Vue({
el: '#signUpForm',
data: {
userName: '',
password: '',
confirmPassword: '',
firstName: '',
lastName: '',
email: ''
},
computed: {
passwordsMatch: function() {
if(this.password == this.confirmPassword) {
return true;
} else {
return false;
}
},
passwordRequirementsMet: function() {
if(this.password.length >= 8) {
return true;
} else {
return false;
}
},
validEmail: function() {
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (!reg.test(this.email)) {
return false;
}
return true;
}
},
created: function() {
},
watch: {
},
methods: {
makeAccount: function() {
if(this.userName.length >= 8 && this.firstName != '' && this.lastName != '' && this.validEmail && this.passwordRequirementsMet && this.passwordsMatch) {
var jsonString = JSON.stringify({
userName: this.userName,
firstName: this.firstName,
lastName: this.lastName,
password: this.password,
email: this.email
});
$.ajax({
url: 'makeAccount.php',
dataType: 'json',
type: 'post',
contentType: 'application/json',
dataType: 'json',
data: jsonString,
error: function(){
alert('Error');
window.location.href='result.php';
},
success: function(data){
console.log(data);
alert('success');
window.location.href='result.php';
}.bind(this)
});
}
}
}
});
</script>
<?php include('foot.php');?>
?>
Heres the code for php page im making an ajax request to. (makeAccount.php)
<?php session_start();
$_SESSION['hitpage']=1
require_once('database.php');
require_once('functions.php');
$requestBody = file_get_contents('php://input');
$requestJSON = json_decode($requestBody);
require_once 'lib/Braintree.php';
$gateway = new Braintree_Gateway([
'environment' => 'sandbox',
'merchantId' => 'ygpmj36rrztwbw6x',
'publicKey' => 'qrf7ncz6kskchgfh',
'privateKey' => '2e9ab466fca6889dd5e570ac583c8a46'
]);
$braintreeResponse = $gateway->customer()->create([
'firstName' => $requestJSON->firstName,
'lastName' => $requestJSON->lastName,
'email' => $requestJSON->email
]);
if ($braintreeResponse->success) {
echo(json_encode($braintreeResponse));
} else {
echo(json_encode($braintreeResponse));
}
function get_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$googleResponse = get_data('https://script.google.com/macros/s/AKfycbzz8Oh3Jqt5tP4wGcNyM8jVhwaMEr6S5AJ-MWqFlhPN1rSzBdSr/exec?name='.urlencode(stripslashes($requestJSON->userName)));
function get_string_between($string, $start, $end){
$string = ' ' . $string;
$ini = strpos($string, $start);
if ($ini == 0) return '';
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
}
$googleResponseParsed = get_string_between($googleResponse, '<title>', '</title>');
echo($googleResponseParsed);
$username = $requestJSON->userName;
$username = mysqli_real_escape_string($mysqli, $username);
$firstname = $requestJSON->firstName;
$firstname = mysqli_real_escape_string($mysqli, $firstname);
$lastname = $requestJSON->lastName;
$lastname = mysqli_real_escape_string($mysqli, $lastname);
$email = $requestJSON->email;
$email = mysqli_real_escape_string($mysqli, $email);
$cleanGoogleResponseParsed = $googleResponseParsed;
$cleanGoogleResponseParsed = mysqli_real_escape_string($mysqli, $cleanGoogleResponseParsed);
$customerid = $braintreeResponse->customer->id;
$customerid = mysqli_real_escape_string($mysqli, $customerid);
$password = $requestJSON->password;
$encryptedpassword=password_encrypt($password);
$makeUserSQL = "INSERT INTO user (userName, firstName, lastName, email, driveFolderId, braintreeId, password)
VALUES ('".$username."','".$firstname."','".$lastname."','".$email."','".$cleanGoogleResponseParsed."','".$customerid."','".$encryptedpassword."')";
if ($mysqli->query($makeUserSQL) === TRUE) {
echo "New record created successfully";
$_SESSION['inserted'];
} else {
echo "Error: " . $makeUserSQL . "<br>" . $mysqli->error;
}
$mysqli->close();
?>
Heres the code for result.php
<?php session_start();
if(isset($_SESSION['hitpage'])){$ajaxworked=1;} else{$axjaxworked=0;}
if(isset($_SESSION['inserted'])){$inserted=1;} else {$inserted=0;}
if($inserted==1 and $ajaxworked==1){echo 'success';}
if($inserted==0 and $ajaxworked==0){echo 'failed';}
session_destroy();
?>

this.userName doesn't exist.
You can also directly do this instead of passing by a variable :
window.location.href="successfullycreated.php?userName="+ <?php echo "'{$_GET['userName']}'";?>;

As long as the new page has the param present you can just get it from the URL in JavaScript.
var userName = new URL(window.location.href).searchParams.get("userName");

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>

Vuejs Ajax call aways fires error function

Hey Everyone so I am trying to make a vueapp that makes an ajax call to a php page. On that php page I am running a few mysql statements the most important of which is a insert statement. if that page ajax call is successful and the insert statement runs successfully I want to redirect a page. If the ajax call or the insert statement fails or the user exists I want to redirect them the same page just render the page diffrently based on the result. I've tried doing it with sessions however when i try to use the ajax error function it fires everytime even when its successful. I know this as I get an alert error. But than when it goes to the result.php page I get success. I dont understand. Any help would be great! Heres the code for the vueapp (signup.php)
<?php ob_start();
session_start();
include('head.php');
include('header.php');
?>
<div id="signUpFormContainer">
<div id="signUpForm">
<div class="inputDiv">
<p>Username*</p>
<input v-model="userName" placeholder="joseChang">
</div>
<div class="inputDiv">
<p>Password*</p>
<input type="password" v-model="password" placeholder="********">
</div>
<div class="inputDiv">
<p>Confirm Password*</p>
<input type="password" v-model="confirmPassword" placeholder="********">
</div>
<div class="inputDiv">
<p>First Name*</p>
<input v-model="firstName" placeholder="Jose">
</div>
<div class="inputDiv">
<p>Last Name*</p>
<input v-model="lastName" placeholder="Chang">
</div>
<div class="inputDiv">
<p>Email*</p>
<input v-model="email" placeholder="jchang#example.com">
</div>
<div class="inputButton">
<input v-on:click.prevent="makeAccount" id="addButton" type="button" value="Sign Up"></input>
</div>
</div>
</div>
<div id="footerContainer"></div>
<script>
var app = new Vue({
el: '#signUpForm',
data: {
userName: '',
password: '',
confirmPassword: '',
firstName: '',
lastName: '',
email: ''
},
computed: {
passwordsMatch: function() {
if(this.password == this.confirmPassword) {
return true;
} else {
return false;
}
},
passwordRequirementsMet: function() {
if(this.password.length >= 8) {
return true;
} else {
return false;
}
},
validEmail: function() {
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (!reg.test(this.email)) {
return false;
}
return true;
}
},
created: function() {
},
watch: {
},
methods: {
makeAccount: function() {
if(this.userName.length >= 8 && this.firstName != '' && this.lastName != '' && this.validEmail && this.passwordRequirementsMet && this.passwordsMatch) {
var jsonString = JSON.stringify({
userName: this.userName,
firstName: this.firstName,
lastName: this.lastName,
password: this.password,
email: this.email
});
$.ajax({
url: 'makeAccount.php',
dataType: 'json',
type: 'post',
contentType: 'application/json',
dataType: 'json',
data: jsonString,
error: function(){
alert('Error');
window.location.href='result.php';
},
success: function(data){
console.log(data);
alert('success');
window.location.href='result.php';
}.bind(this)
});
}
}
}
});
</script>
<?php include('foot.php');?>
?>
Heres the code for php page im making an ajax request to. (makeAccount.php)
<?php session_start();
$_SESSION['hitpage']=1;
require_once('database.php');
require_once('functions.php');
$requestBody = file_get_contents('php://input');
$requestJSON = json_decode($requestBody);
require_once 'lib/Braintree.php';
$gateway = new Braintree_Gateway([
'environment' => 'sandbox',
'merchantId' => '*****',
'publicKey' => '*****',
'privateKey' => '*****'
]);
$braintreeResponse = $gateway->customer()->create([
'firstName' => $requestJSON->firstName,
'lastName' => $requestJSON->lastName,
'email' => $requestJSON->email
]);
if ($braintreeResponse->success) {
echo(json_encode($braintreeResponse));
} else {
echo(json_encode($braintreeResponse));
}
function get_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$googleResponse = get_data('https://script.google.com/macros/s/AKfycbzz8Oh3Jqt5tP4wGcNyM8jVhwaMEr6S5AJ-MWqFlhPN1rSzBdSr/exec?name='.urlencode(stripslashes($requestJSON->userName)));
function get_string_between($string, $start, $end){
$string = ' ' . $string;
$ini = strpos($string, $start);
if ($ini == 0) return '';
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
}
$googleResponseParsed = get_string_between($googleResponse, '<title>', '</title>');
echo($googleResponseParsed);
$username = $requestJSON->userName;
$username = mysqli_real_escape_string($mysqli, $username);
$firstname = $requestJSON->firstName;
$firstname = mysqli_real_escape_string($mysqli, $firstname);
$lastname = $requestJSON->lastName;
$lastname = mysqli_real_escape_string($mysqli, $lastname);
$email = $requestJSON->email;
$email = mysqli_real_escape_string($mysqli, $email);
$cleanGoogleResponseParsed = $googleResponseParsed;
$cleanGoogleResponseParsed = mysqli_real_escape_string($mysqli, $cleanGoogleResponseParsed);
$customerid = $braintreeResponse->customer->id;
$customerid = mysqli_real_escape_string($mysqli, $customerid);
$password = $requestJSON->password;
$encryptedpassword=password_encrypt($password);
$selectcount="SELECT COUNT(*) as exist FROM user WHERE userName='$username'";
$countresult=mysqli_query($mysqli, $selectcount);
while($row=mysqli_fetch_assoc($countresult)){
$exists=$row['exist'];
}
if($exists==0){
$makeUserSQL = "INSERT INTO user (userName, firstName, lastName, email, driveFolderId, braintreeId, password)
VALUES ('".$username."','".$firstname."','".$lastname."','".$email."','".$cleanGoogleResponseParsed."','".$customerid."','".$encryptedpassword."')";
if ($mysqli->query($makeUserSQL) === TRUE) {
echo "New record created successfully";
$_SESSION['inserted']=1;
} else {
echo "Error: " . $makeUserSQL . "<br>" . $mysqli->error;
}
} else {$_SESSION['userexists']=1;}
$mysqli->close();
?>
Heres the code for result.php
<?php session_start();
if(isset($_SESSION['hitpage'])){$ajaxworked=1;} else{$ajaxworked=0;}
if(isset($_SESSION['inserted'])){$inserted=1;} else {$inserted=0;}
if(isset($_SESSION['userexists'])){$userexists=1;} else{$userexists=0;}
if($inserted==1 and $ajaxworked==1){echo 'Congrats you seccessfully created your account click here to go home';}
if($ajaxworked==0){echo 'Possible time out if error prosists please contact creative group click here to try again';}
if($inserted==0 and $ajaxworked==1 and $userexists==0){echo 'There was an error creating your account if error prosists please contact the creative group click here to try again';}
if($userexists==1){echo 'Sorry that user already exists click here to try again';}
session_destroy();
?>
After many tears and banging my head against the screen. Prayers to about every God under the sun and plenty of cussing I have finally found the problem. My JSON string was invalid

Message successfully sent with ajax and php but no email

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

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