PayPal Button API onApprove called twice - javascript

Hi I'm using Angular 2+ to integrate the sandbox PayPal checkout button with my form and throughout most of the process it works fine. The issue I'm having is that the onApprove() method seems to get called twice after the process ends which I can see because the HTTP request I have in that method gets called twice.
I've tried looking online for anyone who has experienced a similar problem but I can't find any resources on how to fix it. I have a few warnings in Chrome's console but these seem to be unrelated to the problem.
The console.log statements in createSubscription and onCancel only print once so I think that eliminates the possibility of there being some kind of duplicate window.
My code seems to be fairly similar to everyone else's implementation which I've seen on the web which is why I can't wrap my head around why it doesn't work.
component.ts
ngAfterViewInit() {
paypal.Buttons({
onInit: (data, actions) => {
},
onClick: (actions) => {
},
createSubscription: (data, actions) => {
return actions.subscription.create({
'plan_id': this.planID,
});
},
onApprove: (data, actions) => {
console.log(data + ' transaction approved');
this.submitLoginDetails();
//this.getSubcriptionDetails(data.subscriptionID);
// use auth login method and redirect to /home
},
onCancel: (data) => {
console.log('Transaction cancelled');
},
onError: (err) => {
console.log(err);
}
}).render(this.paypalElement.nativeElement);
}
component.html
<!-- LOGIN FORM -->
<div id='payment' [hidden]="stepCounter!==2">
<form #loginForm='ngForm'>
<div id="user-data">
<div class="form-group">
<label for="name" required>Name</label>
<input type="text" name="name" id="name" class="form-control" ngModel minlength=1 #name='ngModel'>
<span class="help-block" *ngIf='(!name.valid || name.value.length === 0) && name.touched'>Please enter a valid name</span>
</div>
<div class="form-group">
<label for="email" required email>Email</label>
<input type="email" name="email" id="email" class="form-control" ngModel email #email='ngModel'>
<span class="help-block" *ngIf='(!email.valid || email.value.length === 0) && email.touched'>Please enter a valid email</span>
</div>
</div>
<div class="form-group">
<label for="pwd">Password</label>
<input type="password" name="password" id="password" class="form-control" ngModel required minlength=6 #password='ngModel'>
<span class="help-block" *ngIf='(!password.valid || password.value.length === 0) && password.touched'>Please enter at least six characters</span>
</div>
<div #paypal></div>
<span class="help-block" *ngIf='buttonError && !loginForm.valid'>Please make sure the values above are valid before checking out</span>
</form>
</div>
Console after the checkout has been completed and onApprove() has been called

Related

EmailJs is not sending email by React

I hope you are doing great, I am using Emailjs in React to get Emails. I configure Emailjs and it is properly sending test Emails but when I am trying to send from my project so it's not sending and even it is also not showing any error
Here is the template of the Email
Here is the ID and token which I hide but I am just showing this image to explain
clearly
(1) Here i import emailjs
import emailjs from '#emailjs/browser';
(2) Here is the function that will send the email, (Here in the fourth parameter I am just showing 5 characters as I hide in the above image )
function sendEmail(e) {
e.preventDefault();
emailjs.send('gmail', 'zaryabkhan864', e.target, 'G5CpT9*******')
.then((result) => {
console.log(result.text);
}, (error) => {
console.log(error.text);
});
e.target.reset()
}
(3) Here is the Form code
<form onSubmit={sendEmail}>
<div className="mb-3">
<label htmlFor="name" className="form-label">Your Name</label>
<input type="text" className="form-control" id="name" placeholder="Muhammad Zaryab Khan" name="name" />
</div>
<div className="mb-3">
<label htmlFor="email" className="form-label">Email address</label>
<input type="email" className="form-control" id="exampleFormControlInput1" placeholder="name#example.com" name="email" />
</div>
<div className="mb-3">
<label htmlFor="exampleFormControlTextarea1" className="form-label">Your Message</label>
<textarea className="form-control" id="Message" rows="5" name="message"></textarea>
</div>
<button type="submit" className="btn-theme">Send Message <i className="fa fa-paper-plane ms-2"></i></button>
</form>
Now I am receiving this error
add ref atribute for form, and ad useRef
const form = useRef<HTMLFormElement>(null);
after you should change e.target => form.current
const form = useRef();
const sendEmail = (e) => {
e.preventDefault();
emailjs.sendForm('service_id', 'template_id', form.current, 'user_id')
.then((result) => {
console.log(result.text);
}, (error) => {
console.log(error.text);
});
alert("Email Send");
};

Redirect to another HTML page after successfull login attempt | with JS

