Django request.GET does not contain name of submitted form button - html

I'm basically having the same issue addressed in a previous question (Django request.POST does not contain the name of the button that submitted the form) but the fix described there does not work.
I am using ajax so that, after submission, I stay on the same page. My page has two forms. The first form has three buttons and I correctly pass the "name" of the button in the GET request. My second form has two buttons but I am unable to pass the "name" of either button in the GET request (the "name" of the input field, however, is in the GET request). I don't know why it's not working. Any ideas?
JS SOLUTION:
$(document).ready(function(){
console.log("hello from email.js");
$('.email_citations').submit(function(event){
console.log("submit email");
var whichButton = $(".form_button[clicked=true]")[0].value
console.log("WHICH BUTTON: ");
console.log(whichButton);
var email_address = $(this).val();
var data = $(this).serialize();
data += "&" + whichButton;
console.log(data);
$.ajax({
data: data,
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function(data){
console.log("DATA: ");
console.log(data);
$('.email_sent_message').html(JSON.parse(data).submit_message);
}
});
return false;
});
$(".form_button").click(function() {
$(".form_button").removeAttr("clicked");
$(this).attr("clicked", "true");
});
});
html forms:
<!-- This form works! -->
<form action="export_options" method="get">
<button type="submit" name="plain" class="button inline large hover" id="exportButton2">Download Plain Text</button>
<button type="submit" name="ris" class="button inline large hover" id="exportButton1">Download RIS File</button>
<button type="submit" name="bibtex" class="button inline large hover" id="exportButton3">Download BibTeX File</button>
</form>
<form class="email_citations" id="EmailCitationsForm" action="email_it" method="get">
<input class="input-text" type="text" size="75" maxlength="75" style="width: 40%; font-size: 16px; margin-right: 5px; height: 50px" name="email_address" placeholder="email address">
<button type="submit" value="selected" name="which_citations" class="form_button button inline large hover" id="exportButton4" >Send My Selected Citations</button>
<button type="submit" value="all" name="which_citations" class="form_button button inline large hover" id="exportButton5">Send All Citations</button>
</form>
<div class="email_sent_message" style="float: left; color: #9e1d2a; font-size: 20px; font-weight: bold">{{ submit_message }}</div>
My javascript/ajax in an email.js file:
$(document).ready(function(){
console.log("hello from email.js");
$('.email_citations').submit(function(event){
console.log("submit email");
var clicked_button = $(".form_button[clicked=true]")[0].name;
console.log(clicked_button);
clicked_button.push($(".form_button[clicked=true]")[0].value);
console.log(clicked_button);
var email_address = $(this).val();
var data = $(this).serialize();
data += "&" + clicked_button;
console.log(data);
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function(data){
$('.email_sent_message').html(JSON.parse(data).submit_message);
}
});
return false;
});
$(".form_button").click(function() {
$(".form_button").removeAttr("clicked");
$(this).attr("clicked", "true");
});
});`
My view:
def email_it(request):
context = RequestContext(request)
if request.method == 'GET':
getdict = request.GET.dict()
form = EmailCitationsForm(request.GET)
if form.is_valid():
context = request.session.get('All_Citations_Context')
if ('which_citations') in getdict.keys():
if 'all' in getdict.values():
text_template = 'email_allCitations.txt'
html_template = 'email_allCitations.html'
text_content = render_to_string(text_template, context, context_instance=RequestContext(request))
html_content = render_to_string(html_template, context, context_instance=RequestContext(request))
msg = EmailMultiAlternatives(subject, text_content, from_email, to)
#msg.attach()
msg.attach_alternative(html_content, "text/html")
msg.send()
submit_message = "Thank you. Your citations have been sent via email."
return http.HttpResponse(json.dumps({'submit_message': submit_message}))
if 'selected' in getdict.values():
text_template = 'email_selectedCitations.txt'
html_template = 'email_selectedCitations.html'
text_content = render_to_string(text_template, context, context_instance=RequestContext(request))
html_content = render_to_string(html_template, context, context_instance=RequestContext(request))
msg = EmailMultiAlternatives(subject, text_content, from_email, to)
msg.attach_alternative(html_content, "text/html")
msg.send()
submit_message = "Your citations have been sent via email."
return http.HttpResponse(json.dumps({'submit_message': submit_message}))
else:
submit_message = "Something went wrong. Sorry, your email did not send."
else:
submit_message = form.errors['email_address']
else:
form = EmailCitationsForm()
submit_message = ""
return http.HttpResponse(json.dumps({'submit_message': submit_message}))

Ok, this is more of an HTML/jQuery problem than a Django one.
First, your first form works because presumably you let the browser handle the submit. If you use a similar code to the one provided, it does not work.
If you log $(this).serialize() you get precisely what you get on the backend. Check out this answer jQuery: how to get which button was clicked upon form submission?
<form class="email_citations" id="EmailCitationsForm" action="email_it" method="get">
<input class="input-text" type="text" size="75" maxlength="75" style="width: 40%; font-size: 16px; margin-right: 5px; height: 50px" name="email_address" placeholder="email address">
<button type="submit" value="selected_citations" name="selected_citations" class="form_button button inline large hover" id="exportButton4" >Send My Selected Citations</button>
<button type="submit" value="all_citations" name="all_citations" class="form_buttonbutton inline large hover" id="exportButton5">Send All Citations</button>
</form>
Notice I've removed the django bits.
$(document).ready(function(){
console.log("hello from email.js");
$('.email_citations').submit(function(event){
console.log("submit email");
var clicked_button = $(".form_button[clicked=true]")[0].name;
console.log(clicked_button);
var email_address = $(this).val();
var data = $(this).serialize();
data += "&" + clicked_button;
console.log(data);
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function(data){
$('.email_sent_message').html(JSON.parse(data).submit_message);
}
});
return false;
});
$(".form_button").click(function() {
$(".form_button").removeAttr("clicked");
$(this).attr("clicked", "true");
});
});
Or see in plunker http://plnkr.co/edit/CxPGmxQfeHhtsWiANDJ1

Related

HTML Get method

I have create a form with one text field and one select field and using GET method. Is it possible to make the parameter combine to one when submit the form? Example: test.html?domain=test.com
<form action = "test.html" method = "GET">
Name: <input type = "text" name = "domain" />
<select name="domain_ext" class="inputAuto">
<option value=".com">.com</option>
</select>
<input type = "submit" />
</form>
You can use XHR https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
Here's a very basic example:
var getData = function () {
var xhr = new XMLHttpRequest();
var domain = document.querySelector('.domainInput').value;
var ext = document.querySelector('.extInput').value;
xhr.responseType = 'text';
xhr.onload = function () {
if (xhr.readyState === xhr.DONE && xhr.status === 200) {
document.querySelector('.output').innerText = xhr.responseText;
}
};
xhr.open('GET', domain + ext, true);
xhr.send(null);
};
document.querySelector('.getButton').addEventListener('click', getData);
<form>
Name: <input type="text" value="https://output.jsbin.com/juwuy" class="domainInput" />
<select class="extInput">
<option value=".js" default>.js</option>
<option value=".com">.com</option>
</select>
<input type="button" value="Get" class="getButton"/>
</form>
<p class="output"></p>

Issue Inserting MySQL Record With Node.js and Handlebars

I am having an issue when trying to submit a form with user information that inserts into a table. I have a userForm that allows user data to be entered with the following:
<form id="userForm">
<fieldset>
<legend>Add User</legend>
<p>First Name: <input id="fname" type="text" name="fname"/></p>
<p>Last Name: <input id="lname" type="text" name="lname"/></p>
<p>Email: <input id="email" type="text" name="email"/></p>
<p>Password: <input id="password" type="text" name="password"/></p>
</fieldset>
<input id="addUser" type="submit" name="add" value="Add User" onclick="addRow()" />
</form>
<script src="script.js"></script>
This then launches the following code in my script.js code:
function addRow(){
var form = document.getElementById("userForm");
var req = new XMLHttpRequest();
// Add the form data to the ajax request
var queryString = "";
var fname = form.fname.value;
var lname = form.lname.value;
var email = form.email.value;
var password = form.password.value;
queryString += "fname=" + fname + "&";
queryString += "lname=" + lname + "&";
queryString += "email=" + email + "&";
queryString += "password=" + password;
req.open('GET', '/insert-user?' + queryString, true);
req.send();
console.log(req.status);
Which executes the server side code:
app.get('/add-user', function(req,res){
var context = {};
res.render('addUser', context);
});
app.get('/insert-user',function(req,res,next){
var context = {};
pool.query("INSERT INTO user (`fname`, `lname`, `email`, `password`) VALUES (?,?,?,?)",
[req.query.fname, req.query.lname, req.query.email, req.query.password],
function(err, result){
if(err){
next(err);
return;
}
context.results = "Inserted id " + result.insertId;
res.render('exerciseTable',context);
});
});
The record is not being inserted into the table. When I console.log(req.status) I see 0 in the console. The add-user page is the form that the user fills out and then the insert-user code is called but it does not seem to be working. In fact, the URL does not change from http://18.219.103.143:3000/add-user to http://18.219.103.143:3000/insert-user? when I submit. It just stays static. It seems like my app.get('/insert-user'... code isn't even being called. Does anyone know what I am missing?
I am getting this error in the console:
Try to put
<form id="userForm" onsubmit="return false;">
Otherwise the default action on your form will be called. As your button is a submit button and that your default action is not set so it defaults to the same page and returning nothing or true will reload your page.

HTML How to show an <iframe> when a button is pressed

Ive been using geolocation and HTML recently, i want to try to show an iframe when the submit button is pressed, i keep getting stuck on what to do.
<!DOCTYPE html>
<html>
<body>
<input type="text" id="text" />
<input type="button" id="btn" value="Submit" onClick="javascript: window.open('https://api.ipdata.co/' + document.getElementById('text').value);" />
</body>
</html>
Oh and here’s my iframe
The IPadress is the ipadress of a device i am testing this out on. I want to put this in where the “javascript: window.open” is
I'm not sure why You'd want to show an iframe with a JSON response...
var text = document.getElementById("text"),
btn = document.getElementById("btn"),
iframe = document.getElementById("iframe");
function text2iframe() {
iframe.src = "https://api.ipdata.co/" + text.value;
}
btn.addEventListener("click", text2iframe);
<input type="text" id="text" value="47.91.202.22"><br>
<input type="button" id="btn" value="Submit"><br>
<iframe id="iframe"></iframe>
When you can go for the JSON directly!
var text = document.getElementById("text"),
btn = document.getElementById("btn"),
pre = document.getElementById("pre");
function ipdata() {
var request = new XMLHttpRequest();
request.open('GET', "https://api.ipdata.co/" + text.value, true);
request.addEventListener("load", function() {
if (request.status >= 200 && request.status < 400) {
pre.textContent = request.responseText
var responseObj = JSON.parse(request.responseText);
console.log( responseObj.country_name )
console.dir( responseObj );
} else {
// error
}
});
request.addEventListener("error", function() {
// connection error
});
request.send();
}
btn.addEventListener("click", ipdata);
<input type="text" id="text" value="47.91.202.22"><br>
<input type="button" id="btn" value="Submit"><br>
<pre id="pre"></pre>

Validation from submitting in Apps Script

Please I need help. I have the same need of this post. I followed the instructions but I can't find my error. I'm frustratred.
When I submit with null fields, the script shows me a blank page.
When I submit with complete fields, the script shows me a blank page also and never upload the file.
This is my final code:
code.gs
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html');
}
function uploadFiles(form) {
try {
var dropbox = "NHD Papers";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var blob = form.myFile;
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + form.myName + ", Division: " + form.myDivision + ", School: " + form.mySchool + ", State: " + form.myState);
return "<h2>File uploaded successfully!</h2><p>Copy and paste the following URL into registration:<br /><br /><strong>" + file.getUrl() + '</strong></p>';
} catch (error) {
return error.toString();
}
}
form.html
<p>
<form id="myForm" onsubmit="validateForm();">
<h1>NHD Paper Upload</h1>
<label>Name</label>
<input type="text" name="myName" class="required" placeholder="Enter your full name..">
<label>Division</label>
<input type="text" name="myDivision" class="required" placeholder="(ex. Junior or Senior)">
<label>School</label>
<input type="text" name="mySchool" class="required" placeholder="Enter your school..">
<label>Affiliate</label>
<input type="text" name="myAffiliate" class="required" placeholder="Enter your affiliate..">
<label>Select file to upload. </label>
<input type="file" name="myFile">
<input type="submit" value="Submit File" >
<br />
</form>
</p>
<div id="output"></div>
<script>
function validateForm() {
var x=document.getElementsByClassName('required');
for(var i = 0; i <x.length; i++){
if (x[i].value == null || x[i].value == "")
{
alert("All fields must be filled out.");
return false;
}
this.value='Please be patient while your paper is uploading..';
var myFormObject = document.getElementById('myForm');
google.script.run.withSuccessHandler(fileUploaded)
.uploadFiles(myFormObject);
}
}
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
<style>
input { display:block; margin: 15px; }
p {margin-left:20px;}
</style>
Regards,
In the IFRAME mode HTML forms are allowed to submit, but if the form has no action attribute it will submit to a blank page.
The solution suggested by the official documentation is to add the following JavaScript code to prevent all form submitions on load:
<script>
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
</script>
You can also add a return false; or event.preventDefault() at the end of your validateForm() function.

form getting redirected to base_url when action is set to null in codeigniter view

I submit the below form its processing the code in the controller but after processing its redirecting to my base url. Also I haven't used any redirect in my controller function. why is it redirecting to my base_url when the action is null?
This is my form code
<form action="" class="form-horizontal contact-1" role="form" method="post" id="contactform">
<input type="hidden" name="operation" value="newquery">
<div class="form-group">
<div class="col-sm-6">
<input type="text" class="form-control" name="name" id="name" placeholder="Name">
</div>
<div class="col-sm-6">
<input type="text" class="form-control" name="email" id="email" placeholder="Email">
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input class="form-control" id="subject" type="text" name="subject" placeholder="Subject">
<textarea name="message" type="text" id="msg" class="form-control textarea" cols="30" rows="5" placeholder="Message"></textarea>
<button type="submit" id="contsub" class="btn btn-primary btn-block contact-1-button" data-loading-text="Sending" ><i class="fa fa-send"></i> Send Message</button>
</div>
</div>
</form>
and this is my ajax call
<script>
$(document).ready(function() {
$("#contsub").click(function() {
var name = $("#name").val();
var email = $("#email").val();
var subject = $("#subject").val();
var msg = $("#msg").val();
if (name == '' || email == '' || subject == '' || msg == '') {
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("contactform.php", {
name: name,
email: email,
subject: contact,
msg: msg
}, function(data) {
alert(data);
$('#form')[0].reset(); // To reset form fields
});
}
});
});
</script>
I am not able to figure out what the problem is?
1.If you set form action empty, form will be submitted to its current url.so look at your browser current url and I think it is same as your base_url.
2.If you click on the contsub button your javascript $("#contsub").click(function() will not execute perfectly because when you click this button it will submit the form too and will redirect to the action url.change your <button type="submit" to <button type="button" so it will not submit the form and your javascript will work.
<script>
$(document).ready(function() {
$("#contsub").click(function(e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
var subject = $("#subject").val();
var msg = $("#msg").val();
if (name == '' || email == '' || subject == '' || msg == '') {
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("contactform.php", {
name: name,
email: email,
subject: contact,
msg: msg
}, function(data) {
alert(data);
$('#form')[0].reset(); // To reset form fields
});
}
});
});
</script>
pressing the button causes the form to submit, redirecting you to your current location. adding the e.preventDefault(); will stop this from happening.