Uploaidng file to parse through html form - javascript

I am trying to let users fill out a form and upload a photo. I want all of this information to be stored in my parse database. I got the form to work fine, now I need to include the file upload. I am also creating this with express.js.
Here is my .ejs file with the form
<div id="result"></div>
<form action="/" id="filter-form" >
<P>
Upload your filter!
<input type="file" id="uploadfilter" required>
<img id="yourfilter" src="#" >
</P>
<p>
<input type="text" name="name" placeholder="Name" id="username" required>
</p>
<p>
<input type="email" name="email" placeholder="Email" id="email" required>
</p>
<p>
<textarea name="comments" id="comments" placeholder ="Additional comments" required></textarea>
</p>
<p>
<input type="checkbox" style="position: relative; left:0; visibility: visible;" required > I agree that this is my own work and does not contain logos or trademarks and I have read the Submission Guidelines
</p>
<p>
<input type="checkbox" style="position: relative; left:0; visibility: visible;" required > I agree to the Privacy Policy and Submission Agreement of the Smart Filters submission tool.
</p>
<p>
<input type="submit" value="Submit Filter">
</p>
</form>
Here's the javascript also in the .ejs file.
<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#yourfilter').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#uploadfilter").change(function(){
readURL(this);
});
jQuery(function($){
$('#filter-form').submit(function(event) {
event.preventDefault();
// Get some values from elements on the page:
var $form = $(this);
var name = $form.find("#username").val();
var email = $form.find("#email").val();
var comments = $form.find("#comments").val();
var url = $form.attr("action");
var data = {
"name": name,
"email": email,
"comments": comments,
"filterfile": parseFile,
};
var posting = $.post(url, data);
posting.done(function (data) {
//var data = JSON.parse(data);
var content = "<b>"+data.message+"</b>";
$("#result").empty().append(content);
});
posting.fail(function (data) {
//var data = JSON.parse(data);
var content = data.message;
$("#result").empty().append(content);
});
});
});
Here is the app.js code within the app.post.
app.post('/*', function (req, res) {
console.log('I AM HERE!');
console.log("PARAMS:")
console.log(req.params);
console.log("BODY:");
console.log(req.body);
var data = req.body;
if ((tryParseJSON(data) != false) || (!data.hasOwnProperty('name')) || (!data.hasOwnProperty('email')) || (!data.hasOwnProperty('comments'))) {
return res.json({"message" : "Invalid parameters!", "status" : 200});
}
var newFilter = Parse.Object.extend("FilterSubmit");
var newfilter = new newFilter();
newfilter.set("name", data.name);
newfilter.set("email", data.email);
newfilter.set("comments", data.comments);
newfilter.set("filterfile", data.parseFile);
var FilterSave = newfilter.save();
return Parse.Promise.when([FilterSave]).then(function (FilterSubmit) {
console.log("Filter Saved!");
return res.json({"status" : 400, "message" : "Filter Saved! Thank you "+data.name+"!"});
}, function (error) {
console.log("Save error!");
console.log(error);
return res.json({"message" : "Save error!", "status" : 200});
});
});
function tryParseJSON (jsonString){
try {
var o = JSON.parse(jsonString);
// Handle non-exception-throwing cases:
// Neither JSON.parse(false) or JSON.parse(1234) throw errors, hence the type-checking,
// but... JSON.parse(null) returns 'null', and typeof null === "object",
// so we must check for that, too.
if (o && typeof o === "object" && o !== null) {
return o;
}
}
catch (e) { }
return false; };
This form works perfectly when it's just the text input. It stopped submitting when I included the file input (Probably because I havn't implemented it fully yet). I now just need to get file uploading working with it as well. I'm not sure how to connect them or where to start. Any help would be much appreciated :)

Your form can not send files or images in the way you do:
Your form requires the attribute 'enctype' to be set.
<form action="/" id="filter-form" method="post" enctype="multipart/form-data">.

Related

Validate form using Flask, Ajax and jQuery to check data from back-end before submitting the form