I have created a login form. I want a JS code that:
If the information on the login page i.e Username and Login is correct, It will proceed to another HTML page.
Simply, I want the page to redirect to another page after successfull login attempt. | With JS
I dont want any PHP or MySql code.
I have tried this code but this doesnt works. On wrong information, it says Invalid information. But on correct info, it refreshes the page and there a ? is visible at te end of the url:
Html:
<form id="form" action="" method="GET">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" id="email" class="form-control" aria-describedby="emailHelp" >
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" id="password" class="form-control" >
</div>
<button type="submit" class="btn btn-outline-success btn-lg shadow" onClick="auth()">Submit</button>
</form>
JavaScript:
function auth() {
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
if (email === "admin#gmail.com" && password === "user") {
location = location['href'];
// alert("You Are a ADMIN");
} else {
alert("Invalid information");
return;
}
}
I have also used:
window.location.replace("upload.html");
instead of:
location = location['href'];
But still does not works.
A couple of things here. One you're doing a GET with your form rather than doing a POST. You should change that. Second, on your JavaScript call for auth you should pass the event parameter so that the default action of the form will be stopped. Third, you should be using a relative path for your URL within your redirect. Last, You should do a window.redirect() to simulate an HTTP redirect when the function executes.
Here is the code with the updates:
<form id="form" action="post">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email"
id="email"
class="form-control"
aria-describedby="emailHelp" >
<small id="emailHelp"
class="form-text text-muted">
We'll never share your email with anyone else.
</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" id="password" class="form-control" >
</div>
<button type="submit"
class="btn btn-outline-success btn-lg shadow"
onClick="auth(event)">Submit</button>
</form>
<script>
function auth(event) {
event.preventDefault();
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
if (email === "admin#gmail.com" && password === "user") {
window.location.replace("/upload.html");
} else {
alert("Invalid information");
return;
}
}
</script>

express validator how to get req.validationErrors() to front side?

Hello and thanks for reading. I try to use express-validator. It works fine and block the post if for instance the name input is empty. But I don't know how I can get the error message on the front side. I have tried lot of things without success. Hope somebody can help and sorry for the size of the message. Here is a link to the doc of express validator if it can help ( https://express-validator.github.io/docs/ )
My code...
I have create a basic form:
<form id="sign-in">
<div class="form-group">
<label for="nom">name</label>
<input id="name" type="text" class="form-control" placeholder="name" autocomplete="family-name">
</div>
<div class="form-group">
<label for="username">username</label>
<input id="username" type="text" class="form-control" placeholder="username" autocomplete="given-name">
</div>
<div class="form-group">
<label for="email">email</label>
<input id="email" class="form-control" type="email" placeholder="monemail#gmail.com" autocomplete="email"></input>
</div>
<div class="form-group">
<label for="password">password</label>
<input id="password" class="form-control" type="password" autocomplete="current-password"></input>
</div>
<div class="form-group">
<label for="confirm-password">confirm-password</label>
<input id="confirm-password" class="form-control" type="password" autocomplete="current-password"></input>
</div>
<button type="submit" class="btn btn-primary">sign-in</button>
</form>
</section>
<footer>
</footer>
<script type="module" src="/js/sign-in.js"></script>
Then I do my fetch on the file sign-in.js:
document.getElementById('sign-in').addEventListener('submit', event => {
event.preventDefault()
const name = document.getElementById('name').value
const username = document.getElementById('username').value
...
// Use fetch to post data into the DB
window.fetch(`${config.serverHost}/sign-in`, {
method: 'post',
body: JSON.stringify({
name,
username,
...
})
}).then((res, errors) => {
if (res.status === 200) {
window.parent.location.reload()
} else if (res.status === 422) {
DONT KNOW WHAT TO DO TO GET MY ERROR MESSAGE
}
})
})
And finaly the server side:
app.post('/sign-in', (req, res, next) => {
// Start express validator //
req.checkBody('name', 'Please write your name').notEmpty()
req.checkBody('username', 'Please write your name').notEmpty()
...
const errors = req.validationErrors()
if (errors) {
SEND ME BACK MY ERROR MESSAGE
} else {
this part works fine, thank you
}
})
You have two options here depending on how your client is setup:
Use either express-flash or connect-flash to send errors back to your view. See this for the differences.
Use res.json to send back the errors object you created from validationErrors(). Be sure to set the appropriate HTTP status as well.
As I found the solution I post it, it may be useful for others.
Here is the sign-in.js file:
.then(res => {
if (res.status !== 200) {
res.json()
.then(res => errorsMessages.innerHTML = res.map(e => `<p>${e.msg}</p>`).join(''))
} else {
window.parent.location.reload()
}
})
And the code for the server:
const errors = req.validationErrors()
if (errors) {
res.status(422).json(errors)
} else {...}
Thank you Francisco for your help.

