Sending email using constant contact mail server instead of php mail - php

From past few days, I am searching for a solution in Constant Contact APIs at http://developer.constantcontact.com/libraries/sample-code.html,, but was unable to find it. So, below is our requirement.
In my website we have donations, memberships etc. When a user fills Donation form or Membership form or Contact form etc., once user submits the form, we need to send a confirmation email to user.Our requirement is, we want this email to be send from Constant Contact mail server instead of send grid or php mail server. we have already account in constant contact for sending news letters. we need to use those details foe sending confirmation emails for single user and store the email ID in our Constant Contact Account.
We need the helpful APIs to communicate in the above procedure/manner.
We didn't find any solution to send email for single donated user. how to send email to single user and message.
Current we are using third party service(Send Grid), now we would like to move to Constant Contact. We have developed this website in PHP programming language.
Kindly help us to integrate in the above procedure/manner.
Here i attached the file. i am getting error when i using the given API's and format
Below is my simple code
<?php
require_once 'Ctct/autoload.php';
use Ctct\ConstantContact;
use Ctct\Components\Contacts\Contact;
use Ctct\Components\Contacts\ContactList;
use Ctct\Components\Contacts\EmailAddress;
use Ctct\Components\EmailMarketing\Campaign;
use Ctct\Components\EmailMarketing\MessageFooter;
use Ctct\Components\EmailMarketing\Schedule;
use Ctct\Exceptions\CtctException;
// Enter your Constant Contact APIKEY and ACCESS_TOKEN
define("APIKEY", "xxxxxxxxxxxxxxxxxxxxxxxx");
define("ACCESS_TOKEN", "xxxxxxxx-xxxx-xxxx-xxxx-989939366970");
$date = date('Y-m-d H:i:s');
$cc = new ConstantContact(APIKEY);
try {
$lists = $cc->getLists(ACCESS_TOKEN);
} catch (CtctException $ex) {
foreach ($ex->getErrors() as $error) {
print_r($error);
}
}
print_r($lists);
if (isset($_POST['email']) && strlen($_POST['email']) > 1) {
$action = "Getting Contact By Email Address";
try {
// check to see if a contact with the email addess already exists in the account
$response = $cc->getContactByEmail(ACCESS_TOKEN, $_POST['email']);
// create a new contact if one does not exist
if (empty($response->results)) {
$action = "Creating Contact";
$contact = new Contact();
$contact->addEmail($_POST['email']);
$contact->addList($_POST['list']);
$contact->first_name = $_POST['fname'];
$contact->last_name = $_POST['fname'];
/*
* The third parameter of addContact defaults to false, but if this were set to true it would tell Constant
* Contact that this action is being performed by the contact themselves, and gives the ability to
* opt contacts back in and trigger Welcome/Change-of-interest emails.
*
* See: http://developer.constantcontact.com/docs/contacts-api/contacts-index.html#opt_in
*/
$returnContact = $cc->addContact(ACCESS_TOKEN, $contact, true);
// update the existing contact if address already existed
} else {
$action = "Updating Contact";
$contact = $response->results[0];
$contact->addList($_POST['list']);
$contact->first_name = $_POST['fname'];
$contact->last_name = $_POST['fname'];
/*
* The third parameter of updateContact defaults to false, but if this were set to true it would tell
* Constant Contact that this action is being performed by the contact themselves, and gives the ability to
* opt contacts back in and trigger Welcome/Change-of-interest emails.
*
* See: http://developer.constantcontact.com/docs/contacts-api/contacts-index.html#opt_in
*/
$returnContact = $cc->updateContact(ACCESS_TOKEN, $contact, true);
}
}
catch (CtctException $ex) {
echo '<span class="label label-important">Error ' . $action . '</span>';
echo '<div class="container alert-error"><pre class="failure-pre">';
print_r($ex->getErrors());
echo '</pre></div>';
die();
}
}
function createCampaign(array $params)
{
$cc = new ConstantContact(APIKEY);
$campaign = new Campaign();
$campaign->name = $params['fname'];
$campaign->subject = "Test Mail Subject";
$campaign->from_name = $params['fname'];
$campaign->from_email = $params['email'];
//$campaign->greeting_string = $params['greeting_string'];
//$campaign->reply_to_email = $params['email'];
$campaign->text_content = $params['content_text'];
$campaign->email_content = $params['content_text'];
$campaign->email_content_format = 'HTML';
// add the selected list or lists to the campaign
$campaign->addList('venky.para#gmail.com');
return $cc->addEmailCampaign(ACCESS_TOKEN, $campaign);
}
function createSchedule($campaignId, $time)
{
$cc = new ConstantContact(APIKEY);
$schedule = new Schedule();
$schedule->scheduled_date = $time;
return $cc->addEmailCampaignSchedule(ACCESS_TOKEN, $campaignId, $schedule);
}
global $wpdb;
if(isset($_POST['submit']))
{
$fname=mysql_real_escape_string($_POST['fname']);
$useremail=mysql_real_escape_string($_POST['email']);
$content=mysql_real_escape_string($_POST['content_text']);
// attempt to create a campaign with the fields submitted, displaying any errors that occur
try {
$campaign = createCampaign($_POST);
} catch (CtctException $ex) {
echo '<span class="label label-important">Error Creating Campaign</span>';
echo '<div class="container alert-error"><pre class="failure-pre">';
print_r($ex->getErrors());
echo '</pre></div>';
die();
}
// attempt to schedule a campaign with the fields submitted, displaying any errors that occur
try {
$schedule = createSchedule($campaign->id,$date);
} catch (CtctException $ex) {
echo '<span class="label label-important">Error Scheduling Campaign</span>';
echo '<div class="container alert-error"><pre class="failure-pre">';
print_r($ex->getErrors());
echo '</pre></div>';
die();
}
}
?>
<script type="text/javascript">
function validtestmail(){
var fname=document.getElementById('fname').value;
var email=document.getElementById('email').value;
var content_text=document.getElementById('content_text').value;
if(fname=='')
{
alert('Enter Name');
document.getElementById('fname').focus();
return false;
}
else if(email=='')
{
alert('Enter Email');
document.getElementById('email').focus();
return false;
}
else if(content_text=='')
{
alert('Enter Content');
document.getElementById('content_text').focus();
return false;
}
}
</script>
<div class="container ">
<div class="row ">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<div class="innerPagesBlock fullWidth">
<div id="primary" class="col-xs-12 col-sm-12 col-md-8 col-lg-8 content-area contactbg">
<div class="myprofileHeading">Change Password </div>
<form class="form-horizontal" role="form" id="member_cp" name="member_cp" action="<?php echo get_bloginfo('home'); ?>/testmail" method="post" onsubmit="return validtestmail();" style="margin-top:30px;">
<!-- Self form start-->
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 formLog">
<span style="font-size:16px; font-weight: bold; color: #FFFFFF;">
<?php
if($msg)
{?>
<div class="<?php echo $class; ?>" role="alert"><?php
echo $msg;
?>
</div><?php
}
?>
</span>
</div>
<div class="form-login formMain">
<label for="inputEmail3" class="col-xs-12 col-sm-4 col-md-4 col-lg-4 control-label">Name:<span>*</span></label>
<div class="col-xs-12 col-sm-8 col-md-8 col-lg-8 formLog">
<input type="text" class="form-control" id="fname" name="fname" placeholder="Name" value="" >
</div>
<label for="inputEmail3" class="col-xs-12 col-sm-4 col-md-4 col-lg-4 control-label">Email: <span>*</span></label>
<div class="col-xs-12 col-sm-8 col-md-8 col-lg-8 formLog">
<input type="text" class="form-control" id="email" name="email" placeholder="Email" value="" >
</div>
<label for="inputEmail3" class="col-xs-12 col-sm-4 col-md-4 col-lg-4 control-label">Content: <span>*</span></label>
<div class="col-xs-12 col-sm-8 col-md-8 col-lg-8 formLog">
<input type="text" class="form-control" id="content_text" name="content_text" placeholder="Content" value="" >
</div>
<div class="col-xs-6 col-sm-2 col-md-2 col-lg-2 formLog">
<button type="submit" class="btn btn-primary btnSubmit" name="submit" id="submit">Submit</button>
</div>
<div class="col-xs-6 col-sm-2 col-md-2 col-lg-2 formLog">
<button type="reset" name="button2" id="button2" class="btn btn-primary btnReset">Reset</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<div id="main-content" class="main-content">
<?php
if ( is_front_page() && twentyfourteen_has_featured_posts() ) {
// Include the featured content template.
get_template_part( 'featured-content' );
}
?>
</div><!-- #main-content -->
Here how to send email to single user. How?. Is it possible?. Please help me. My time wasting from last 2 weeks.
Thanking You

