Hi everyone
So there is my code :
HTML :
<html>
<body>
<form enctype="multipart/form-data" method="post" name="image">
<input onchange="test();" type="file" accept="image/*" capture="camera" name="file" id="camera">
<input id="go" type="submit" value="Stash the file!" style="display: none;" />
</form>
<div id="output"></div>
</body>
<script src="./script.js"></script>
</html>
JS :
var form = document.forms.namedItem("image");
form.addEventListener('submit', function(ev) {
var
oOutput = document.getElementById("output"),
oData = new FormData(document.forms.namedItem("image"));
oData.append("CustomField", "This is some extra data");
var oReq = new XMLHttpRequest();
oReq.open("POST", "./upload.php", true);
oReq.onload = function(oEvent) {
if (oReq.status == 200) {
oOutput.innerHTML = "Uploaded!";
} else {
oOutput.innerHTML = "Error " + oReq.status + " occurred uploading your file.<br \/>";
}
};
oReq.send(oData);
ev.preventDefault();
}, false);
function test() {
document.getElementById("go").click()
}
My problem is it's totaly functional but litlle... dirty.
I try to submit the form with JS document.forms.namedItem("image").submit(); but the EventListener dont catch it.
And i dont want to add JQuery to my project just for that (for those who have an answer who use JQuery).
The solution is certainly right before my eyes but i dont find an other way to do it.
Thanks all in advance.
I think you can simplify like this :
function pleaseUpload() {
console.log('upload fonction ...');
}
<html>
<body>
<form enctype="multipart/form-data" method="post" name="image">
<input onchange="pleaseUpload();" type="file" accept="image/*" capture="camera" name="file" id="camera">
</form>
<div id="output"></div>
</body>
<script src="./temp.js"></script>
</html>
Your confusing form.submit() with submit button click.
There is no need for a hidden submit button.
var output = document.getElementById("output");
var form = document.querySelector("form[name='image']");
form.addEventListener('submit', function(ev) {
ev.preventDefault();
var oOutput = document.getElementById("output")
var oData = new FormData(document.forms.namedItem("image"));
oData.append("CustomField", "This is some extra data");
var oReq = new XMLHttpRequest();
oReq.open("POST", "./upload.php", true);
oReq.onload = function(oEvent) {
if (oReq.status == 200) {
oOutput.innerHTML = "Uploaded!";
} else {
oOutput.innerHTML = "Error " + oReq.status + " occurred uploading your file.<br \/>";
}
};
oReq.send(oData);
}, false);
function test() {
form.submit();
output.textContent = "form submitted!";
}
<form enctype="multipart/form-data" method="post" name="image">
<input onchange="test();" type="file" accept="image/*" capture="camera" name="file" id="camera">
</form>
<div id="output"></div>
Related
in my code I have 2 button. first of them is file-input and another send to server that file. How can I do that with only 1 button in my site?
her is my php code:
const realFileBtn = document.getElementById("real-file");
const customBtn = document.getElementById("custom-button");
customBtn.addEventListener("click", function() {
realFileBtn.click();
});
<form method="POST" action="upload.php" enctype="multipart/form-data">
<input type="file" name="file" id="real-file" hidden="hidden">
<input type="submit" value="Göndər" id="custom-button">
</form>
<script src="./script.js"></script>
<link rel="stylesheet" href="./style.css">
<?php
$files = scandir("uploader");
?>
here you go.
const fileInput = document.getElementById('file-input')
const button = document.getElementById('custom-button')
fileInput.onchange = (e) => {
console.log(e)
document.getElementById('my-form').submit()
};
button.addEventListener('click', (e) => {
e.preventDefault();
fileInput.click()
});
<form method="POST" action="upload.php" id="my-form" enctype="multipart/form-data">
<input type="file" name="file" id="file-input" hidden="hidden">
<button value="Göndər" id="custom-button">Gönder</button>
</form>
You can call form submit when there is file changed by
document.getElementById("real-file").onchange = function() {
document.getElementById("form").submit();
};
I have a Login form that working fine. I tried to extend login action for adding extra features.
First I prevent the form to be submit when the submit button is clicked, I perform ajax request and finally if everything is correct I submit the form, but my form is not submitted until the submit button is clicked twice. What am I doing wrong?
HTML Part:
<div id="loginFormDiv">
<form class="form-horizontal" method="POST" action="index.php">
<input type="hidden" name="module" value="Users">
<input type="hidden" name="action" value="Login">
<div class="group"><input id="username" type="text" name="username" ><span class="bar"></span><label>Username</label></div>
<div class="group"><input id="password" type="password" name="password" ><span class="bar"></span><label>Password</label></div>
<div class="group"><button type="submit" class="button buttonBlue">Sign in</button></div>
</form>
</div>
JS Part:
jQuery.Class("ParsSecureLogin_Js", {}, {
checkLogin: function () {
var thisInstance = this;
var checkUserLogin = function (e) {
e.preventDefault();
var username = $('#username').val();
var user_pass = $('#password').val();
var theForm = $(this);
var url = 'index.php?module=ParsSecureLogin&parent=Settings&action=CheckLogin&_user=' + username + '&_pss=' + user_pass;
jQuery.ajax({
url: url
}).done(function (data) {
if (data == '' || data == 'undefined') {
alert('Unknown error. Please contact admin to check!');
return false;
} else {
theForm.unbind('submit').submit();
return true;
}
});
}
jQuery('#loginFormDiv').on("submit", checkUserLogin);
},
registerEvents: function () {
var thisInstance = this;
thisInstance.checkLogin();
}
});
jQuery(document).ready(function () {
var ParsSecureLogin = new ParsSecureLogin_Js();
ParsSecureLogin.registerEvents();
});
It is because #loginFormDiv is a <div> not a <form> change the selector to:
jQuery('#loginFormDiv form').on("submit", checkUserLogin);
In my code I want to accept only image file.otherwise it will not accept and will give alert that its not image file.
I have done below code in jsfiddle:--
jsfiddle link
but the problem is it..It is not giving any message.what am I doing wrong?
https://jsfiddle.net/weufx7dy/2/
You forgot to add id on file element
<input type="file" id="file" name="fileUpload" size="50" />
You had used
var image =document.getElementById("file").value;
but forgot to give id to file control so give that
<input type="file" name="fileUpload" id="file" size="50" />
and try following code in w3schools tryit browser and use onClick event on submit button instead of onSubmit
<!DOCTYPE html>
<html>
<body>
<div align="center">
<form:form modelAttribute="profilePic" method="POST"enctype="multipart/form-data" action="/SpringMvc/addImage">
<input type="file" name="fileUpload" id="file" size="50" />
<input type="submit" value="Add Picture" onClick="Validate();"/>
</form:form>
</div>
<script>
function Validate(){
var image =document.getElementById("file").value;
if(image!=''){
var checkimg = image.toLowerCase();
if (!checkimg.match(/(\.jpg|\.png|\.JPG|\.PNG|\.gif|\.GIF|\.jpeg|\.JPEG)$/)){
alert("Please enter Image File Extensions .jpg,.png,.jpeg,.gif");
document.getElementById("file").focus();
return false;
}
}
return true;
}
</script>
</body>
</html>
Use this :
userfile.addEventListener('change', checkFileimg, false);
function checkFileimg(e) {
var file_list = e.target.files;
for (var i = 0, file; file = file_list[i]; i++) {
var sFileName = file.name;
var sFileExtension = sFileName.split('.')[sFileName.split('.').length - 1].toLowerCase();
var iFileSize = file.size;
var iConvert = (file.size / 10485760).toFixed(2);
if (!(sFileExtension === "jpg")) {
txt = "File type : " + sFileExtension + "\n\n";
txt += "Please make sure your file is in jpg format.\n\n";
alert(txt);
document.getElementById('userfile').value='';
}
}
}
I tried pass the content of an entire div in form action url using JS. but on servlet side when i try to get this request param as String, i am getting it as [object Object].
This is my form and JS
<div id="paraContent">
Content in jsp
</div>
<form id="form1" action="/sendEmail.email.send.html" method="post">
<input type="hidden" id="contentValue1" name="contentValue1"/>
<input type="button" value="place order" onClick="formSubmit()"/>
</form>
<script type="text/javascript">
var divContent = $('#paraContent');
$("#contentValue").val(divContent);
function formSubmit() {
var form = document.getElementById("form1");
var str = "/sendEmail.email.send.html?contentValue=" + $('#paraContent');
form.action = "/sendEmail.email.send.html?contentValue=" + $('#paraContent');
form.submit();
}
</script>
You could copy the div's content into a div when the form is subbmitted.
<form id = "form1" action="/sendEmail.email.send.html" method="post">
<input type="hidden" id="contentValue1" name="contentValue1"/>
<c:Set var="contVal" value="ddd"/>
<input type="button" value="place order" onClick="formSubmit()"/>
</form>
<script type="text/javascript">
function formSubmit() {
$("#contentValue1").val($("#paraContent").text());
var form = document.getElementById("form1");
var str = "/sendEmail.email.send.html?contentValue=" + $(paraContent);
form.action = "/sendEmail.email.send.html?contentValue=" + $(paraContent);
form.submit();
}
</script>
try by changing the
$(paraContent) to $("#paraContent"); and also
$("contentValue").val(divContent); to $("#contentValue").val(divContent);
Well you can use ajax post in order to send data from div to your servlet
<div id="paraContent">
Content in jsp
</div>
<script>
$(document).ready(function (){
var data=$("#paraContent").text();
$.ajax({
url: "YOUR SERVLET",
type: "POST",
data: { "data": data},
success: function(data) {
console.log(data);
}
});
});
</script>
In your servlet
String datafromdiv=request.getParameter("data");
Try this instead on a button click function .....
this same code was working yesterday, iframe[0].contentWindow.document.body.innerHTML has value "success".
But, today iframe[0].contentWindow.document.body is "". I cannot find innerHTML.
Same is result of iframe[0].contentDocument.body.
html
<form id="formid" method="post" action="file/upload" enctype="multipart/form-data" target="frame">
<input id="" type="file" name="file" />
</form>
<iframe id="frame" name="frame" width="0px" height="0px" frameborder="0"></iframe>
js
var iframe = $('#frame');
document.getElementById("formid").submit();
$("#frame").ready(function(){
$("#frame").load(function () {
data = iframe[0].contentWindow.document.body.innerHTML;
if(data == "success"){
successFunction(); // calling function if success
}
});
});
Using different path to iframe innerHtml worked:
JS:
function fileUpload(form, action_url) {
var iframe = document.createElement("iframe");
iframe.setAttribute("id", "frame");
iframe.setAttribute("name", "frame");
iframe.setAttribute("width", "0");
iframe.setAttribute("height", "0");
iframe.setAttribute("frameborder", "0");
form.parentNode.appendChild(iframe);
iframeId = document.getElementById("frame");
var eventHandler = function () {
if (iframeId.detachEvent) iframeId.detachEvent("onload", eventHandler);
else iframeId.removeEventListener("load", eventHandler, false);
if (iframeId.contentDocument) {
content = iframeId.contentDocument.body.innerHTML;
} else if (iframeId.contentWindow) {
content = iframeId.contentWindow.document.body.innerHTML;
} else if (iframeId.document) {
content = iframeId.document.body.innerHTML;
}
setTimeout('iframeId.parentNode.removeChild(iframeId)', 200);
}
if (iframeId.addEventListener) iframeId.addEventListener("load", eventHandler, true);
if (iframeId.attachEvent) iframeId.attachEvent("onload", eventHandler);
form.setAttribute("target", "frame");
form.setAttribute("action", action_url);
form.setAttribute("method", "post");
form.submit();
}
Html:
<form>
<input type="file" name="file" /></br>
<input type="button" value="upload" onClick="fileUpload(this.form,'url'); return false;" >
</form>