How to get data from a form dropdown select element? - node.js

I'm using Express.js and trying to get form data of a dropdown select element,
I tried with body-parser but what I get with eq.body.method_select is undefined.
I didn't find much info about how to do this on the web.
Here is my code html code:
<form action="url_analyse">
<div class="col-lg-6">
<div class="input-group">
<select class="custom-select mb-2 mr-sm-2 mb-sm-0" name="method_select" id="inlineFormCustomSelect">
<option value="5">Regular Search (Short)</option>
<option value="10">Intense Search (Long)</option>
<option value="20">Deep Search (Very Long)</option>
</select>
<input type="text" name="url_input" class="form-control" placeholder="Enter URL">
<span class="input-group-btn">
<button class="btn btn-secondary">Go!</button>
</span>
</div>
</div>
Here is my js code:
app.get('/url_analyse', function(req, res) {
console.log(req.body.method_select);
})
Hope you can help me with that.
Thank you.

There are two issues here:
You might want to explicitly add the leading forward slash: action="/url_analyse"
The default form submission HTTP method is GET, which means that form fields will be passed in the query string portion of the URL. This means you will instead need to access req.query to get at the form fields. You only need body-parser and req.body when you use POST and other methods (with the appropriate enctype) to submit your form.

Related

Cannot pass variables to Django 3 method from HTML template

I am a Django newbie who is trying to convert an existing HTML based website to Django 3. The only complex piece of this page is a call to a Django method that uses the django.core.mail package and everything works, but, I am trying to pull some data off of the HTML template and pass it to this method.
The method works, only it sends a blank email. I am trying to pass contact information that the end user would fill out on the form. If I hard code the data into the method it works.
I have tried passing the data through urls.py, but, everything I try fails to even parse when I call the method. When I use a request.GET.get everything seems to work, just no data.
I was hoping to use something similar to JQuery like the following in the method.
name = str(request.GET.get('Name:', '').strip())
email = str(request.GET.get('Email:', '').strip())
msg1 = str(request.GET.get('Message:', '').strip())
with the fields being in the HTML form.
I am going to include some of the relevant configuration items below.
urls.py
from django.urls import path
from django.conf import settings
from django.conf.urls import url
from django.conf.urls.static import static
from . import views
app_name = 'willdoit'
urlpatterns = [
path('', views.index),
#url(r'^contact/(?P<name>\.+)/(?P<email>\.+)/(?P<msg1>\.+)/?$', views.contact, name='contact'),
path('contact/', views.contact, name='contact'),
]
views.py
def contact(request):
name1 = request.GET.get('name', '')
email1= request.GET.get('email', '')
msg1 = request.GET.get('message1', '')
subject = 'Work needed'
from_email = settings.DEFAULT_FROM_EMAIL
message = name + ' ' + email + ' ' + msg1
recipient_list = ['pkustra914#gmail.com']
send_mail(subject, message, from_email, recipient_list, fail_silently=False)
return HttpResponse('Success')
Relevant HTML Template section
<div class="contact_content">
<div class="col-md-6 col-sm-6 col-xs-12">
<div class="contact_message wow fadeInLeft" data-wow-duration="1.5s">
<form action="#" id="formid">
<form action="#" id="formid">
<div class="form-group"> <input class="form-control" name="name"
placeholder="Name" required="" type="text"> </div>
<div class="form-group"> <input class="form-control" name="email"
placeholder="Email" required="" type="email"> </div>
<div class="form-group">
<div class="Descrizione"> <label for="InserisciDescrizione"
class=""><b>Message</b></label> <textarea class="form-control"
id="message" placeholder="Type message:" name="message1" rows="6" cols="50"
title="Message"></textarea> </div>
<a id="submit" href="{% url 'willdoit:contact' %}" class="btn btn-primary">Submit</a>
I would prefer to use the request.GET.get method, but, there is a lot more documentation passing it through the urls.
Thanks.
Your code request.GET.get('Name:', '') returns empty string when the key 'Name:' is not found.
To fix this, use request.GET.get('name', '') request.GET.get('email', '') request.GET.get('message', '') instead.
Details
I see that you are using a with template tag for nothing. The following line of code does not change the name attribute string to PascalCase. See with template tag (Docs)
{% with Name=name Email=email Message=message %}
Even if it worked, your code should be calling request.GET.get('Name', '') instead of request.GET.get('Name:', ''). But it won't work, as with would not modify the attribute names in the GET request.
#EDIT1
There are apparently more bugs in your html code. I have reformatted your code and listed up some obvious bugs.
<!--REFORMATTED CODE-->
<form action="#" id="formid"> <--------------DUPLICATES, remove one
<form action="#" id="formid"> <--------------DUPLICATES, remove one
<div class="form-group"> <input class="form-control" name="name"
placeholder="Name" required="" type="text"> </div>
<div class="form-group"> <input class="form-control" name="email"
placeholder="Email" required="" type="email"> </div>
<div class="form-group">
<div class="Descrizione">
<label for="InserisciDescrizione" class=""><b>Message</b></label>
<textarea class="form-control" id="message"
placeholder="Type message:" name="message1" rows="6" cols="50"
title="Message"></textarea>
</div>
<a id="submit" href="{% url 'willdoit:contact' %}"
class="btn btn-primary">Submit</a>
<-------- MISSING DIV END TAG
<-------- MISSING FORM END TAG
Furthermore, you are calling the server by url directly using the following code:
<a id="submit" href="{% url 'willdoit:contact' %}" class="btn btn-primary">Submit</a>
This does not tell the page which form you want to submit (there are cases where there are multiple forms).
You have two choices:
Replace the tag with standard html form submit button <input type="submit">, and add the url to the action attribute of the form. Use the following code to do so:
<form action="{% url 'willdoit:contact' %} id="formid">
...
...
<input id="submit" type="submit" class="btn btn-primary" value="Submit"/>
</form>
This solution will by default use the GET method to send a request to the server, and you will be able to get the inputted values by calling request.GET.get(name).
If you are using JQuery, you can replace the with the following:
Submit
This is however not recommended. Please use the standard html form input tag for the submit button.
Great. Moving the method call to the form tag worked great.
Thanks! You guys are the best.