You need to cast $_POST['list'] as a string. It may be posting as an integer.
Changing this:
$contact->addList($_POST['list']);
to this:
$contact->addList( (string)$_POST['list'] );
would probably do it.

Related

How to display message in HTML Tag with PHP in a function

I have this PHP form validator that is also hooked up to a mail function and to keep things organized I did the form validation in a separate function that is being called when the form is submitted.
Now I have this problem that I don't know how to display the error message when a field is empty in the HTML form.
Can anyone help? Thank you in advance.
I'm also pretty new to PHP and the whole thing.
PHP:
<?php
// Validation function
function validation($name, $email, $message) {
// Searching for every empty POST variable
// And if empty push into $error array
if (empty($name)) {
array_push($errors, "Name");
}
if (empty($email)) {
array_push($errors, "E-Mail");
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$mail_error = " and E-Mail must be correct/filled out.";
}
if (empty($message)) {
array_push($errors, "Message");
}
// Combining all index of array to one final string
$final = implode(", ", $errors);
// Adding additional string to final
$final .= " is not allowed to be empty." . $mail_error . "\n";
return $final;
}
if (isset($_POST["submit"])) {
// Defining POST variables for validation and mail content
$fname = $_POST["fname"];
$femail = $_POST["femail"];
$fmessage = $_POST["fmessage"];
// Defining variable for pushing errors for validation
$errors = array();
// Calling function
validation($fname, $femail, $fmessage);
}
HTML:
<form name="main-form" action="" method="post" class="row g-3 pt-1 p-5 bg-custom">
<div class="input-group mb-3 col-md-6">
<span class="input-group-text">Name</span>
<input name="fname" type="text" class="form-control me-3 " placeholder="Name" aria-label="Name">
<span class="input-group-text">E-Mail</span>
<input name="femail" type="email" class="form-control" placeholder="example#mail.com"aria-label="example#mail.com">
</div>
<div class="input-group mb-3 col-md-12 col-sm-6">
<span class="input-group-text">Message</span>
<textarea name="fmessage" type="text" class="form-control"></textarea>
</div>
<!-- The error message if a field is empty should be displayed here: -->
<p id="error-message" class="text-center text-danger"><?php echo($final); ?></p>
<div class="col-md-12 text-center">
<button class="btn btn-primary me-2" id="btn-send" style="width: 30%;" class="btn btn-primary me-2" type="submit" name="submit">Send</button>
</div>
</form>
<?php
// Validation function
function validation($name, $email, $message) {
$errors = [];
$final = "";
// Searching for every empty POST variable
// And if empty push into $error array
if (empty($name)) {
array_push($errors, "Name");
}
if (empty($email)) {
array_push($errors, "E-Mail");
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$mail_error = " and E-Mail must be correct/filled out.";
}
if (empty($message)) {
array_push($errors, "Message");
}
// Combining all index of array to one final string
$final = implode(", ", $errors);
// Adding additional string to final
$final .= " is not allowed to be empty." . $mail_error . "\n";
return $final;
}
if (isset($_POST["submit"])) {
// Defining POST variables for validation and mail content
$fname = $_POST["fname"];
$femail = $_POST["femail"];
$fmessage = $_POST["fmessage"];
// Defining variable for pushing errors for validation
// Calling function
$error = validation($fname, $femail, $fmessage);
}
HTML
<form name="main-form" action="" method="post" class="row g-3 pt-1 p-5 bg-custom">
<div class="input-group mb-3 col-md-6">
<span class="input-group-text">Name</span>
<input name="fname" type="text" class="form-control me-3 " placeholder="Name" aria-label="Name">
<span class="input-group-text">E-Mail</span>
<input name="femail" type="email" class="form-control" placeholder="example#mail.com"aria-label="example#mail.com">
</div>
<div class="input-group mb-3 col-md-12 col-sm-6">
<span class="input-group-text">Message</span>
<textarea name="fmessage" type="text" class="form-control"></textarea>
</div>
<!-- The error message if a field is empty should be displayed here: -->
<p id="error-message" class="text-center text-danger"><?=if(isset($error)); $error : "";?></p>
<div class="col-md-12 text-center">
<button class="btn btn-primary me-2" id="btn-send" style="width: 30%;" class="btn btn-primary me-2" type="submit" name="submit">Send</button>
</div>
</form>
$error = validation($fname, $femail, $fmessage); store data in variable and
isset() use to check variable exist or not