I have recently started learning Python and jQuery. I am doing a small exercise for validating the form from back-end. I do not want to submit the form if the validation fails.
Here, I want to print the message, user already exists if user record is present in the backend. The code I wrote for validation works but by form is always getting submitted. Much appreciate guidance from this forum on how to handle this form submission.
Here's a snippet of my code:
HTML:
<form action="/register" method="post">
<div class="form-group">
<input autocomplete="off" autofocus class="form-control" name="username" id="user" placeholder="Username*" type="text" required>
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password*" type="password" required>
</div>
$('form').on('submit', function(e) {
let user = document.querySelector("#user").value;
$.get('/validate?q=' + user, function(users) {
let text = '';
if (users.length != 0) {
document.querySelector("#error").innerHTML = "Username already exists";
return false;
}
});
});
application.py
#app.route("/validate")
def validate():
user = request.args.get("q")
row = db.execute("SELECT username FROM users WHERE username = ?", user)
print(row)
return jsonify(row)
You need to validate that outside your "get" function, preferably using a variable.
$('form').on('submit', function(e) {
var chkUser = 0;
let user = document.querySelector("#user").value;
$.get('/validate?q=' + user, function(users) {
let text = '';
chkUser = users.length;
if (users.length != 0) {
document.querySelector("#error").innerHTML = "Username already exists";
return false;
}
});
if (chkUser > 0)
return false;
});
I haven't tested this code. Also you should mention how are you subtmitting your form. The easiest way is just to have an <input type='submit'> element.

How can I fix this html code to not display sensitive information to the user?

I am creating a html form to capture applicants' inputs and then send a POST request to an api with the data. I do not know how to go about hiding three specific values from something like 'View Page Source' or console.log(). I need to store the values securely and still be able to use them in the HTML form.
I know I will probably have to rewrite my solution but I do not know the best way to go about this. Is there a way to store the values of the api keys in a database?
Here are the three values in question:
<body>
<main role="main" class="container-fluid">
<form id="form1" name="form1" onsubmit="beforeSubmit(); return false;">
<div class="aspNetHidden">
<input type="hidden" name="merchantID" id="merchantID" />
<input type="hidden" name="login" id="login" />
<input type="hidden" name="password" id="password" />
</div>
<script type="text/javascript">
var merID = "1234567";//need to store these values somewhere else!!!!!!!
var log = "API123";
var pass = "1234567";
//even if these values are moved they would be viewable by something like console.log(obj)
document.getElementById("merchantID").value = merID;
document.getElementById("login").value = log;
document.getElementById("password").value = pass;
</script>
And here is where I make the API call:
<script type="text/javascript">
beforeSubmit = function () {
//======================================================================================================
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
//======================================================================================================
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
xhttp.open("POST", "https://someurl.com/enroll.svc/JSON/CreateMerchant", true);
xhttp.setRequestHeader("Content-type", "application/json");
var obj = JSON.stringify($('#form1').serializeObject());
console.log(obj);//security concern! all someone would have to do is cntrl+shift+j when the form is submitted
//this log command would display the entire JSON object including the merchant ID, Login and Password
xhttp.send(obj);
} //=====================================================================================================
</script>
I am very new to this. The code does what it is supposed to aside from sensitive information easily being viewed by inspecting the page source. Any suggestions of for a better/more secure way would be appreciated.
Its shouldn't be too hard put your api in a php variable then insert your variable into your database table.
Then use select to take it out when you need it also php is not readable from view source.
If you don't know how to input and select from databases there are plenty of tutorials out there.
Your code is a horrid mix of unnecessary serialisation you are not using and a weird event handling of beforesubmit.
This is how a generic jQuery ajax looks like
$(function() { // page load
$("#form1").on("submit", function(e) {
e.preventDefault(); // cancel the submit
$.post("https://someurl.com/enroll.svc/JSON/CreateMerchant", // url
$(this).serialize(), // serialising the form
function(result) {
console.log(result); // do something with the result of the submission
});
});
});
<form id="form1" name="form1">
<div class="aspNetHidden">
<input type="hidden" name="merchantID" id="merchantID" />
<input type="hidden" name="login" id="login" />
<input type="hidden" name="password" id="password" />
</div>
</form>