How to get value of checkbox plus another value together from ejs with express

in the code below, I want to get checkbox value 'on/undefined' based on user selection and the value which I am passing (item._id) together in req.body. how do I do that?
<form action="/update" method="POST">
<div class="items">
<input type="checkbox" name="checkbox" value="<%= item._id%>" onChange=" this.form.submit()">
<p><%= item.title %></p>
</div>
</form>
Got the answer : Pass the additional attribute as hidden property.

How to change the pop html on button click

I am trying to find a way to change the pop up HTML on a chrome extension to another one when you click a button. I have tried to make a onclick function href but nothing works. I am new to both HTML and chrome extensions so I am sorry if this problem seems easy to the more experience developers.
<form id="gform" method="POST" class="pure-form pure-form-stacked" data-email="from_email#example.com"
action="https://script.google.com/a/cvsd356.org/macros/s/AKfycbxb4ZyUUQCnTN-7iYF-YRViDSy/exec">
<div class="name">
name: <input type="text" name="Name" id= "inputbox"><br>
</div>
<div class="id">
ID# <input type="text" name= "ID" id= "inputbox"><br>
</div>
<div class="MailingAddress">
Mailing Address: <input type="text" name= "Mailing Adresss" id= "inputbox" style=width:350px;><br>
</div>
<div class="sendToTr">
Send Transcript to: <input type ="text" name="College" style=width:350px; id= "inputbox" ><br>
</div>
<div class="emailmy">
<label for="email"><em>Your</em> Email Address:</label>
<input id="inputbox" name="email" type="email" value=""
required placeholder="your.name#email.com" />
</div>
<div class="sButton">
<button style=height:30px;width:70px;border-radius: 3px; class="button-success pure-button button-xlarge">
send
</button>
</div>
I think there are quite a few ways to achieve what you are asking. If I were you, I would add a JavaScript file to my project to do this.
Step 1:
I would tell my HTML page where to find this JS file. The sample below can be included near the end of your HTML file, right before </body></html>. The sample below assumes your new popup.js file is in the root folder of your project:
<script src="popup.js" type="text/javascript"></script>
Step 2:
In the popup.js file, I would create a function that tells the popup how it should be modified. In the sample below, I'm going to hide the element with an ID of "theOldElement" and show the element with an ID of "theNewElement". I'm also going to attach this function to the click event of "theButton" element.
popup.js
function updatePopup(){
document.getElementById("theNewElement").style.display = "block";
document.getElementById("theOldElement").style.display = "none";
}
document.getElementById('theButton').addEventListener('click', updatePopup);
Step 3:
I like referring to my HTML elements by ID (as I've been doing above - note the "getElementById" references), so I would:
add id="theNewElement" to the element I want to reveal
add id="theOldElement" to the element I want to hide
add id="theButton" to the button that I want to trigger this change
Note: you can insert these IDs as the first attribute within the tag you want to identify. E.g., <div id="theNewElement" ...

Adding comment features to blog using express and handlebars

I'm trying to create a blog site that has the ability to comment on a blog/article. I have the end point
app.get('/post/:slug', function(req, res) {
var _slug = req.params.slug;
var blog_post = _.findWhere(_DATA, { slug: _slug });
if (!blog_post) return res.render('404');
res.render('post', blog_post);
});
that handles the display of a blog/article using HandleBars. It retrieves a post from database _DATA and simply display it using the template post.handlebars. It right now does nothing else.
I would like to add the ability to comment on this article. I'm very new to web programming and don't know how to handle requests like that. Right now, my idea is to add
<article>
<form method="POST" action="/comment">
<div class="input-field">
<label>Comment:</label>
<textarea type="text" name="comment" rows="20" placeholder="What's on your mind?"></textarea>
</div>
<button type="submit">Add Comment</button>
</form>
</article>
to the bottom of my post.handlebars and add the end point app.post('/comment', function(req, res) {});
But this presents multiple problems, namely, how would I know which article I'm commenting on? In this new end-point, my req.body would contain nothing except the contents of the comment.
What is the proper way to handle this?
Put the ID of your article in the comment form as an hidden input. When you'll submit the form you'll get the article-id value.
I've used handlebar to place the article id in the form change the value of article.id according to your data.
<article>
<form method="POST" action="/comment">
<div class="input-field">
<label>Comment:</label>
<textarea type="text" name="comment" rows="20" placeholder="What's on your mind?"></textarea>
</div>
<input type="hidden" name="article-id" value="{{article.id}}">
<button type="submit">Add Comment</button>
</form>
</article>

Use App Scripts to open form and make a selection

To put this briefly I am testing a Google drive form that will record votes for a school election to ensure that it is secure.
Is there a way to open a form from the shared URL and list/input data? In short, can I write a script to act like a bot that will vote and try to crash the form?
Sample URL: http://docs.google.com/forms/d/RANDOM_STRING/viewform
Edit: Some time around the end of 2014 a change in the Google Forms service invalidated this hack. Look at Is it possible to 'prefill' a google form using data from a google spreadsheet? and How to prefill Google form checkboxes? for a solution that relies on the Form methods.
A Google Form, when shown as a "live form", is just an HTML Form, with all the regular behaviors of a form. You can view the HTML source of a live form, and get the information that will help you simulate POST requests.
HTML Form
For example, look at the form from Spreadsheet Email Trigger. Here is the form HTML, cleaned up for readability:
<form action="https://docs.google.com/spreadsheet/formResponse?formkey=#FORMKEY#&ifq"
method="POST" id="ss-form">
<br>
<label class="ss-q-title" for="entry_0">First Name
<span class="ss-required-asterisk">*</span>
</label>
<label class="ss-q-help" for="entry_0"></label>
<input type="text" name="entry.0.single" value="" class="ss-q-short" id="entry_0">
<br>
<label class="ss-q-title" for="entry_1">No of User
<span class="ss-required-asterisk">*</span>
</label>
<label class="ss-q-help" for="entry_1"></label>
<select name="entry.1.single" id="entry_1">
<option value="5">5</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
</select>
<br>
<label class="ss-q-title" for="entry_2">Email ID
<span class="ss-required-asterisk">*</span>
</label>
<label class="ss-q-help" for="entry_2"></label>
<input type="text" name="entry.2.single" value="" class="ss-q-short" id="entry_2">
<br>
<input type="hidden" name="pageNumber" value="0">
<input type="hidden" name="backupCache" value="">
<input type="submit" name="submit" value="Submit">
<div class="password-warning">Never submit passwords through Google Forms.</div>
</form>
Important elements are marked in this screenshot:
Script to simulate a Google Form submission
Armed with the action URL and field names, we can code a function to programmatically submit a form, by modifying the example from the UrlFetch documentation:
// Simulate POST to form
function sendHttpPost() {
// Copy the entire URL from <form action>
var formAction = "https://docs.google.com/spreadsheet/formResponse?formkey=#FORMKEY#&ifq";
var payload = {
"entry.0.single": "Nelson", // First Name
"entry.1.single": "10", // No of users
"entry.2.single": "user#example.com" // Email ID
};
// Because payload is a JavaScript object, it will be interpreted as
// an HTML form. (We do not need to specify contentType; it will
// automatically default to either 'application/x-www-form-urlencoded'
// or 'multipart/form-data')
var options = {
"method": "post",
"payload": payload
};
var response = UrlFetchApp.fetch(formAction, options);
}
Result
Here's the result of the above script, a form response has been added to the spreadsheet.

Resources