Get multiple email adresses from a textarea

I have a question: i need to create a POST method form with a textarea, where the user can copy-paste multiple email adressses and my form should be able to do something with each adress separately.
And i don't know how to tell to php to recognize each email adress separately from the POST value of the textarea and insert them into a table of my database for example.
so my code looks like that for the moment:
<?php
if($_POST) {
if(!empty($_POST['emails'])) {
$emails = explode(" ", $_POST['Emails']);
foreach($emails as $email) {
/* Do something with each adresses ( like inserting them into a
table in my database for example) */
}
}
}
?>
<html>
<form class="mx-auto" method="POST" id="invitations">
<div class="form-group w-50 mx-auto text-center">
<label for="emails">Insert the email adresses</label>
<textarea name="emails" id="emails"></textarea>
<button id="send-data" class="btn btn-primary mx-auto my-5 text-center">Send the invitations</button>
</div>
</form>
</html>
<?php
if(!empty($_POST['Emails'])) {
$emails = explode(" ", $_POST['Emails']);
foreach($emails as $email) {
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Do something
} else {
echo "This email adress is not valid => $email !";
return;
/* here if something else than a space or a valid email adress is inserted
the foreach will be exited and a error message specifying where
something was wrong is displayed :) */
}
}
} else {
$feedback = "Please insert one or multiple email adress(es)";
}
if(isset($feedback) and !empty($feedback)) {
echo $feedback;
}
?>
<html>
<form class="mx-auto" method="POST" id="invitations">
<div class="form-group w-50 mx-auto text-center">
<label for="emails">Insert the email adresses</label>
<small>Separate them with a space</small>
<textarea name="emails" id="emails"></textarea>
<button id="send-data" class="btn btn-primary mx-auto my-5 text-center">Send the invitations</button>
</div>
</form>
</html>

