I am currently experimenting with the EmailJS library, I have followed the documentation to what I thought was 100%, I placed the code in the script tag that is embedded in the head on the contact.html, when I send the form, I get a error in the console that says "unexcepted", I created a file called sendEmail.js and wired it to my contact.html, and tried it there, here is the issue:
I am being told that my service ID is incorrect, I went, updated it, and then was told my template ID is incorrect too, so I updated that, saved it and tried again, its still not working, please see attached screenshot of the details on my test emailJS account:
Service ID:
Service ID
Template ID:
Template ID
Here is my contact.html code:
This is my init method in the
<script type="text/javascript">
(function() {
emailjs.init("user_vanqZMkpPOADQP2iEpqKS");
})();
</script>
Here is my form code:
<form onsubmit="return sendMail(this);">
<input type="text" name="name" class="form-control" id="fullname" placeholder="Name" required/>
<input type="text" name="emailaddress" class="form-control" id="emailaddress" placeholder="Email" required/>
<textarea rows="5" name="projectsummary" class="form-control" id="projectsummary" placeholder="Project Description" required></textarea>
<button type="submit" class="btn btn-secondary center-block">Send Project Request</button>
</form>
Here is my sendEmail.js code:
// function has one one argument "contactForm"
function sendMail(contactForm) {
const templateParams = {
"from_name": contactForm.name.value,
"project_request": contactForm.projectsummary.value,
"from_email": contactForm.emailaddress.value
};
const serviceID = "service_golcdlt";
const templateID = "template_7qaoafp";
// Service ID, Template ID, template parameters
emailjs.send(serviceID, templateID, templateParams)
.then(
function(response) {
console.log("SUCCESS", response)
},
function(error) {
console.log("Error: Unable to send", error)
}
);
return false; // To block from loading a new page
};
What am I missing or doing wrong?
Related
I have the following HTML:
<!DOCTYPE html>
<html>
<head>
<title>My Login Form</title>
</head>
<body>
<form class="login-form" ng-submit="login(credentials)" ng-controller = "loginScreenController">
<label for="username">Username:</label><br>
<input type="text" id="username" name="username" ng-model="credentials.username"><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password" ng-model="credentials.password"><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
Associated is an angularJS script which is used to execute the login() function:
var webApp = angular.module('App.module', [ngCookies]);
webApp.controller('loginScreenController',loginScreenController);
loginScreenController.$inject = ['$https','$cookies'];
function loginScreenController($https,$cookies) {
console.log("We launched the function!")
print("ffs is it working yet?")
var vm = this;
vm.login = login;
// Credentials is passed not explciitly as a JSON object, but formatted thusly and the server handle it as if it is JSON
function login(credentials) {
console.log("Print something")
}
}
I am using the "Live Server" extension in VSCode to host the HTML. I am expecting the console.log to print something to terminal in VSCode when the but nothing happens upon clicking the button. I also checked "Output" and nothing happens there. Am I looking in the wrong spot? Is there something wrong with my code?
I am using Streamlit to build a simple app. In this app I made a simple form using FormSubmit to let people contact me. But I don't want them to leave the website when they click on Send button, so I am trying to send the form using AJAX.
To integrate JS in Python I am using Js2Py, but I can't solve this.
This is the form:
contact_form = """
<form id="myForm">
<input type="hidden" name="_captcha" value="false">
<input type="text" name="name" style="font-size:20px;background-color:#72c2dd; color:#000000" placeholder="Your name" required>
<input type="email" name="email" style="font-size:20px;background-color:#72c2dd; color:#000000" placeholder="Your email" required>
<textarea name="message" style="font-family:'Alegreya, serif';
font-size:20px;" placeholder="Your message here" required></textarea>
<input type="hidden" name="_template" value="table">
<button type="submit" value="Submit" id="sendButton" class="block">Send</button>
</form>
"""
so I made a javascript variable, to check when Send button is clicked:
check_submit = '''<script src="https://code.jquery.com/jquery-3.6.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#sendButton").click(function(e) {
e.preventDefault();
var form = $('myForm'[0]);
var data = new FormData(form);
$.ajax({
method: "POST",
url: "https://formsubmit.co/my-email",
dataType: 'json',
data: data,
success: (data) => console.log(data),
error: (err) => console.log(err)
});
});
});
</script>
'''
then:
st.markdown(contact_form, unsafe_allow_html=True)
So I am passing the javascript variable into the function eval_js() from Js2Py:
js2py.eval_js(check_submit)
I got my form up, and an error message below the form:
JsException: SyntaxError: Line 1: Unexpected token <
and when I fill the form and clicking the Send button, nothing happens.
This means according to me that I misunderstood how to use JS2Py in Python!!!
Any help/suggestion to show me where I did wrong, is very appreciated
I am experiencing a "Method Not Allowed" issue when trying to override my POST request with PUT (for updating information in my blog). I already installed method override for koa.
HTML:
<div class="create-message content">
<form action="/messages/edit/<%= message.id %>?_method=PUT" method="POST">
<label for="title">Message title:</label>
<input required value="<%= message.title %>" type="text" id="title" name="title" required>
<label for="snippet">Message snippet:</label>
<input required value="<%= message.snippet %>" type="text" id="snippet" name="snippet" required>
<label for="body">Message body:</label>
<input required value="<%= message.body %>" type="text" id="body" name="body" required>
<button>Update</button>
</form>
My routs are the following:
//edit message
router.get('/messages/edit/:id', async (ctx, next) => {
const id = ctx.params.id;
const result = await MessageModel.findById(id)
await ctx.render('edit', {
title: 'Messages',
message: result
})
});
The code above runs well, but after I click on submit button, "Method Not Allowed" issue occurs instead of running this:
//update edited message
router.put('/messages/edit/:id', async (ctx, next) => {
MessageModel.findByIdAndUpdate(ctx.params.id, ctx.request.body, {new:true}, (err:any, result:any) => {
})
return ctx.redirect('/');
});
Please share your thoughts on this issue.
Thank you
Make sure you add the following to your app.js (index.js) file.
app.use(methodOverride('_method'));
You can't set the form method to PUT, it's either GET or POST.
to send a PUT request you can use AJAX, via (for instance) the Fetch API
EDIT: my bad, you used the "tunneling" concept mentioned in that solution.
per this documentation, maybe try with
<form method="POST" action="/resource" enctype="application/x-www-form-urlencoded">
<input type="hidden" name="_method" value="PUT">
Objective
FrameWork used : ElectronJS
I want to take the user submitted form, and use the NodeJS script to generate a JSON file on client PC. The json file will have key and value pairs.
Please see below for expected output.
HTML
<form id="form" method="POST" action="#">
<div class="form-group col-auto">
<input type="text" class="form-control" id="username" name="username" placeholder="Enter Username" value="">
</div>
<div class="form-group col-auto">
<input type="text" class="form-control" id="account" name="account" placeholder="Enter Account" value="">
</div>
<button type="submit" id="save" class = "btn text-white mb-0"> Save </button>
</form>
JS
document.getElementById("save").addEventListener('click', saveJSON(e))
async function saveJSON(e){
e.preventDefault()
var userData = document.getElementById('username').value
var acctData = document.getElementById('account').value
var formData = userData + acctData;
console.log(formData);
await writer.jsonWriter(formData);
//Error - Uncaught TypeError: Cannot read property 'value' of undefined.
Error
Here is the error I am facing
NodeJS Script
async function jsonWriter(data){
let element = JSON.stringify(data);
fs.writeFileSync(__dirname + '\\data\\auth.json', element)
}
module.exports.jsonWriter = jsonWriter;
Required Output
// auth.json
{"username":"Stack","account":"Overflow"}
I believe there was an issue with how you were passing your event into your function and trying to call preventDefault(). I put your function directly on the event listener method with async keyword.
As previously mentioned, document.querySelector() uses CSS selectors unlike document.getElementById(). In your case I would stick with getting the input elements by their ID.
Like Paul said in his answer, you need a JavaScript object for JSON.stringify() to work properly.
document.getElementById("save").addEventListener('click', async function(e) {
e.preventDefault()
var userData = document.getElementById('username').value
var acctData = document.getElementById('account').value
var formData = {
username: userData,
account: acctData
}; // create JS object
console.log(JSON.stringify(formData));
});
<form id="form" method="POST" action="#">
<input type="text" id="username" name="username" placeholder="Enter Username">
<input type="text" id="account" name="account" placeholder="Enter Account">
<button type="submit" id="save">Save</button>
</form>
Okay I think that I can see your mistake.
In the Javascript you can change this part :
var formData = userData + acctData;
console.log(formData);
await writer.jsonWriter(formData);
To this part :
Try to assign it to a javascript object like that :
var formData = {username: userData, account: acctData};
console.log(formData);
await writer.jsonWriter(formData);
it will stringify your object and write an appropriate output.
I think.
I have this form in HTML and I am trying to convert it into a POST request using a frontend framework (either AngularJS or Angular2). The purpose of this form is to allow a client to subscribe to my wordpress blog. I am trying to convert it from PHP to Angular2 (if someone knows how to convert it to AngularJS I can convert to Angular2 from there). How would I do this? What would have to be in the body of the POST request vs query strings? I am having trouble understanding exactly what role each part of this form plays in the POST request.
EDIT: Just to clarify, I know how to use AngularJS and Angular2 and how to use the HTTP service in both of them. I am wondering how to convert the form into the body/query strings of the request.
<form action="/blog/" class="form-inline" role="form" method="POST" accept-charset="utf-8" id="subscribe-blog">
<!-- add hidden inputs for wordpress jetpack widget -->
<input type="hidden" name="action" value="subscribe" />
<input type="hidden" name="source" value="http://www.mywebsite.com/blog/" />
<input type="hidden" name="sub-type" value="widget" />
<input type="hidden" name="redirect_fragment" value="blog_subscription-2" />
<label class="sr-only" for="exampleInputEmail">Email address</label>
<input type="email" class="form-control wide" id="exampleInputEmail" placeholder="Enter email address">
<button type="submit" name="jetpack_subscriptions_widget" class="btn btn-submit">Subscribe</button>
</form>
Would something along the lines of this be correct?
postForm() {
var body = {
action: 'subscribe',
source: 'http://www.mywebsite.com/blog/',
sub-type: 'widget',
redirect_fragment: 'blog_subscription-2',
email: 'clientEmailAddress#gmail.com', // don't think this is right
// not sure what to do with `jetpack_subscriptions_widget` attribute on the submit button either
};
return this.http.post(`http://www.mywebsite.com/blog/`, body)
.map(res => res.json())
.toPromise()
.then(data => {
return data;
});
}
You need to include angular.min.js and script.js
html
<body ng-app="myApp" ng-controller="myCtrl">
<input type="text" ng-model="name" />
<input type="submit" value="Send" ng-click="send(name)"/>
</body>
angular js code:
script.js
angular.module('myApp', [])
.controller('myCtrl', ['$scope', '$http', funtion($scope, $http){
$scope.name = ""; // intially the input field is empty. As you type in the input field, the value will be updated here.
$scope.send = function(name){
alert(name);
var url = $scope.name; // try to enter an url
$http.get(url).then(function Success(res){
// here you can do anything with res
}, function Error(err){
alert(error);
})
}
}]);
Using angular, you split the application in parts:
view (html)
process some validations, etc (controller)
and do some model logic processing (service).
If you want to make the http request completely with angular to an endpoint (backend service, REST, or any other), usually in this case:
You use ng-model for each input field you need to send in the request, something like <input type="text" ng-model="val">. In your case your html would be something like:
html
<form ng-submit="send()" class="form-inline" role="form" accept-charset="utf-8" id="subscribe-blog">
<!--no need of 'action' attribute in the form since the post will be done using angular-->
<!-- add hidden inputs for wordpress jetpack widget -->
<input type="hidden" name="action" value="subscribe" ng-model="subscribe"/>
<input type="hidden" name="source" value="http://www.mywebsite.com/blog/" ng-model="source"/>
<input type="hidden" name="sub-type" value="widget" ng-model="widget" />
<input type="hidden" name="redirect_fragment" value="blog_subscription-2" ng-model="redirect_fragment"/>
<label class="sr-only" for="exampleInputEmail">Email address</label>
<input type="email" class="form-control wide" id="exampleInputEmail" placeholder="Enter email address" ng-model="email">
<button type="submit" name="jetpack_subscriptions_widget" class="btn btn-submit">Subscribe</button>
</form>
Then in your controller you can process all your ng-model if needed and then pass those values to a (angular) service like this
//....angular controller
function send(){
//..collect params using the ng-models
var params = [];
params['email'] = $scope.email; //here you define 'email' as the name of the param received by the webservice as input !!!
myService.sendValues(params).then(function(data){
})
}
...where you would finally send the values to the php service like code below:
//... angular service
function sendValues(params){
var url = "miendpointurl/subscribe";
//... at this pont in params you have all those params you named like 'email', 'subscribe' and so on
return $http.post(url, params).then(function(response){
return response.data;
},
function(responseOnError){
return responseOnError.data;
}
}
Angular will interact with the php service transparently to you and will give you back the server response.