How to use ajax for login form - javascript

I am currently creating a login form in PHP PDO and I am using ajax to display the relevant messages on screen, e.g.
"Logging in..."
"Some input fields are empty"
"Your username is required"
"Your password is required"
Validation such as checking if input fields are empty is working fine along with when login credentials appear to be incorrect however when I login with correct credentials I just get message "Logging in..." and nothing happens, I don't even think it sets the session. I have also added a token to prevent CSRF and was just wondering if i'm using it correctly.
I'm unsure of what is causing my code not to proceed with logging in.
my ajax script:
<script type='text/javascript'>
$(document).ready(function () {
var submitButton = $("#btn-login");
submitButton.on('click', function (e) {
e.preventDefault();
// Get input field values of the contact form
var loginFormInputs = $('#login-form :input'),
userName = $('#txt_uname_email').val(),
userPassword = $('#txt_password').val(),
token = $('#token').val(),
alertMessage = $('#login-alert-message');
// Disable Inputs and display a loading message
alertMessage.html('<p style="opacity: 1"><i class="fa fa-spinner fa-spin text-success"></i> Logging in..</p>');
submitButton.html('<i class="fas fa-spinner fa-spin"></i>');
loginFormInputs.prop("disabled", true);
// Data to be sent to server
var post_data = {
'form': 'loginForm',
'userName': userName,
'userPassword': userPassword,
'token': token
};
// Ajax post data to server
$.post('./api', post_data, function (response) {
// Load jsn data from server and output message
if (response.type === 'error') {
alertMessage.html('<p><i class="fa-lg far fa-times-circle text-danger"></i> ' + response.text + '</p>');
submitButton.html('Login');
loginFormInputs.prop("disabled", false);
} else {
alertMessage.html('<p><i class="fa-lg far fa-check-circle text-success"></i> ' + response.text + '</p>');
submitButton.html('Login');
window.location = "dashboard";
}
}, 'json');
});
});
</script>
My login function (class.user.php) which is used in api.php:
public function doLogin($uname,$umail,$upass)
{
try
{
$stmt = $this->conn->prepare("SELECT * FROM `settings` LIMIT 1");
$stmt->execute();
$mainten=$stmt->fetch(PDO::FETCH_ASSOC);
$stmt = $this->conn->prepare("SELECT user_id, user_name, user_email, user_pass, status FROM users WHERE user_name=:uname OR user_email=:umail ");
$stmt->execute(array(':uname'=>$uname, ':umail'=>$umail));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() == 1)
{
if(password_verify($upass, $userRow['user_pass']))
{
session_regenerate_id(false);
return ["correctPass"=>true, "banned"=> ($userRow['status']== 1) ? true : false, "maintenance"=> ($mainten["maintenance"]== 1) ? true : false];
}
else
{
return ["correctPass"=>false];
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
api.php:
//include class.user.php here and set $login = new USER();
//set $uname, $umail, $upass, $token vars here
if( $_POST && $_POST["form"] === 'loginForm' ) {
// Use PHP To Detect An Ajax Request code is here
// Checking if the $_POST vars well provided, Exit if there is one missing code is here
// PHP validation for the fields required code is here
$validation = $login->doLogin($uname,$umail,$upass);
if($validation["correctPass"]){
if($validation["maintenance"]){
if (!in_array($uname, array('admin'))){
$output = json_encode(
array(
'type' => 'error',
'text' => 'Website under maintenance.'
));
die($output);
}
}
if($validation["banned"]){
$output = json_encode(
array(
'type' => 'error',
'text' => 'User has been banned.'
));
die($output);
}else{
if(Token::check($_POST['token'])) {
$stmtt = $login->runQuery("SELECT user_id FROM users WHERE user_name=:uname OR user_email=:umail ");
$stmtt->execute(array(':uname'=>$uname, ':umail'=>$umail));
$userRow=$stmtt->fetch(PDO::FETCH_ASSOC);
$_SESSION['user_session'] = $userRow['user_id'];
$output = json_encode(
array(
'type' => 'message',
'text' => 'Logged in successfully.'
));
die($output);
//$success = "Logged in successfully, redirecting..";
//header( "refresh:3;url=ab" );
//$login->redirect('dashboard');
} else {
$output = json_encode(
array(
'type' => 'error',
'text' => 'Unexpected error occured.'
));
die($output);
}
}
}
else{
$output = json_encode(
array(
'type' => 'error',
'text' => 'Incorrect username or password.'
));
die($output);
}
}

Related

Woocommerce API connection to place order button

I am trying to connect to an api using the code below, so when the customer clicks on the "place order" button on the Woocommerce checkout page, I am getting a "please try again" error:
var amount = <?php global $woocommerce; print WC()->cart->total; ?>;
var merchantOrderId = '<?php echo print time(); ?>';
var apiKey = 'm85BXXLpf_icrSvqbElR11xquEgmKZ8wfeRb2ly3-G7pIwCKDuytgplB7AQGi-5t';
renderMMoneyPaymentButton(amount, merchantOrderId, apiKey);
I am trying to pass this information to the api via this function but I am not getting a successful connection.
public function process_payment( $order_id ) {
global $woocommerce;
// we need it to get any order detailes
$order = new WC_Order($order_id);
/*
* Array with parameters for API interaction
*/
$args = array(
'amount' => '<?php global $woocommerce; print WC()->cart->total; ?>',
'merchant_order_id' => '<?php print time(); ?>',
'api_Key' => 'm85BXXLpf_icrSvqbElR11xquEgmKZ8wfeRb2ly3-G7pIwCKDuytgplB7AQGi-5t',
'currency' => 'BBD',
);
/*
* Your API interaction could be built with wp_remote_post()
*/
$response = wp_remote_post( 'https://api.mmoneybb.com/merchant/js/mmoney-payment.js', $args );
if( !is_wp_error( $response ) ) {
$body = json_decode( $response['body'], true );
// it could be different depending on your payment processor
if ( $body ['$response'] == 'APPROVED') {
// we received the payment
$order->payment_complete();
$order->reduce_order_stock();
// some notes to customer (replace true with false to make it private)
$order->add_order_note( 'Thanks for your payment!!!!', true );
// Empty cart
$woocommerce->cart->empty_cart();
// Redirect to the thank you page
return array(
'result' => 'success',
'redirect' => $this->get_return_url( $order )
);
} else {
wc_add_notice( 'Please try again.', 'error' );
return;
}
} else {
wc_add_notice( 'Connection error.', 'error' );
return;
}
}
let me know what i am doing wrong much appreciated also this is the other script as well
function renderMMoneyPaymentButton(amount, merchantOrderId, apiKey) {
let paymentParams = {
amount: amount,
api_key: apiKey,
currency: 'BBD',
merchant_order_id: merchantOrderId,
onCancel: function () { console.log('Modal closed'); },
onError: function(error) { console.log('Error', error); },
onPaid: function (invoice) { console.log('Payment complete', invoice); }
};
// "mMoney" window global provided by sourcing mmoney-payment.js script.
// Attach the button to the empty element.
mMoney.payment.button.render(paymentParams, '#mmoney-payment-button');
}
1) In your first snippet code you are using javascript and you need to get the order Id and then the order total… You can only get the Order ID after the order is placed…
There is an answer example here.
2) Your 2nd public function involves only PHP… There are some errors and mistakes in this code. Try the following revisited code instead:
public function process_payment( $order_id ) {
// Get The WC_Order Object instance
$order = wc_get_order( $order_id );
/*
* Array with parameters for API interaction
*/
$args = array(
'amount' => $order->get_total(),
'merchant_order_id' => $order_id,
'api_Key' => 'm85BXXLpf_icrSvqbElR11xquEgmKZ8wfeRb2ly3-G7pIwCKDuytgplB7AQGi-5t',
'currency' => $order->get_currency(),
);
/*
* Your API interaction could be built with wp_remote_post()
*/
$response = wp_remote_post( 'https://api.mmoneybb.com/merchant/js/mmoney-payment.js', $args );
if( !is_wp_error( $response ) ) {
$body = json_decode( $response['body'], true );
// it could be different depending on your payment processor
if ( $body ['$response'] == 'APPROVED') {
// we received the payment
$order->payment_complete();
$order->reduce_order_stock();
// some notes to customer (replace true with false to make it private)
$order->add_order_note( 'Thanks for your payment!!!!', true );
// Empty cart
$woocommerce->cart->empty_cart();
// Redirect to the thank you page
return array(
'result' => 'success',
'redirect' => $this->get_return_url( $order )
);
} else {
wc_add_notice( 'Please try again.', 'error' );
return;
}
} else {
wc_add_notice( 'Connection error.', 'error' );
return;
}
}
It should better work.

php sends blank e-mail

For some reason we recieve around 5/10 emails a day from the support page that are empty, no input fields filled in but also no input fields fetched at all. The emails only show the subject.
If we test the form it works fine and the e-mail shows the info we filled and even if we fill in nothing we still recieve an e-mail stating the input field names. In the recordings the website makes of the users on the support page, there doesn't seem te be a user filling in the form at the time we recieve a 'blank' email.
I would some help because i'm completely lost on how to fix this.
Javascript:
$( document ).ready(function() {
var $form = $('form');
$form.submit(function() {
$.post($(this).attr('action'), $(this).serialize(), function(response) {
$('.email-popup-container').css({
"transform": "scale(.9)",
});
setTimeout(function(){
$('.email-popup-container').animate({
"margin-left": "+=1200px",
"opacity": "0",
}, 400, function(){
setTimeout(function(){
$('#email-popup').removeClass('is-visible').ready(function(){
$('.email-popup-container').css({
"transform": "scale(1)",
});
$('#contact-form')[0].reset();
$('.email-popup-container').animate({
"margin-left": "-=1200px",
}, 0
);
});
},150)
setTimeout(function(){
$.notify(" Thank you! We have recieved your e-mail.", {
delay: 4000,
color: "#fff",
background: "#1AC16D",
type: "success",
icon: "check",
align: "right",
animationType: "fade"
});
},400)
});
},600)
}, 'json');
return false;
});
});
php:
// configure
$from = 'New Message - Support Page <istillwebsite#donotreply.com>';
$sendTo = 'New Message - Support Page <sales#istillmail.com>';
$subject = 'Message from iStill Support Page';
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'email' => 'Email', 'message' => 'Message'); // array variable name => Text to appear in email
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
// let's do the sending
try
{
$emailText = "Someone sent a message from the support page\n=============================\n";
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
mail($sendTo, $subject, $emailText, "From: " . $from);
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
else {
echo $responseArray['message'];
}
?>
This is a super unsafe way to send mails. Someone can just call your .php script and send multiple mails. So it is probably a bot or something like this, that is calling your script.
To prevent this, you can use Google reCaptcha for example.

Ajax Message not displaying

I try to display an error message but it does'nt work.
When the email does'nt exist,
I have this message : Thank you : your email is added
But if the email is always in mailchimp or other error, I haven't message under the button submit.
Do you have an idea to resolve this point ?
Thank you
The detail of the error come from server.
string(88) "400: ****** is already a list member. Use PUT to insert or update list members."
array(5) {
["type"]=>
string(77) "http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/"
["title"]=>
string(13) "Member Exists"
["status"]=>
int(400)
["detail"]=>
string(83) "********* is already a list member. Use PUT to insert or update list members."
["instance"]=>
string(0) ""
}
my javascript is
$footer .= '
<script>
$(document).ready(function() {
$('#signup').submit(function() {
$("#message").html("<div class=\"alert alert-info\" style=\"padding:05px; margin-top:5px;\" role=\"alert\">Thank you : your email is added</div>");
$.ajax({
url: 'ext/api/mailchimp_v3/subscribe.php', // proper url to your "store-address.php" file
type: 'POST', // <- IMPORTANT
dataType: 'json',
data: $('#signup').serialize() + '&ajax=true',
success: function(msg) {
var message = '';
var result = '';
message = $.parseJSON(msg);
if (message.status === 'pending') { // success
result = '<div class=\"alert alert-success\" role=\"alert\">Thank you: an email has sent you for confirmation</div>';
} else { // error
result = '<div class=\"alert alert-danger\" role=\"alert\">Error ' + message.detail + '</div>';
}
},
complete: function(message) {
$('#message').html('<div> ' + message.title + '</div>'); // display the message
}
});
$('#fname').attr('value',''); // reset input field
$('#lname').attr('value',''); // reset input field
$('#email').attr('value',''); // reset input field
return false;
});
});
</script>';
PHP code
if ( isset($_POST['anonymous'])) {
$list_id = MODULES_HEADER_TAGS_MAILCHIMP_LIST_ANONYMOUS;
$merge_vars = [
'FNAME' => '',
'LNAME' => ''
];
} else {
$list_id = MODULES_HEADER_TAGS_MAILCHIMP_LIST_CUSTOMERS;
$merge_vars = [
'FNAME' => $_POST['firstname'],
'LNAME' => $_POST['lastname']
];
}
$array = [
'email_address' => $_POST['email'],
'merge_fields' => $merge_vars,
'status' => MODULES_HEADER_TAGS_MAILCHIMP_STATUS_CHOICE
];
if (MODULES_HEADER_TAGS_MAILCHIMP_STATUS_CHOICE == 'pending') {
$status = 'pending';
} else {
$status = 'subscribed';
}
$mc = new \MailChimp($key);
// add the email to your list
$result = $mc->post('/lists/' . $list_id . '/members', $array);
//send
json_encode($result);
// If being called via ajax, run the function, else fail - console
if ( MODULES_HEADER_TAGS_MAILCHIMP_DEBUG == 'True') {
if ($_POST['ajax']) {
var_dump($result); // send the response back
} else {
var_dump('Method not allowed - please ensure JavaScript is enabled in this browser');
}
}

Send and image from PHP to Javascript (JSON)

I'm trying to make a "meal" in my DB, so in my website i made a form with a name, and a picture. This is the code of the form :
<?php
$new_meal_title = htmlentities($_POST["new_meal_title"]);
$new_meal_img = htmlentities($_POST["new_meal_img"]);
$data = array(
'new_meal_title' => $new_meal_title,
'new_meal_img' => base64_encode($new_meal_img)
);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents(constant("API_URL")."/meal", false, $context);
if($result === FALSE){
var_dump($result);
}
$json = json_decode($result);
if($json->success == "true"){
header('Location: ../../');
return;
}
else{
echo $json->message;
}
header('Location: ../../');
?>
The form is sending data to my Node API. My Question is, how to save into a folder the image path through form in Javascript after it has been received in JSON.
Thanks for your help, i just had to change this line :
$new_meal_img = htmlentities($_POST["new_meal_img"]);
By
$new_meal_img = $_FILES['new_meal_img']["tmp_name"];
And
'new_meal_img' => base64_encode($new_meal_img)
By
'new_meal_img' => base64_encode(file_get_contents($new_meal_img))

Stripe AJAX PHP and JavaScript

The below is my code I'm using for my Stripe Subscription Payments, because the site I'm implementing this into is AngularJS I want to keep the site from Refreshing so I'm opting for this AJAX option.
I have commented out a piece of the PHP which is
$charge = Stripe_Charge::create(array(
'customer' => $customer->id,
'amount' => $amount,
'currency' => 'gbp'
));
If I exclude this, the payment goes through once and I'm unsure how this application is able to process the charge if there is no call for it in the PHP file.
If I include the above snippet then the charge goes through twice.
My config.php only has require_once('Stripe.php'); along with my API keys.
So I'm hoping someone could explain why the charge goes through without the charge code piece in there if my code is actually okay for me to continue with.
HTML
<button id="proBtn">Subscribe</button>
JavaScript
Stripe.setPublishableKey('HIDDEN');
$('#proBtn').click(function(){
var token = function(res){
var $input = $('<input type="hidden" name="stripeToken" />').val(res.id);
var tokenId = $input.val();
var email = res.email;
setTimeout(function(){
$.ajax({
url:'/assets/lib/charge.php',
cache: false,
data:{ stripeEmail : email, stripeToken:tokenId, stripePlan: 'pro' },
type:'POST'
})
.done(function(data){
// If Payment Success
console.log(data);
$('#proBtn').html('Thank You').addClass('disabled');
})
.error(function(){
$('#proBtn').html('Error, Unable to Process Payment').addClass('disabled');
});
},500);
//$('form:first-child').append($input).submit();
};
StripeCheckout.open({
key: 'HIDDEN', // Your Key
address: false,
amount: 500,
currency: 'gbp',
name: 'Pro Account',
description: '',
panelLabel: 'Checkout',
allowRememberMe: false,
token: token
});
return false;
});
charge.php
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/assets/lib/config.php');
$token = $_POST['stripeToken'];
$email = $_POST['stripeEmail'];
$plan = $_POST['stripePlan'];
if ( $plan == 'pro' ) {
$amount = 500;
$amountFormat = number_format( $amount / 100, 2) ;
$plan = 'pro';
}
if ( $plan == 'team' ) {
$amount = 2000;
$amountFormat = number_format( $amount / 100, 2) ;
$plan = 'team';
}
Stripe_Plan::retrieve("pro");
Stripe_Plan::retrieve("team");
$customer = Stripe_Customer::create(array(
'email' => $email,
'card' => $token,
'plan' => $plan
));
try {
/*
$charge = Stripe_Charge::create(array(
'customer' => $customer->id,
'amount' => $amount,
'currency' => 'gbp'
));*/
echo 'success';
} catch(Stripe_CardError $e) {
echo "The card has been declined";
echo $token;
}
print_r($token);
echo '<br/>';
print_r($email);
echo '<br/>';
echo $customer->id;
echo '<h1>Successfully charged '.$amountFormat.'!</h1>';
?>
When you create a customer in Stripe it automatically charges them if you pass in a plan. You're basically saying create this customer and sign them up for this plan. That's why you are charging them twice.
Here's a link to the Customer API:
https://stripe.com/docs/api#create_customer

Categories

Resources