Contact Form Stuck in Validation

I am trying to get a contact form up and running for a portfolio website. I understand design, but have a very limited understanding of development/server side issues.
The form functions as expected, BUT when submitted the form returns "..sending" and things stop there. I do not receive an email, and the status does not progress.
My site is hosted on Hostinger, who does not utilize Apache (of which I have no understanding). However, from what I have read, I do need some type of php server like apache to make this form function. The host says that they do support Ajax and that the emails are not being blocked.
I am trying to use Ajax, with validate script, and php to allow form submission without leaving the current page as follows: (this is a MDB form). This is a link to the hosted site for reference: https://intakt-design.com
I am receiving this error in dev tools: Uncaught reference error: sendMessage() is not defined at validate form
I feel like this is the problem, but I don't know what goes here, and google is leading me in circles...
code snippet link: https://mdbootstrap.com/snippets/jquery/marcin-luczak/2705367
Please excuse my ignorance, I'm new to web design (graphic design student), in general, and backend development is way over my head.
PHP:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$subject = $_POST['subject'];
header('Content-Type: application/json');
if ($name === ''){
print json_encode(array('message' => 'Name cannot be empty', 'code' => 0));
exit();
}
if ($email === ''){
print json_encode(array('message' => 'Email cannot be empty', 'code' => 0));
exit();
} else {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
print json_encode(array('message' => 'Email format invalid.', 'code' => 0));
exit();
}
}
if ($subject === ''){
print json_encode(array('message' => 'Subject cannot be empty', 'code' => 0));
exit();
}
if ($message === ''){
print json_encode(array('message' => 'Message cannot be empty', 'code' => 0));
exit();
}
$content="From: $name \nEmail: $email \nMessage: $message";
$recipient = "story#intakt-design.com";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $content, $mailheader) or die("Error!");
print json_encode(array('message' => 'Email Delivered! Thanks for contacting inTakt Design!', 'code' => 1));
exit();
?>
HTML:
<!-- Contact Form -->
<div class="contact-content py-5">
<section class="mb-4 col-11 col-sm-10 col-lg-8 mx-auto mt-0 mb-3 form">
<!--Section heading-->
<h2 class="h1-responsive font-weight-bold text-center p-3 my-4 form-text form-head">Just Fill in the Blanks!</h2>
<!--Section description-->
<p class="text-center w-responsive mx-auto mb-5 form-text form-subhead">Do you have any questions or inquiries? Please do not hesitate to contact me directly.<br />I will typically respond within 24 hours.</p>
<div class="row">
<!--Grid column-->
<div class="col-md-9 mb-md-0 mb-5">
<form id="contact-form" name="contact-form">
<!--Grid row-->
<div class="row">
<!--Grid column-->
<div class="col-md-6 form-field-containers">
<div class="md-form mb-0 form-field-containter">
<input type="text" id="name" name="name" class="form-control">
<label for="name" class="form-text form-field mt-n1">Your name</label>
</div>
</div>
<!--Grid column-->
<!--Grid column-->
<div class="col-md-6 form-field-containers">
<div class="md-form mb-0 form-field-container">
<input type="text" id="email" name="email" class="form-control">
<label for="email" class="form-text form-field mt-n1">Your email</label>
</div>
</div>
<!--Grid column-->
</div>
<!--Grid row-->
<!--Grid row-->
<div class="row">
<div class="col-md-12 mt-3 form-field-containers">
<div class="md-form mb-0 form-field-container">
<input type="text" id="subject" name="subject" class="form-control">
<label for="subject" class="form-text form-field mt-n1">Subject</label>
</div>
</div>
</div>
<!--Grid row-->
<!--Grid row-->
<div class="row">
<!--Grid column-->
<div class="col-md-12 mt-3">
<div class="md-form message-container">
<textarea type="text" id="message" name="message" rows="2" class="form-control md-textarea p-2 message waves-effect"></textarea>
<label for="message" class="form-text form-field mt-n1 message-label"><span class="message-canned-txt italic">Type Your Message Here</span></label>
</div>
</div>
</div>
<!--Grid row-->
</form>
<div class="text-center text-md-left">
<a class="btn btn-rounded waves-effect cta-btn-res col-12 col-lg-5 mt-3 mb-0" onclick="validateForm();">Submit</a>
</div>
<div class="status" id="status"></div>
</div>
<!--Grid column-->
<!--Grid column-->
<div class="col-md-3 text-center">
<ul class="list-unstyled mb-0">
<li><br />
Connect with Me!
</li>
<li><br />
+ 501 259 6907
</li>
<li><br />
story#intakt-design.com
</li>
</ul>
</div>
<!--Grid column-->
</div>
</section>
<!--/ Contact Form-->
JS:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery-3.5.1.js"></script>
<script type="text/javascript" src="popper.js"></script>
<script type="text/javascript" src="js/bootstrap.bundle.js"></script>
<script type="text/javascript" src="js/mdb.js"></script>
<script type="text/javascript" src="js/mdb.pro.js"></script>
<!--Custom scripts-->
<script>
function validateForm() {
var name = document.getElementById('name').value;
if (name == "") {
document.querySelector('.status').innerHTML = "Name cannot be empty";
return false;
}
var email = document.getElementById('email').value;
if (email == "") {
document.querySelector('.status').innerHTML = "Email cannot be empty";
return false;
}
else {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if(!re.test(email)){
document.querySelector('.status').innerHTML = "Email format invalid";
return false;
}
}
var subject = document.getElementById('subject').value;
if (subject == "") {
document.querySelector('.status').innerHTML = "Subject cannot be empty";
return false;
}
var message = document.getElementById('message').value;
if (message == "") {
document.querySelector('.status').innerHTML = "Message cannot be empty";
return false;
}
document.querySelector('.status').innerHTML = "Sending...";
sendMessage();
}
function sendMessge() {
formData = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'subject' : $('input[name=subject]').val(),
'message' : $('textarea[name=message]').val()
};
$.ajax({
url : "mail.php",
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR)
{
$('#status').text(data.message);
if (data.code) //If mail was sent successfully, reset the form.
$('#contact-form').closest('form').find("input[type=text], textarea").val("");
},
error: function (jqXHR, textStatus, errorThrown)
{
$('#status').text(jqXHR);
}
});
}
</script>
I don't know why, but for some unusual reasons the sendMessage is not working. Try to rename the function. messageSending() in your js file and call it in your validateForm() function.
function validateForm() {
var name = document.getElementById('name').value;
if (name == "") {
document.querySelector('.status').innerHTML = "Name cannot be empty";
return false;
}
var email = document.getElementById('email').value;
if (email == "") {
document.querySelector('.status').innerHTML = "Email cannot be empty";
return false;
}
else {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if(!re.test(email)){
document.querySelector('.status').innerHTML = "Email format invalid";
return false;
}
}
var subject = document.getElementById('subject').value;
if (subject == "") {
document.querySelector('.status').innerHTML = "Subject cannot be empty";
return false;
}
var message = document.getElementById('message').value;
if (message == "") {
document.querySelector('.status').innerHTML = "Message cannot be empty";
return false;
}
document.querySelector('.status').innerHTML = "Sending...";
messageSending();
}
function messageSending() {
document.querySelector('.status').innerHTML = "123Sending...";
formData = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'subject' : $('input[name=subject]').val(),
'message' : $('textarea[name=message]').val()
};
$.ajax({
url : "mail.php",
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR)
{
$('#status').text(data.message);
if (data.code) //If mail was sent successfully, reset the form.
$('#contact-form').closest('form').find("input[type=text], textarea").val("");
},
error: function (jqXHR, textStatus, errorThrown)
{
$('#status').text(jqXHR);
}
});
}