Ajax function reloads the page with some parameter on response

I am working on an application where user submit his/her information in tabs...
After .onclick() function, data is submitted to action and saved correctly and returned "success" successfully redirect user to login page...
I have returned two responses so far, "success" and "fail"
But the problem really is, when returning "false"...console.log shows the response correctly, although the work i'd like to perform on "fail" isn't really working..and page reloads with some parameters(i will show it in snapshot)....
Html
<form class="form-horizontal" id="default" name="myform">
<fieldset title="Step1" class="step" id="default-step-0">
<div class="form-group">
<label class="col-lg-2 control-label">Email</label>
<div class="col-lg-10">
<input type="email" class="form-control" id="Email1" required>
<label id="err1" class="col-lg-6 control-label" "></label>
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Password</label>
<div class="col-lg-10">
<input type="password" name="password1" class="form-control" id="password1" required>
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Confirm Password</label>
<div class="col-lg-10">
<input type="password" name="confirmpassword1" class="form-control" id="confirmpassword1" required>
<label id="passMatch" class="col-lg-6 control-label""></label>
</div>
</div>
</fieldset>
<fieldset title="Step 2" class="step" id="default-step-1">
//some other input fields on 2nd tab
</fieldset>
<input type="button" class="finish btn btn-danger" value="Save" id="btnSubmitAll" />
</form>
Ajax
<script>
$("#btnSubmitAll").click(function (event) {
event.preventDefault();
var Email = $('#Email1').val();
var password = $('#password1').val();
var confirmpassword = $('#confirmpassword1').val();
$.ajax({
type: "POST",
url: '#Url.Action("Submit", "Home")',
dataType: "JSon",
async: false,
data: {"Email": Email, "password": password, "confirmpassword": confirmpassword},
success: function (data) {
if (data == "success")
{
window.location.href = '#Url.Action("login","Home")';
console.log(data);
}
else {
$('#err1').html("Email Exist");
console.log(data);
}
},
error: function (data, jqXHR, exception) {
//some errors in if/else if/else
}
}
});
});
</script>
Please remember, when data == "success", all things go right(returns success after successfull record insertion), but when "fail" returned, console shows it correctly but label not updated with the message and also the whole page reloads with some parameters from the form inputs as can be seen below...
InAction
if (objIdHelper.IsUserExist(Email))
{
return this.Json ("fail");
}
else
{
//some process
return this.Json ("success");
}
I am surely missing some logic or doing something stupid, please help....
Any kind of help will be appreciated...thanks for your time
Check for the argumet passed in the success callback..Also note that you have wrong understanding for error callback. It wont execute if there are any errors in success callback conditions. It is to handle network errors.
Your if statement if (data == "success") uses data instead of data1 like the function specifies.

Meteor.call method not found

I am working my way through the Microscope project in Discover Meteor and I have hit a problem. I am getting a 'Method not found' error for the following code:
HTML Template - microscope/client/templates/posts/post_submit.html
<template name="postSubmit">
<form class="main form">
<div class="form-group">
<label class="control-label" for="url">URL</label>
<div class="controls">
<input name="url" id="url" type="text" value="" placeholder="Your URL" class="form-control"/>
</div>
</div>
<div class="form-group">
<label class="control-label" for="title">Title</label>
<div class="controls">
<input name="title" id="title" type="text" value="" placeholder="Name your post" class="form-control"/>
</div>
</div>
<input type="submit" value="Submit" class="btn btn-primary"/>
</form>
JS - microscope/client/templates/posts/post_submit.js
Template.postSubmit.events({
'submit form': function(e) {
e.preventDefault();
var post = {
url: $(e.target).find('[name=url]').val(),
title: $(e.target).find('[name=title]').val()
};
Meteor.call('postInsert', post, function(error, result) {
// display the error to the user and abort
if (error)
return alert(error.reason);
Router.go('postPage', {_id: result._id});
});
}
});
I am not sure how to debug this as I am getting no errors in the console. Please can anyone suggest where I am going wrong?
Very likely that you need to add the method postInsert to the server side. If you're following along in Discover Meteor, they do that in the next section - https://book.discovermeteor.com/chapter/creating-posts
For example, you put the method in a file called lib/collections/posts.js like this
Meteor.methods({
postInsert: function(postAttributes) {
check(Meteor.userId(), String);
check(postAttributes, {
title: String,
url: String
});

Categories

Resources