How to get response from server without refreshing and using JQuery/AJAX?

Is there any "right" way to get response from server without using JQuery/AJAX and of course without refreshing page?
server.js:
var http = require('http');
var url = require('url');
var qs = require('querystring');
var static = require('node-static');
var file = new static.Server('.');
http.createServer(function(req, res) {
if (req.method == 'POST' && req.url == "/reglog.html") {
var body = '';
req.on('data', function (data) {
body += data;
// Destroy connection if data is too large for it
if (body.length > 1e6) {
req.connection.destroy();
}
});
req.on('end', function () {
//it's time to parse body
var post = qs.parse(body);
//send response everything is ok
if (post.email.length > 0 && post.pswrd.length > 0 && post.login.length > 0) {
//also console.log to see what was sent from client
console.log(post);
res.end('Everything is good!');
} else {
// ...or not ok
res.end('Everything is bad!');
}
});
} else if (method = 'GET') {
file.serve(req, res);
}
}).listen(8080);
So, there's reglog.js:
var xhr = new XMLHttpRequest();
var uemail = document.getElementById("email"); //HTML element for user's email
var ulogin = document.getElementById("login"); //HTML element for user's login
var upswrd = document.getElementById("pswrd"); //HTML element for user's password
var message = document.getElementById("message"); //HTML element for response from server
function hide(tout) {
if (tout === undefined) tout = 2500;
return setTimeout(function() {
message.innerHTML = "";
}, tout);
}
document.getElementById("btn").onclick = (function createUser(){
var email = uemail.value;
var login = ulogin.value;
var pswrd = upswrd.value;
//XHR part starts//
var body = "email="+email+"&login="+login+"&pswrd="+pswrd;
//I know that email, login and pswrd should be with encodeURIComponent, but in my case it's not a problem and using it won't solve my main problem
xhr.open("POST","/reglog.html",true);
xhr.send(body);
message.style.color = "black";
xhr.onload = function() {
message.innerHTML = xhr.responseText;
}
//XHR part ends//
});
document.getElementById("lbtn").onclick = (function logMenu(){
document.getElementById('logform').style.display = "block";
document.getElementById('regform').style.display = "none";
});
document.getElementById("rbtn").onclick = (function regMenu(){
document.getElementById('regform').style.display = "block";
document.getElementById('logform').style.display = "none";
});
And reglog.html:
<HTML>
<HEAD>
<meta charset="utf-8">
<style>
.button{
position: absolute;
top: 45%;
bottom: 55%;
left: 15%;
}
</style>
</HEAD>
<BODY>
<form id="regform" action="/reglog.html" style="display:block;">
<center><p>Register</p>
E-mail: <input type="email" id="email" name="email" autocomplete="off"><br>
Login: <input type="text" id="login" name="login" required autocomplete="off"><br>
Password: <input type="password" id="pswrd" name="password" required autocomplete="off"><br>
<span id="message"></span><br>
<div class="button">
<input type="submit" id="btn" value="Register"/><br><br>
<input type="button" id="lbtn" value="Back to log in"/></div>
</center>
</form>
<form id="logform" style="display:none;">
<center><p>Log in</p>
Login: <input type="text" id="login2" autocomplete="off"/><br>
Password: <input type="password" id="pswrd2" autocomplete="off"/><br>
<span id="message2"></span><br>
<div class="button">
<input type="button" id="btn2" value="Log in"/><br><br>
<input type="button" id="rbtn" value="Registration"/></div>
</center>
</form>
<script async src="/reglog.js"></script>
</BODY>
</HTML>
As you can see I can get response on client side in
<span id="message"></span>
But I can see it for ~0.5 sec and after that there would be page refreshing. And that is not the best way to see results. My question: is it possible to see this response in "span" for more than ~0.5 sec? I mean, maybe refresh page and then show this response? I don't get how to do it because there is always response coming (for 0.5 sec) and then page refreshing.
Also I don't know if it's possible to do that without AJAX/JQuery.
I would glad to get any help because it's the question that torments me for two days, and I didn't find any reasonable answer via google.
Your code looks fine you just need to prevent the default action of the form submitting the traditional (page reload) way when you click the submit button.
document.getElementById("btn").onclick = (function createUser(e){
e.preventDefault();
// rest of function
});