Strange issue with timestamp update in MYSQL

I have a strange issue i have come accross on a few sites i have built, but i am unable to find the problem, it seems so simple, when a user logs in to the site i update the timestamp for the column "member_login" to NOW() which works great, the only issue is, it also updates the "member_joined" column to the exact same time as the "member_login" timestamp but NOWHERE in the code do i tell it to update the "member_joined" column! the entire login script is fairly simple:
login.php
<?php
session_start();
include('includes/db_connection.php');
include('includes/functions.php');
?>
<?php
if (isset($_POST['submitLogin'])) {
$username = trim(strtolower($_POST['username']));
$password = trim(strtolower($_POST['password']));
if (empty($username) || empty($password)) {
include('includes/header.php');
include('includes/navbar.php');
stderr('Please fill in <b>both</b> login fields.');
include('includes/footer.php');
}
$memberInfo = DB::getInstance()->selectOne(
'
SELECT DISTINCT member_username, member_fees_paid, member_fees_paid_on
FROM `membership`
WHERE `member_username` = :member_username
AND `member_password` = :member_password',
[
'member_username' => $username,
'member_password' => $password
]
);
if (!count($memberInfo)) {
include('includes/header.php');
include('includes/navbar.php');
stderr('Sorry, username <b>and/or</b> password combination not found.');
include('includes/footer.php');
} else {
$_SESSION['member'] = $username;
if ($memberInfo['member_fees_paid'] === 'N') {
$payedOn = new \DateTime($memberInfo['member_fees_paid_on']);
$payedOn->setTime(0, 0, 0);
$monthAgo = new \DateTime('28 days ago');
$monthAgo->setTime(0, 0, 0);
if ($monthAgo > $payedOn) {
try {
DB::getInstance()->execute(
'
UPDATE `membership`
SET `member_fees_paid`= \'N\'
WHERE `member_username` = :member_username
AND `member_password` = :member_password',
[
'member_username' => $username,
'member_password' => $password
]
);
header('Location: my-account.php');
} catch (Exception $e) {
include('includes/header.php');
include('includes/navbar.php');
stderr($e->getMessage());
include('includes/footer.php');
}
}
}
try {
DB::getInstance()->execute(
'
UPDATE `membership`
SET `member_login` = NOW()
WHERE `member_username` = :member_username
AND `member_password` = :member_password',
[
'member_username' => $username,
'member_password' => $password
]
);
header('Location: my-account.php');
} catch (Exception $e) {
include('includes/header.php');
include('includes/navbar.php');
stderr($e->getMessage());
include('includes/footer.php');
}
}
}
?>
<?php
include('includes/header.php');
include('includes/navbar.php');
?>
<div class="panel panel-primary">
<div class="panel-heading">Login to your account.</div>
<div class="panel-body">
<form action="login.php" method="post" class="form-horizontal container-fluid" role="form">
<div class="row form-group">
<div class="col-sm-6 text-right">
<label class="control-label">Username:</label>
</div>
<div class="col-sm-6">
<input type="text" name="username" class="form-control" size="40" required="required"/>
</div>
</div>
<div class="row form-group">
<div class="col-sm-6 text-right">
<label class="control-label">Password:</label>
</div>
<div class="col-sm-6">
<input type="password" name="password" class="form-control" size="40" required="required"/>
</div>
</div>
<div class="row form-group">
<div class="col-sm-6 text-right">
<label class="control-label" style="display: inline-block;"> </label>
</div>
<div class="col-sm-6 text-right">
<button type="submit" name="submitLogin" class="btn btn-primary">Login</button>
</div>
</div>
</form>
</div>
<div class="panel-footer">Forgot <b>your password</b>? recover it here.</div>
</div>
<?php
include('includes/footer.php');
On a successful login we just update the timestamp for the "member_login" and redirect to the "my-account.php" page, which works as it should, but it keeps updating the "member_joined" colums the same as the "member_login" i cannot figure out why it is doing this, any help would be appreciated!
If your column member_joined is type timestamp, you might want to check that on update CURRENT_TIMESTAMP isn't being used - you can check this in a database reader such as phpMyAdmin, SequalPro, Heidi etc.
This will automatically update the datestamp to the current date/time.

