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
Related
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");
For some reason I get status:error result when I try to log in on the client, which is weird cause if I hard-code the userName and password in the query, then I get: {"status":"ok", "userId":"103", "userRole":"1", "userName":"a#a.dk", "firstName":"A", "lastName":"A", "image":"img_webshop/userimage-5a2694e0b8c7f.png"} Can you help me ?
Probably the data from the browser never comes in? Which is also weird cause it looks right to me. I have no idea what can be wrong? I have been trying to fix this for a couple of days now.
My Login API:
<?php
session_start();
try {
// connect to the database
require 'connect.php';
// data from the browser
$sUserName = $_POST['txtEmailorPhoneNumber'];
$sPassword = $_POST['txtPassword'];
// create a query to compare data in the database with data from the browser
$query = $conn->prepare("SELECT * FROM users WHERE userName=':userName' AND password=':password'");
$query->bindParam( ':userName' , $sUserName );
$query->bindParam( ':password' , $sPassword );
// run query
$bResult = $query->execute();
$ajResult = $query->fetch(PDO::FETCH_ASSOC);
// take each property one by one
$sUserId = $ajResult['userId'];
$_SESSION['sUserId'] = $sUserId;
$sUserRole = $ajResult['userRoles_roleId'];
$sUserName = $ajResult['userName'];
$sFirstName = $ajResult['firstName'];
$sLastName = $ajResult['lastName'];
$sImagePath = $ajResult['image'];
$sjResponse = $bResult ? '{"status":"ok", "userId":"'.$sUserId.'", "userRole":"'.$sUserRole.'", "userName":"'.$sUserName.'", "firstName":"'.$sFirstName.'", "lastName":"'.$sLastName.'", "image":"'.$sImagePath.'"}' : '{"status":"error"}';
echo $sjResponse;
} catch (Exception $e) {
echo "ERROR";
}
?>
On the client:
// Logs in the user and displays different HTML bits according diffrent roles by using sessionstorage
btnLoginForm.addEventListener( "click", loginUser );
function loginUser() {
// it is not the OPTIMAL way to fix the reload issue and there
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if ( this.readyState == 4 && this.status == 200 ) {
ajUserDataFromServer = JSON.parse(this.responseText);
console.log( "Response:", ajUserDataFromServer );
if ( ajUserDataFromServer.status == "ok" ) {
//after login also sets key values to the sessionstorage
sessionStorage.setItem( 'status', 'loggedin' );
sessionStorage.setItem( 'userId', ajUserDataFromServer.userId );
sessionStorage.setItem( 'userRole', ajUserDataFromServer.userRole );
sessionStorage.setItem( 'userName', ajUserDataFromServer.userName );
sessionStorage.setItem( 'firstName', ajUserDataFromServer.firstName );
sessionStorage.setItem( 'lastName', ajUserDataFromServer.lastName );
sessionStorage.setItem( 'image', ajUserDataFromServer.image );
pageLogin.style.display = "none";
loggedin = true;
// for ADMIN view
if ( (loggedin === true ) && (sessionStorage.getItem( 'userRole' ) === "1" ) ) {
showWelcomeMessage();
showAdminInterface();
getProductData();
getUserData();
getSubriberData();
// for USER view
} else if (loggedin === true && sessionStorage.getItem('userRole') === "2") {
showWelcomeMessage();
showUserInterface();
getProductData();
}
} else {
//console.log( "LOGIN FAIL - TRY AGAIN" );
pageLogin.style.display = "flex";
pageViewProducts.style.display = "none";
lblLoginErrorMessage.innerHTML = "";
var sLoginErrorMessage = "Login Failed - Try again";
lblLoginErrorMessage.insertAdjacentHTML('beforeend', sLoginErrorMessage );
}
}
}
ajax.open( "POST", "api_login_users.php", true );
var jFrmLogin = new FormData( frmLogin );
ajax.send( jFrmLogin );
}
And my html, however I triple checked the input fields name, but there is no typo and looks the same in the API too.
<!-- LOGIN for USERS and ADMIN -->
<div id="pageLogin" class="page popup">
<div class="wrapper">
<h3>LOGIN</h3>
<form class="form" id="frmLogin">
<input type="text" name="txtEmailorPhoneNumber" placeholder="Mobile number or Email" required>
<input type="text" name="txtPassword" placeholder="Password" required>
<button type="button" class="btnForm" id="btnLoginForm">Login</button>
<div class="lblFormExtention">
<p class="pnoAccount">DonĀ“t have an account?</p>
<button type="button" class="btnShowPage" id="btnSignup">Signup</button>
</div>
</form>
<h3 class="lblErrorMessage" id="lblLoginErrorMessage"></h3>
</div>
</div>
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
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";
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!