javascript errors in html

First of all , I have no idea of ​​javascript, I got this code from a tutorial.
I am developing a website in ruby , and to do that I need to make a form of payment. I'm currently using the API Mango.
I have the following code:
<form id="form" action="/pay" method="POST">
<fieldset>
<div>
<label for="ccv">Código de seguridad</label>
<input type="text" id="ccv" required>
</div>
</fieldset>
<input type="submit" value="Pagar ahora!">
</form>
<div id="errores">
</div>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://js.getmango.com/v1/mango.js"></script>
<script>
var PUBLIC_API_KEY = 'public_test_u3wbj4jctik1k2u8qtnajhvn82h590ue';
Mango.setPublicKey(PUBLIC_API_KEY);
var submission = false;
var $form = $('#form');
$form.on('submit', function(event) {
if (submission) {
return false;
}
submission = true;
var cardInfo = {
'ccv': $('#ccv').val()
};
Mango.token.create(cardInfo, handleResponse);
return false;
});
function handleResponse(err, data) {
submission = false;
//Here I put an error message that's displayed in html
if (err) {
...
}
var token = data.uid;
var $hidden = $('<input type="hidden" name="token">');
$hidden.val(token);
$form.append($hidden);
$form[0].submit();
}
</script>
How I can capture that error and show it in html ?
function handleResponse(err, data) {
submission = false;
//Here I put an error message that's displayed in html
if (err) {
...
}
var token = data.uid;
var $hidden = $('<input type="hidden" name="token">');
$hidden.val(token);
$form.append($hidden);
$form[0].submit();
}
this function - is an event handler for Response,obviously. First param is error and if this will be passed your if(err) code block will be executed.
As i see - you use JQuery, so in this place you can Insert some code, which will show error into your form.
For example $('form').append('<div class="error">Some error occurs</div>');
You could try something like
$('body').append($errorp);

Contact form variables are not passing into javascript from section tag