Ajax live insertion double submit glitch

This code is a savings system. But the withdrawal is not finished yet because i've found a glitch in my code. This code works fine. It can validate properly and deposite properly. And i found the glitch after I accidentally press the enter twice. And i noticed that i inserted two records in the database before clearing the password of the cashier. I want is even the cashier pressed the enter twiced.It's just insert one record in the transaction table.
this is my SavingsAddInsert.php
<?php
include("general.php");
if(isset($_POST['Submit'])){
$Amount = $_POST['Amount'];
$Password = $_POST['Password'];
$Transaction = $_POST['Transaction'];
$SaverAccount = $_POST['AccountID'];
if(empty($Amount) && empty($Password) && $Transaction == "undefined"){
$error[] = "Please Select Transaction Type and put an Amount and Password!";
}else{
if(empty($Amount) === true || $Amount === null){
$error[] = "Amount is empty";
}else{
if(!preg_match('/^[0-9.]*$/',$Amount)){
$error[] = "i only accept numeric and decimal";
}
}
if(empty($Password) === true || $Password === null){
$error[] = "Password is empty";
}else{
$Cashier_Password = Cashier_password($_SESSION['AccountID'],$Password);
if($Cashier_Password === false){
$error[] = "Cashier Password is wrong";
}
}
if($Transaction == "undefined"){
$error[] = "Please select Category in Transaction Type ";
}else{
if($Transaction == "WITHDRAW"){
if($Amount > Check_Balance($SaverAccount)){
$error[] = "Insufficient Balance!";
}
}
}
}
if(isset($error)){
echo output_errors($error);
}
if(empty($error) || $error = 0){
if($Transaction == "DEPOSITE"){//deposite
$Balance = Check_Balance($SaverAccount);
$TotalAmount = $Balance + $Amount;
$Cashier = $_SESSION['AccountID'];
$SavingsID = Get_SavingsID($SaverAccount);
$update_savings = mysql_query("UPDATE tblsavings SET TotalSavings = '$TotalAmount' WHERE AccountID = '$SaverAccount'");
if($update_savings){
$insert_transaction = mysql_query("INSERT INTO tbltransaction
(SavingsID,Cashier,ReceiveWithdraw,RunningBalance,TransactionType,Date,Time) VALUES
('$SavingsID','$Cashier','$Amount','$TotalAmount','$Transaction',now(),now())") or die(mysql_error());
if($insert_transaction){
echo "<p><i class='fa fa-check' aria-hidden='true'></i>Transaction Complete. The Total Amount of AccountNo:'".get_AccountNo($SaverAccount)."' is ".$TotalAmount."</p>";
}
}
}
else if($Transaction == "WITHDRAW"){//withdraw
unset($Password);
}
}
}
?>
this is my SavingsAdd.php
<div class="popup-wrapper">
<div class="popup-body">
<div class="popup-head">
<p>Withdraw and Deposite</p>
</div>
<?php
if(isset($_GET['Account'])){
$Account = $_GET['Account'];
$get_info1 = mysql_query("SELECT tbluserdetail.FirstName,
tbluserdetail.MiddleName,
tbluserdetail.LastName,
tbluserdetail.Image,
tbluserdetail.ImageName,
tbluserdetail.Gender,
useraccounts.AccountNo,
useraccounts.AccountID,
useraccounts.Position
FROM useraccounts
INNER JOIN tbluserdetail
ON useraccounts.UserID=tbluserdetail.UserID
WHERE useraccounts.AccountID = '$Account'");
while($row1 = mysql_fetch_array($get_info1)){
$FirstName_p = $row1['FirstName'];
$MiddleName_p = $row1['MiddleName'];
$LastName_p = $row1['LastName'];
$AccountNo_p = $row1['AccountNo'];
$AccountID_p = $row1['AccountID'];
$Gender_p = $row1['Gender'];
$Image_p = $row1['Image'];
?>
<div class="container-fluid">
<div class="row">
<div class="p-header col-md-2 col-sm-2 col-xs-2">
<?php
if(empty($Image_p)){
if($Gender_p == "Male"){
echo '<img src="img/default-male.jpg"/>';
}else if($Gender_p == "Female"){
echo '<img src="img/default-female.jpg"/>';
}
}else{
echo '<img src="data:image/jpeg;base64,'.base64_encode( $Image_p ).'"/>';
}
?>
</div>
<div class="p-info col-md-9 col-sm-9 col-xs-9">
<div class="row">
<p><?php if(isset($_GET['Account'])){ echo $FirstName_p." ".$MiddleName_p." ".$LastName_p;} ?></p>
</div>
<div class="row">
<p>Account No: <?php if(isset($_GET['Account'])){ echo $AccountNo_p;} ?></p>
</div>
</div>
</div>
<hr/>
<div id="ajaxResult">
</div>
<hr/>
<div class="row">
<div class="col-md-5 col-sm-5 col-xs-5">
<p>Transaction Type:</p>
</div>
<div class="col-md-7 col-sm-7 col-xs-7">
<select class="form-control" name="Transaction">
<option value="undefined">Select</option>
<option value="WITHDRAW">Withdraw</option>
<option value="DEPOSITE">Deposite</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-5 col-sm-5 col-xs-5">
<p>Amount:</p>
</div>
<div class="col-md-7 col-sm-7 col-xs-7">
<input type="text" class="form-control" name="Amount" id="Amount" placeholder="0.00"/>
<input type="hidden" class="form-control" name="AccountID" id="AccountID" value="<?php if(isset($_GET['Account'])){ echo $AccountID_p;} ?>" readonly>
</div>
</div>
<div class="row">
<div class="col-md-5 col-sm-5 col-xs-5">
<p>Cashier password:</p>
</div>
<div class="col-md-7 col-sm-7 col-xs-7">
<input type="password" class="form-control" name="Password" id="Password" placeholder="••••••••••"/>
</div>
</div>
<div class="row">
<div class="float-right col-md-12">
<input type="button" value="Cancel" name="Cancel" class="btn btn-danger"/>
<input type="submit" value="Submit" name="Submit" id="Submit" class="btn btn-success"/>
</div>
</div>
</div>
<?php }}?>
</div>
</div>
and this is my javascript inside the SavingsAdd.php
var form = document.forms.namedItem("myForm");
form.addEventListener('submit', function(ev) {
var oOutput = document.getElementById("ajaxResult"),
fn = new FormData(form);
fn.append("Submit", fn.get('Submit'));
fn.append("Amount", fn.get('Amount'));
fn.append("AccountID", fn.get('AccountID'));
fn.append("Password", fn.get('Password'));
fn.append("Transaction", fn.get('Transaction'));
var xhr = new XMLHttpRequest();
xhr.open('POST', 'SavingAddInsert.php', true);
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
if(form){
document.getElementById('Amount').value = null;
document.getElementById('Password').value = null;
var return_data = xhr.responseText;
document.getElementById("ajaxResult").innerHTML = return_data;
}
}
}
xhr.send(fn);
ev.preventDefault();
}, false);
as you can see in the image. i try to submit by pressing double enter. and the record inserted it twice.
You reset the passwort input field only after you receive a response from the server. You need to do this directly after you send the request.
If you want to keep the data (including passwort) in case the request fails, you need to add a variable stating if a request is active (and waiting). Set this to 1 or 'active' instead of emptying the password field and reset after the request was successful. As long as a request is active, your JS must not send another request.

Categories