Send Email Directly From JavaScript using EmailJS.
Please look the below answer and I'm getting so many comments for malicious attacks.. because this file is loading in browser so malicious user can easily get your key configuration. So, how to avoid it?
var templateParams = {
to_name: 'xyz',
from_name: 'abc',
message_html: 'Please Find out the attached file'
};
emailjs.send('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', templateParams)
.then(function(response) {
console.log('SUCCESS!', response.status, response.text);
}, function(error) {
console.log('FAILED...', error);
});
Hi you can directly send email through using EmailJS without using the server side code. It'll totally client side.
For sending you need to configure below details.
1)First,Go to this site [https://www.emailjs.com/] and create free account.
2)below 'Connect your email service' button click and configure. You'll get 'YOUR_SERVICE_ID'
3)Then 'Create email template' button click and configure. You'll get 'YOUR_TEMPLATE_ID'
4)click on 'Send email from JavaScript' button. You'll get code.
5)You'll get the 'YOUR_USER_ID' in [https://dashboard.emailjs.com/account]
I did all configuration and added code please check. below code.
NOTE : - "Please encrypted or embedded your use_id for malicious attacks."
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/emailjs-com#2.4.0/dist/email.min.js">
</script>
<script type="text/javascript">
(function() {
emailjs.init("YOUR_USER_ID"); //please encrypted user id for malicious attacks
})();
//set the parameter as per you template parameter[https://dashboard.emailjs.com/templates]
var templateParams = {
to_name: 'xyz',
from_name: 'abc',
message_html: 'Please Find out the attached file'
};
emailjs.send('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', templateParams)
.then(function(response) {
console.log('SUCCESS!', response.status, response.text);
}, function(error) {
console.log('FAILED...', error);
});
</script>
Using JavaScript can expose your credentials like user id , service id to the public. For this , you can store these keys values in a variable (half value) and then manipulating it in runtime like appending remaining half of the key etc. But its not totally safe.
Code :
<html>
<head>
<title>Contact Us</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/emailjs-com#2/dist/email.min.js"></script>
</head>
<body>
<div class="container">
<div class="card col-md-6 offset-md-3" style="margin-top:50px;">
<div class="card-body">
<h2>Contact Us</h2>
<label for="thename">Name</label>
<input type="text" class="form-control" id="thename" placeholder="Enter Name">
<label for="themail">Email:</label>
<input type="email" class="form-control" id="themail" placeholder="Enter Email">
<label for="themsg">Message</label>
<textarea class="form-control" id="themsg" placeholder="Enter Message"></textarea>
<button class="btn btn-danger btn-sm" style="margin-top:10px;" onCLick="sendemail();">Send</button>
</form>
</div>
</div>
</div>
<script>
function sendemail() {
var userid = "YourUserID"
emailjs.init(userid);
var thename = document.getElementById('thename').value;
var themail = document.getElementById('themail').value;
var themsg = document.getElementById('themsg').value;
var validmail = /^w+([.-]?w+)*#w+([.-]?w+)*(.w{2,3})+$/;
if (thename == "") {
alert("Please Enter Name");
}
else if (themail == "" || themail.match(!validmail)) {
alert("Please Enter Valid Email");
}
else if (themsg == "") {
alert("Please Enter Message");
}
else {
var contactdetail = {
from_name: thename,
from_email: themail,
message: themsg
};
emailjs.send('YourServiceID', 'YourTemplateID', contactdetail).then(function (res) {
alert("Email Sent Successfully");
},
reason => {
alert("Error Occur");
})
}
}
</script>
</body>
</html>
Make sure to replace "YourUserID" , "YourServiceID" & "YourTemplateID" with your own ids
Reference : Narendra Dwivedi - Send Email From JavaScript
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/emailjs-com#2.4.0/dist/email.min.js">
</script>
<script type="text/javascript">
(function() {
emailjs.init("service_ud48moz"); //please encrypted user id for malicious attacks
})();
//set the parameter as per you template parameter[https://dashboard.emailjs.com/templates]
var templateParams = {
to_name: 'xyz',
from_name: 'abc',
message_html: 'Please Find out the attached file'
};
emailjs.send('service_ud48moz', 'template_njhhxon', templateParams)
.then(function(response) {
console.log('SUCCESS!', response.status, response.text);
}, function(error) {
console.log('FAILED...', error);
});
</script>
Related
In my JavaScript Firebase application, I have tried to set up user authentication via email, and at the same time sync user data to Firebase's realtime database. While our Google sign in worked with no problems, the function that makes accounts, firebase.auth().createUserWithEmailAndPassword(email, password); fails to execute and (annoyingly) does not throw any error messages. Here is the code:
main.js: (The problematic section is submitAcc())
var config = {
apiKey: "censored",
authDomain: "censored",
databaseURL: "censored",
projectId: "censored",
storageBucket: "censored",
messagingSenderId: "censored"
};
firebase.initializeApp(config);
var database = firebase.database();
function showAccCreate() { //Hides and shows account create button
var x = document.getElementById("hiddenaccountcreation");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
function submitAcc() { //On submit button pressed
alert("Signing in");
var email = document.getElementById("emailinput").value;
var password = document.getElementById("passinput").value;
var username = document.getElementById("usernameinput").value;
//console.log(email + password +username);
var user;
alert("recorded values");
firebase.auth().createUserAndRetrieveDataWithEmailAndPassword(email,password).then(function(result) {
alert("Gets into .then");
var user = firebase.auth().currentUser;
var uidvalue = user.uid;
console.log(uidvalue);
console.log(uidvalue);
alert("User value recorded");
writeUserDataFromEmailSignin(email, username,uidvalue);
alert(user.uid);
}).catch(function(error) {
alert(error.message);
console.log(error.message);
console.log(error.code);
});
}
//Testing if auth state changes
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
alert("User is signed in.");
document.getElementById("debugtest").innerHTML = "Signed in";
}
});
function writeUserDataFromEmailSignin(email, name, uuid) { //Writes user data to database if user signs in
alert("Entered function");
database.ref('users/' + uuid).set({
"name": name,
"email": email,
"uid": uuid,
}).then(function() {
alert("Completed");
}).catch(function() {
console.log(error.message);
console.log(error.code);
})
}
function showsignin() {
var x = document.getElementById("hiddensignin");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
function googlesignin() { //Signs people into app via Google
var provider = new firebase.auth.GoogleAuthProvider();
provider.addScope("https://www.googleapis.com/auth/contacts.readonly");
firebase.auth().languageCode = 'en';
firebase.auth().signInWithPopup(provider).then(function(result) {
var token = result.credential.accessToken; //Google Auth access token
var user = result.user; //Contains all user info that Google provided us
writeToDatabaseFromGoogle(user.email, user.displayName, user.uid, user.photoUrl);
}).catch(function(error) {
console.log(error.message);
console.log(error.code);
});
}
function writeToDatabaseFromGoogle(email, name, uuid, image_url) { //Writes user data to database from Google signin
database.ref("users/" + uuid).set({
"name": name,
"email": email,
//"imageUrl": image_url,
"uid": uuid,
}).catch(function(error) {
console.log(error.message);
console.log(error.code);
});
}
function signInUser() { //Uses email sign-in so signin to existing account
var email = document.getElementById("emailreauth");
var pass = document.getElementById("passreauth");
// noinspection JSUnresolvedFunction
firebase.auth().signInWithEmailAndPassword(email, pass).catch(function (error) {
//Handle errors here
let errorCode = error.code;
let errorMessage = error.MESSAGE;
console.log(errorCode);
console.log(errorMessage);
});
}
and the index.html file:
<!DOCTYPE html>
<!--suppress HtmlRequiredLangAttribute -->
<html>
<head>
<script src="https://www.gstatic.com/firebasejs/5.8.5/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyAhglAXFWaJhtvOrfeugAMgJHrBw5CUNEc",
authDomain: "projectcrosscomm.firebaseapp.com",
databaseURL: "https://projectcrosscomm.firebaseio.com",
projectId: "projectcrosscomm",
storageBucket: "projectcrosscomm.appspot.com",
messagingSenderId: "412861101382"
};
firebase.initializeApp(config);
</script>
<!-- Firebase App is always required and must be first -->
<script src="https://www.gstatic.com/firebasejs/5.8.5/firebase-app.js"></script>
<!-- Add additional services that you want to use -->
<script src="https://www.gstatic.com/firebasejs/5.8.5/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.8.5/firebase-database.js"></script>
<!-- Comment out (or don't include) services that you don't want to use -->
<!-- <script src="https://www.gstatic.com/firebasejs/5.8.5/firebase-storage.js"></script> -->
<script src="main.js" rel="script"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Project Cross Comm!</title>
<link rel="stylesheet" href="stylesheet.css">
</head>
<body>
<button id="accountcreate" onclick="showAccCreate()">Create your account here!</button>
<button id="showsignin" onclick="showsignin()">Already have an account?</button>
<button2 id="googlesignin" onclick="googlesignin()">Sign in with Google</button2>
<h1>Project Cross Comm!</h1>
<h2 id="subtitle">
Welcome to <strong>Project Cross Comm!</strong>
</h2>
<img height="200px" src="https://i.kym-cdn.com/entries/icons/mobile/000/013/564/doge.jpg" width="260px" alt="If you can't see this image you're a pleb">
<h2></h2>
<p id="desc"> Project Cross Comm is a free to use chatting program that runs in your browser. All the chats are encrypted, so no one can read your chats. Enjoy the program and chat away.</p>
<div id="hiddenaccountcreation">
<form>
<fieldset>
<legend>Account Creation</legend> <!--Create account via email sign-in-->
<p>
<label for="usernameinput">Username</label>
<input type="text" id="usernameinput" name="createUsername" placeholder="Username">
<p>
<label for="emailinput">Email</label>
<input type="email" id="emailinput" value="" placeholder="example#example.com" name="createEmail">
</p>
<p>
<label for="passinput">Password</label>
<input type="password" id="passinput" value="" placeholder="password" name="createPass">
</p>
<button id="submit" onclick="submitAcc()">SUBMIT</button>
</fieldset>
</form>
</div>
<div id="hiddensignin">
<form>
<fieldset>
<legend>Sign In</legend>
<p>
<label for="usernamereauth">Username</label>
<input type="text" id="usernamereauth" value="">
<p>
<label for="emailreauth">Email</label>
<input type="email" id="emailreauth" value="">
</p>
<p>
<label for="passreauth">Password</label>
<input type="password" id="passreauth" value="">
</p>
<button id="signin" onclick="signInUser()">SUBMIT</button>
</fieldset>
</form>
</div>
<div id="getthisblockoutofmygoddamnedway"> <!--Problematic code block that another member of my team put there -->
<a style = "color: white; "id="link" href="InfoPage.html">Click here for more information.</a>
<h6></h6>
<a style = "color: white; "id="link2" href="ChatLayout.html">Click Here To Chat</a>
<h6></h6>
<a style = "color: white; "id="link3" href="https://app.termly.io/document/privacy-policy/0ae020d8-ee05-4202-a0c7-d4ff19e8f661">Privacy Policy </a>
</div>
</body>
<footer>
<p id="debugtest" class="debug">Haven't Been Signed In Yet</p>
<noscript>Man, sucks for you! We only support modern, functioning browsers. Maybe you should get JavaScript </noscript>
</footer>
</html>
The farthest alert my program gets to is alert("recorded values");, no further alerts are executed. Javascript does not throw any errors during the process; the console is empty. Is there any way to find out what's wrong, or even to force Javascript to be more verbose and log its memory every so often?
Can you please try this? This works in my case.
firebase.auth().signInWithEmailAndPassword(email, password)
.then(response => {
const uid = response.user.uid; // you have uid
response.user.getIdToken()
.then(token => {
// do anything with token
})
.catch(error => {
// any error handling
})
})
.catch(error => {
// any error handling
})
Your Current issue is you are not able to store the Values into the DB with the method submitAcc().This method is called when the user creates the account. I have corrected and made some changes please test and let me know if that works for you.
I have added two functions logout() and status() to understand where the problem is. I'd suggest you remove them.
I have also observed in the method signInUser(). You have missed the .value to Email and Password and corrected it.
See below image once the user clicks to Create the Account.I have logged his input to console.
Database Saving user's info:
Code
var database = firebase.database();
function showAccCreate() { //Hides and shows account create button
var x = document.getElementById("hiddenaccountcreation");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
function submitAcc() { //On submit button pressed
alert("Signing in");
var email = document.getElementById("emailinput").value;
var password = document.getElementById("passinput").value;
var username = document.getElementById("usernameinput").value;
console.log(email + password +username);
alert("recorded values");
firebase.auth().createUserWithEmailAndPassword(email,password).then(function(result) {
alert("Gets into .then");
var user = firebase.auth().currentUser;
var uidvalue = user.uid;
console.log(uidvalue);
console.log(uidvalue);
alert("User value recorded");
writeUserDataFromEmailSignin(email, username,uidvalue);
alert(user.uid);
}).catch(function(error) {
alert(error.message);
console.log(error.message);
console.log(error.code);
});
}
function writeUserDataFromEmailSignin(email, name, uuid) { //Writes user data to database if user signs in
alert("Entered function");
database.ref('users/' + uuid).set({
"name": name,
"email": email,
"uid": uuid,
}).then(function() {
alert("Completed");
}).catch(function() {
console.log(error.message);
console.log(error.code);
})
}
function logout()
{
firebase.auth().signOut().then(function() {
// Sign-out successful.
}).catch(function(error) {
// An error happened.
});
}
function status()
{
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
var emailv =user.email;
console.log("User is signed in. em ankunav enti "+ emailv);
} else {
console.log("No user is signed in.");
}
});
}
//Testing if auth state changes
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
alert("User is signed in.");
document.getElementById("debugtest").innerHTML = "Signed in";
}
else
{
document.getElementById("debugtest").innerHTML = "NOT LOGGED IN ";
}
});
function showsignin() {
var x = document.getElementById("hiddensignin");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
function signInUser() { //Uses email sign-in so signin to existing account
var email = document.getElementById("emailreauth").value;
var pass = document.getElementById("passreauth").value;
// noinspection JSUnresolvedFunction
firebase.auth().signInWithEmailAndPassword(email, pass).catch(function (error) {
//Handle errors here
let errorCode = error.code;
let errorMessage = error.MESSAGE;
console.log(errorCode);
console.log(errorMessage);
});
}
<!DOCTYPE html>
<!--suppress HtmlRequiredLangAttribute -->
<html>
<head>
<script src="https://www.gstatic.com/firebasejs/5.8.6/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "hmcalreac",
authDomain: "kbckyc",
databaseURL: "https://abc.dmc",
projectId: "test12d",
storageBucket: "t11",
messagingSenderId: "11"
};
firebase.initializeApp(config);
</script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Project Cross Comm!</title>
</head>
<body>
<button id="accountcreate" onclick="showAccCreate()">Create your account here!</button>
<button id="showsignin" onclick="showsignin()">Already have an account?</button>
<button2 id="googlesignin" onclick="googlesignin()">Sign in with Google</button2>
<h1>Project Cross Comm!</h1>
<h2 id="subtitle">
Welcome to <strong>Project Cross Comm!</strong>
</h2>
<img height="200px" src="https://i.kym-cdn.com/entries/icons/mobile/000/013/564/doge.jpg" width="260px" alt="If you can't see this image you're a pleb">
<h2></h2>
<p id="desc"> Project Cross Comm is a free to use chatting program that runs in your browser. All the chats are encrypted, so no one can read your chats. Enjoy the program and chat away.</p>
<div id="hiddenaccountcreation">
<fieldset>
<legend>Account Creation</legend> <!--Create account via email sign-in-->
<p>
<label for="usernameinput">Username</label>
<input type="text" id="usernameinput" name="createUsername" placeholder="Username">
<p>
<label for="emailinput">Email</label>
<input type="email" id="emailinput" value="" placeholder="example#example.com" name="createEmail">
</p>
<p>
<label for="passinput">Password</label>
<input type="password" id="passinput" value="" placeholder="password" name="createPass">
</p>
<button id="submit" onclick="submitAcc()">SUBMIT TO CREATE ACCOUNT </button>
</fieldset>
</div>
<div id="hiddensignin">
<fieldset>
<legend>Sign In</legend>
<p>
<label for="usernamereauth">Username</label>
<input type="text" id="usernamereauth" value="">
<p>
<label for="emailreauth">Email</label>
<input type="email" id="emailreauth" value="">
</p>
<p>
<label for="passreauth">Password</label>
<input type="password" id="passreauth" value="">
</p>
<button id="signin" onclick="signInUser()">SUBMIT To Signin to console</button>
</fieldset>
</div>
<button id=mystat onclick="status()">CLICK me to GET Status</button>
<button id=mystat onclick="logout()">CLICK me to logout </button>
<div id="getthisblockoutofmygoddamnedway"> <!--Problematic code block that another member of my team put there -->
<a style = "color: white; "id="link" href="InfoPage.html">Click here for more information.</a>
<h6></h6>
<a style = "color: white; "id="link2" href="ChatLayout.html">Click Here To Chat</a>
<h6></h6>
<a style = "color: white; "id="link3" href="https://app.termly.io/document/privacy-policy/0ae020d8-ee05-4202-a0c7-d4ff19e8f661">Privacy Policy </a>
</div>
<script src="ne2.js" rel="script"></script>
</body>
<footer>
<p id="debugtest" class="debug">Haven't Been Signed In Yet</p>
<noscript>Man, sucks for you! We only support modern, functioning browsers. Maybe you should get JavaScript </noscript>
</footer>
</html>
I have looked at a few posts on here with the same issue but under different circumstances that don't supply me with an answer to my particular issue...
I was using Braintree JSv2 with my Django project and all was working fine. Since I have migrated over to v3 of Braintree, the only issue I seem to have right now is that the value inputted to "payment_method_nonce" is not there...
Here is the code that is supposed to be dumping the payment_method_nonce value:
document.querySelector('input[name="payment_method_nonce"]').value = payload.nonce;
And here is the code that is supposed to be grabbing it on the python side:
client_payment_nonce = request.POST['payment_method_nonce']
When submitting this in my dev environment, I get an error (MultiValueDictKeyError) for "payment_method_nonce".
I am using Django 1.9 and Python 2.7. I am also using the example given by Braintree for a simple integration using HostedFields...
Small test
So I manually added an input field in my form with name "payment_method_nonce" just to see if not having a field was causing some issue. I know it is injected by Braintree but just testing a thought. It seems that although the value of payment_method_nonce is supposed to be my nonce, I didn't type anything into the input box and it was still coming back as null.
Full Snippets of Form and HostedFields
<form action="/booking/" method="post" id="checkout_form">
{% csrf_token %}
<div class="payment">
<span>Payment</span>
<!--input elements for user card data-->
<div class="hosted-fields" id="card-number"></div>
<div class="hosted-fields" id="postal-code"></div>
<div class="hosted-fields" id="expiration-date"></div>
<div class="hosted-fields" id="cvv"></div>
<div class="btns">
<input type="hidden" name="payment_method_nonce">
<input type="submit" value="Complete Booking" id="pay-button">
</div>
</div>
</form>
Note: I had just changed the payment_method_nonce field to type="hidden" instead of type="text" but still have the same effect...
<!-- load the required client component -->
<script src="https://js.braintreegateway.com/web/3.15.0/js/client.min.js"></script>
<!-- load the hosted fields component -->
<script src="https://js.braintreegateway.com/web/3.15.0/js/hosted-fields.min.js"></script>
<!-- Braintree setup -->
<script>
var client_token = "{{ request.session.braintree_client_token }}"
var form = document.querySelector('#checkout-form');
var submit = document.querySelector('input[type="submit"]');
braintree.client.create({
authorization: client_token
}, function (clientErr, clientInstance) {
if (clientErr) {
// Handle error in client creation
return;
}
braintree.hostedFields.create({
client: clientInstance,
styles: {
'input': {
'font-size': '14px'
},
'input.invalid': {
'color': 'red'
},
'input.valid': {
'color': 'green'
}
},
fields: {
number: {
selector: '#card-number',
placeholder: 'Credit Card Number'
},
cvv: {
selector: '#cvv',
placeholder: '123'
},
expirationDate: {
selector: '#expiration-date',
placeholder: '10/2019'
},
postalCode: {
selector: '#postal-code',
placeholder: '10014'
}
}
}, function (hostedFieldsErr, hostedFieldsInstance) {
if (hostedFieldsErr) {
// handle error in Hosted Fields creation
return;
}
submit.removeAttribute('disabled');
form.addEventListener('submit', function (event) {
event.preventDefault();
hostedFieldsInstance.tokenize(function (tokenizeErr, payload) {
if (tokenizeErr) {
// handle error in Hosted Fields tokenization
return;
}
// Put `payload.nonce` into the `payment_method_nonce`
document.querySelector('input[name="payment_method_nonce"]').value = payload.nonce;
document.querySelector('input[id="pay-button"]').value = "Please wait...";
form.submit();
});
}, false);
});
});
</script>
Note: the line document.querySelector('input[id="pay-button"]').value = "Please wait..."; doesn't fire (I know this because the button does not change values). Maybe these querySelector lines just aren't working?
Something New Noticed
I just went back to my page and hit the submit button without even entering any information. In v2 of Braintree, I would not be able to click the submit button until all fields were filled in... Maybe the values in my form aren't even being sent to braintree to receive a nonce and that's why there is an empty string being returned..?
Moral of the story
Review your code... Multiple times. As pointed out by C Joseph, I have my form ID as something different than what my var form is referencing...
<form action="/booking/" method="post" id="checkout_form">
var form = document.querySelector('#checkout-form');
I've tried to integrate Braintree in my Laravel 5.2 app and everything works fine with JS v2 client setup, but I would like to upgrade it to v3.
This is from the docs (I've customized a bit):
<form id="checkout-form" action="/checkout" method="post">
<div id="error-message"></div>
<label for="card-number">Card Number</label>
<div class="hosted-field" id="card-number"></div>
<label for="cvv">CVV</label>
<div class="hosted-field" id="cvv"></div>
<label for="expiration-date">Expiration Date</label>
<div class="hosted-field" id="expiration-date"></div>
<input type="hidden" name="payment-method-nonce">
<input type="submit" value="Pay">
</form>
<!-- Load the Client component. -->
<script src="https://js.braintreegateway.com/web/3.0.0-beta.8/js/client.min.js"></script>
<!-- Load the Hosted Fields component. -->
<script src="https://js.braintreegateway.com/web/3.0.0-beta.8/js/hosted-fields.min.js"></script>
<script>
var authorization = '{{ $clientToken }}'
braintree.client.create({
authorization: authorization
}, function (clientErr, clientInstance) {
if (clientErr) {
// Handle error in client creation
return;
}
braintree.hostedFields.create({
client: clientInstance,
styles: {
'input': {
'font-size': '14pt'
},
'input.invalid': {
'color': 'red'
},
'input.valid': {
'color': 'green'
}
},
fields: {
number: {
selector: '#card-number',
placeholder: '4111 1111 1111 1111'
},
cvv: {
selector: '#cvv',
placeholder: '123'
},
expirationDate: {
selector: '#expiration-date',
placeholder: '10 / 2019'
}
}
}, function (hostedFieldsErr, hostedFieldsInstance) {
if (hostedFieldsErr) {
// Handle error in Hosted Fields creation
return;
}
form.addEventListener('submit', function (event) {
event.preventDefault();
hostedFieldsInstance.tokenize(function (tokenizeErr, payload) {
if (tokenizeErr) {
// Handle error in Hosted Fields tokenization
return;
}
document.querySelector('input[name="payment-method-nonce"]').value = payload.nonce;
form.submit();
});
}, false);
});
});
</script>
But when I click the submit button, nothing happens.event.preventDefault() stops the submission and the payment_method_nonce token is generated, but I can't submit the form after that, because form.submit() isn't works
How can I submit the form after event.preventDefault()?
Or how can I send the payment_method_nonce token to my controller?
Thanks!
When I copied your snippet and tried to run the example, I got (index):69 Uncaught ReferenceError: form is not defined in the console. When I added
var form = document.getElementById('checkout-form');
it worked just fine.
Best guess, you just forgot to assign the form variable to reference the form dom element. If that's not the case, be sure to let me know.
So here's a great example from https://developer.forecast.io/docs/v2
What I want to do and trying is this:
I have a simply webpage whereby I want to display the current forecast and extended forecast.
Here's my Index.html
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html lang="en" class="no-js" ng-app="myApp">
<head>
<title>Weather Forecaster</title>
<meta charset="UTF-8">
<!-- favicon -->
<link rel="shortcut icon" href="images/Oxygen-Icons.org-Oxygen-Status-weather-clear.ico" />
<!-- END favicon -->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="css/style.css" rel="stylesheet" type="text/css"/>
<link href="css/jquery.jdigiclock.css" rel="stylesheet" type="text/css" />
<link href="css/wx-custom.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="js/jquery-1.12.2.js"></script>
</head>
<body ng-controller="wxController as ctrlWx">
<div class="container">
<div class="row">
<div class="col-10">
<div id="my-div" ng-model="myiFrame">
<iframe src="http://www.latlong.net/convert-address-to-lat-long.html" id="my-iframe" scrolling="no"></iframe>
</div>
<div id="plugin_container" class="forecast-panel">
<h1>Here's Today's Weather</h1>
<div class="fc forecast-panel1">
<p class="dayTitle">Day 1</p>
</div>
<div class="spacer"></div>
<div class="fc forecast-panel2">
<p class="dayTitle">Day 2</p>
</div>
<div class="spacer"></div>
<div class="fc forecast-panel3">
<p class="dayTitle">Day 3</p>
</div>
<div class="spacer"></div>
<div class="fc forecast-panel4">
<p class="dayTitle">Day 4</p>
</div>
<div class="spacer"></div>
<div class="fc forecast-panel5">
<p class="dayTitle">Day 5</p>
</div>
</div>
</div>
</div>
</div>
<script src="js/angular/angular.min.js" type="text/javascript"></script>
<script src="js/angular/app.js" type="text/javascript"></script>
<script src="js/angular/controller.js" type="text/javascript"></script>
<script src="js/angular/services.js" type="text/javascript"></script>
<script src="js/angular/ang-custom.js" type="text/javascript"></script>
</body>
</html>
Notice the "IFRAME".... the src is this: http://www.latlong.net/convert-address-to-lat-long.html
Now, if you go there, which is pretty cool, you can put ANY address to get the LAT LON for that address:
Here's a screen shot with an example LAT LON from DC... the Whitehouse.
OK, now, my code uses Angular with a simple controller and service...
Here:
APP:
/* global angular */
// Code goes here
var myApp;
myApp = angular.module("myApp", []);
myApp.config(function ($sceDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist(['self', '**']);
});
console.log("Host name is: " + document.location.hostname);
//if (document.location.hostname === "localhost") {
// myApp.constant('URL', '/WeatherForecaster/js/json/');
//} else if (document.location.hostname === "omnimanger.co/wx" || "www.omnimanager.co/wx") {
// myApp.constant('URL', '/js/json/');
//} else {
// myApp.constant('URL', '/wx/js/json/');
//}
myApp.constant("URL", {
//Default LAT/LON for CONCRETE
apiKey: "3bb0f0fe93c92922f0b42f9eabda48d0/",
lat: "48.530031",
lon: ",-121.879460",
country: "us",
uri: "https://api.forecast.io/forecast/"
}).config(function($httpProvider){
delete $httpProvider.defaults.headers.common['X-Requested-With'];
});;
myApp.constant("wx", {
data: {
latitude: 0,
longitude: 0,
currently: {},
minutely: {
summary: "",
icon: "",
data: []
},
hourly: {
summary: "",
icon: "",
data: []
},
daily: {
summary: "",
icon: "",
data: []
},
flags: {
sources: [],
"lamp-stations": [],
"isd-stations": [],
"madis-stations": [],
units: ""
}
}
});
CONTROLLER:
'use strict';
myApp.controller('wxController', function (wxDataService) {
var ctrlWx = this;
//Listen for the Submit (FIND) button on the iFrame
ctrlWx.content = {};
console.log("LAT/LON: ", ctrlWx.latlon);
ctrlWx.fetchWx = function () {
//General Data
wxDataService.getWxData().then(function (result) {
ctrlWx.content = result;
console.log("All Data: ", result);
});
};
ctrlWx.fetchWx();
});
SERVICE:
myApp.factory('wxDataService', function ($http, URL) {
console.log("URL", URL);
//DEFAULT Headers for KEY and AUTH TOKEN
var headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': ['GET', 'POST'],
'Access-Control-Allow-Headers': 'Content-Type',
'Content-Type': 'application/json'
};
var myURL = {
data: {
header: headers,
uri: URL.uri + URL.apiKey + URL.lat + URL.lon
}
};
var getWxData = function () {
return $http.get(myURL)
.success(function (data) {
console.log("SUCCESS!");
console.log("The Weather Data is here: " + data);
return data;
})
.error(function (e) {
console.log("He\'s dead Jim!<br>", e);
return e;
});
};
return {
getWxData: getWxData
};
});
SOLUTION I'm Trying to Achieve:
When the user enters the address and clicks the "FIND" button, which generates the LAT LON, I want to capture that LAT LON inside the IFRAME.
This is what I'm trying to do, but I know I need to make a directive that BINDS the "CLICK" or "SUBMIT" event to the FIND button. What I have below is NOT that; yet.
var latlon = {};
$(function () {
$('#my-iframe').load(function () {
$(this).contents().find("#latlongform, #gadres").live('blur', function (e) {
latlon = {
mylat: $("input[name='lat']").val(),
mylon: $("input[name='lon']").val()
};
if (e) {
console.log("Err: ", e);
return e;
}
});
});
});
GIVENS:
The FORM and the LAT LON are as follows:
<div class="row">
<div class="col-8 graybox">
<form id="latlongform">
<label for="gadres">Address</label>
<input id="gadres" type="text" class="width70" placeholder="Type address here to get lat long" required="">
<button title="Find lat long coordinates" class="button">Find</button><br>
<small>Write city name with country code for better results.</small>
</form>
<div class="row">
<div class="col-6 m2">
<label for="lat">Latitude</label>
<input type="text" name="lat" id="lat" placeholder="lat coordinate">
</div>
<div class="col-6 m2">
<label for="lng">Longitude</label>
<input type="text" name="lng" id="lng" placeholder="long coordinate">
</div>
</div>
</div>
</div>
QUESTION:
How can I get the LAT LON, "AFTER" the user clicks FIND, THEN fire my angular service to inject the CALL to the URL which gets the WEATHER DATA...as described. Here's that WEATHER DATA JSON OBJECT. It uses an API KEY which mine is limited to 1000 uses per day.
If you'd like to see what the result is on the weather API, you need to get a FREE API_KEY.... it gives 1000 hits per day...
Thanks everyone and I hope you can all this this is a VALID question.
Accessing the Forecast.io API with JSONP
The forecast.io website doesn't support CORS (Cross Origin Resource Sharing) for GET operations but it does support JSONP.
Revised Code
var url = myURL.data.uri;
var jsonpURL = url+"?callback=JSON_CALLBACK";
var getWxData = function () {
return $http.jsonp(jsonpURL)
.then(function (response) {
console.log("SUCCESS!");
console.log(response.data);
//return to chain data
return response.data;
})
.catch(function (e) {
console.log("He\'s dead Jim!");
console.log(e);
//throw to chain rejection
throw e;
});
};
Sample Result
LAT: 48.530031
LOG: -121.87946
TIMEZONE: America/Los_Angeles
SUMMARY: Partly Cloudy
TEMP: 56.02
The DEMO on JSFiddle.
Notice that I changed the .success and .error methods to .then and .catch respectively. Those old methods are deprecated and ignore return values.
I tried sending email by referring various links but in vain.I just want to send email and below is my code for sending email. Please suggest the changes .
Thanks in advance :)
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/ionic/js/ng-cordova.min.js"></script>
<script src="js/cordova.js"></script>
<script src="js/app.js"></script>
</head>
<body ng-app="starter" ng-controller="ExampleController">
<ion-pane>
<ion-content>
<div class="padding">
<button class="button button-icon icon ion-email" ng-click="vesitEmail()">
Send Email
</button>
</div>
</ion-content>
</ion-pane>
</body>
</html>
App.js
var example=angular.module('starter', ['ionic','ngCordova'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
});
example.controller('ExampleController', function($scope,$cordovaEmailComposer) {
$cordovaEmailComposer.isAvailable().then(function() {
// is available
alert("available");
}, function () {
// not available
alert("not available");
});
$scope.vesitEmail = function(){
var email = {
to: 'siddhesh.kalgaonkar#ves.ac.in',
cc: 'monish.gupte#mservices.in',
bcc: null,
attachments: null,
subject: 'Mail subject',
body: 'How are you? Nice greetings from Leipzig',
isHtml: true
};
$cordovaEmailComposer.open(email).then(null, function () {
// user cancelled email
});
}
window.alert("Message Sent");
});
When i test in browser it shows below error :
TypeError: Cannot read property 'plugins' of undefined
and when i test it on mobile phone it doesnt work on it as well.
For email, you will have to install Cordova Email Plugin. The plugin provides access to the standard interface that manages the editing and sending an email message. Install using CLI
cordova plugin add https://github.com/katzer/cordova-plugin-email-composer.git
$scope.vesitEmail = function(){
cordova.plugins.email.isAvailable(
function (isAvailable) {
if(isAvailable){
cordova.plugins.email.open({
to: [''],
cc: [''],
bcc: [''],
subject: '',
body: ''
});
}else{
alert('Service is not available.');
}
}
);
};
I have used like this after installing Cordova Email Plugin in my project.. hope it may help...
$scope.sendEmail = function () {
if (window.plugins && window.plugins.emailComposer) {
window.plugins.emailComposer.showEmailComposerWithCallback(function (result) {
alert(result);
},
"Feedback Form", // Subject
$scope.emailText[0].body, // Body
["ameerhamza810#gmail.com"], // To
null, // CC
null, // BCC
false, // isHTML
null, // Attachments
null); // Attachment Data
}
}