Contact form variables are not passing into javascript. basically javascript fail on validation. On debug, I am getting "undefined is not a function." I have several seperators on this page. If i put identical code inside a seperate page like "contact.html" variables pass into javascript.
My understanding is that HTML tag id="contact-form" for some reason does not pass into the function.
Java Script
function code_contactvalidation() {
// Add form.special data (required for validation)
$('form.special input, form.special textarea').each(function() {
this.data = {};
this.data.self = $(this);
var val = this.data.self.val();
this.data.label = (val && val.length) ? val : null;
this.data.required = this.data.self.attr('aria-required') == 'true';
});
// Special form focus & blur
$('form.special input, form.special textarea').focus(function() {
with (this.data) {
console.log('focusing');
if ( label && self.val() == label) self.val('');
else return;
}
}).blur(function() {
with (this.data) {
if ( label && self.val().length == 0 ) self.val(label)
else return;
}
});
// initialize captcha
var randomcaptcha = function() {
var random_num1=Math.round((Math.random()*10));
var random_num2=Math.round((Math.random()*10));
document.getElementById('num1').innerHTML=random_num1;
document.getElementById('num2').innerHTML=random_num2;
var n3 = parseInt(random_num1) * parseInt(random_num2);
$('#captcharesult').attr('value', n3);
$('#buttonsubmit').attr('value','Submit');
};
randomcaptcha();
//initialize vars for contact form
var sending = false,
sent_message = false;
$('#contact-form').each(function() {
var _this = this;
this.data = {};
this.data.self = $(this);
this.data.fields = {};
this.data.labels = {};
this.data.notification = this.data.self.find('.notification');
_.each(['name','email','subject'], function(name) {
_this.data.fields[name] = _this.data.self.find(_.sprintf('input[name=%s]', name));
_this.data.labels[name] = _this.data.fields[name].val();
});
}).validate({
errorPlacement: function() {},
highlight: function(element) { $(element).addClass('invalid'); },
unhighlight: function(element) { $(element).removeClass('invalid'); },
submitHandler: function(form) {
if (sending) return false;
if ( sent_message ) { alert('Your message has been sent, Thanks!'); return false; }
var field, valid = true;
with (form.data) {
_.each(fields, function(field, name) {
if ( $.trim(field.val()) == labels[name] ) { valid = false; field.addClass('invalid'); } else { field.removeClass('invalid'); }
});
}
if (valid) {
sending = true;
$('#ajax-loader').show();
form.data.self.ajaxSubmit({
error: function(errorres) {
$('#ajax-loader').hide();
randomcaptcha();
form.data.notification.removeClass('sucess').addClass('error').find('span:first-child').html('Unable to send message (Unknown server error)');
form.data.notification.animate({opacity: 100}).fadeIn(500);
},
success: function(res) {
sending = false;
$('#ajax-loader').hide();
if (res == 'success') {
sent_message = true;
form.data.notification.removeClass('error').addClass('success').find('span:first-child').html('Your message has been sent!');
form.data.notification.animate({opacity: 100}).fadeIn(500);
$('#formName').val("");
$('#formEmail').val("");
$('#formSubject').val("");
$('#formMessage').val("");
$('#formcheck').val("");
} else if (res == 'captchaerror') {
randomcaptcha();
form.data.notification.removeClass('sucess').addClass('error').find('span:first-child').html('Captcha Error');
form.data.notification.animate({opacity: 100}).fadeIn(500);
} else {
randomcaptcha();
form.data.notification.removeClass('sucess').addClass('error').find('span:first-child').html('Unable to send message (Unknown server error)');
form.data.notification.animate({opacity: 100}).fadeIn(500);
}
}
});
}
return false;
}
});
}
HTML
<section id="contact">
<div class="container">
<div class="row text-center">
<div id="principal" data-align="left">
<div class="form_group_contact">
<script type="text/javascript" src="js/jquery.validate.pack.js"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>
<form class="contactForm special validate" id="contact-form" action="sendmsg.php" method="post">
<p><input id="formName" name="name" type="text" value="Name" class="required" /></p>
<p><input id="formEmail" name="email" type="text" value="Email" class="required email" /></p>
<p><input id="formSubject" name="subject" class="last required" type="text" value="Subject" /></p>
<p><textarea id="formMessage" name="message" class="required margin20" rows="4" cols="83"></textarea></p>
<div class="form_captcha margin20">
<p>Captcha Recognition (<span id="num1"></span> * <span id="num2"></span>) =
<input type="hidden" id="captcharesult" name="captcha_result" value=""/>
<input type="text" class="required number" maxlength="3" size="3" id="formcheck" name="captcha" value=""/>
</p>
</div>
<p class="notification" style="display: none;"><span></span> <span class="close" data-action="dismiss"></span></p>
<p><input type="submit" value="" class="margin20" id="buttonsubmit" /><img id="ajax-loader" alt="" src="./images/ajax-loader.gif" /></p>
</form>
</div>
</div>
</div>
</div>
</section>
if ( label && self.val().length == 0 ) self.val(label)
There needs to be a semicolumn (;) to end that line ;)
Also, you call "each" on the contact-form which makes me think you expect more than one contact-form. You will need to set the identifier as "class" rather than "id" in the HTML and use "." in the jQuery selector rather than "#".
Now you got those little things fixed, please try it out in Firefox. Google is very vague with javascript errors, Firefox will give you a better error message. Please share it with us so I can edit this post with a final solution.

Categories

Resources