jQuery iframe file upload - javascript

Im building a file upload with jQuery, but Im getting a jQuery error trying to set the attributes of the form:
$(document).ready(function () {
$("#formsubmit").click(function () {
var iframe = $('<iframe name="postframe" id="postframe" class="hidden" src="about:none" />');
$('div#iframe').append(iframe);
$('#theuploadform').attr("action", "/ajax/user.asmx/Upload")
$('#theuploadform').attr("method", "post")
$('#theuploadform').attr("userfile", $('#userfile').val())
$('#theuploadform').attr("enctype", "multipart/form-data")
$('#theuploadform').attr("encoding", "multipart/form-data")
$('#theuploadform').attr("target", "postframe")
$('#theuploadform').submit();
//need to get contents of the iframe
$("#postframe").load(
function () {
iframeContents = $("iframe")[0].contentDocument.body.innerHTML;
$("div#textarea").html(iframeContents);
}
);
}
);
<div id="uploadform">
<form id="theuploadform" action="">
<input id="userfile" name="userfile" size="50" type="file" />
<input id="formsubmit" type="submit" value="Send File" />
</form>
</div>
<div id="iframe" style="width: 0px; height: 0px; display: none;">
</div>
<div id="textarea">
</div>

I found the solution. This code works:
<script type="text/javascript">
$(document).ready(function () {
$("#formsubmit").click(function () {
var iframe = $('<iframe name="postiframe" id="postiframe" style="display: none"></iframe>');
$("body").append(iframe);
var form = $('#theuploadform');
form.attr("action", "/upload.aspx");
form.attr("method", "post");
form.attr("encoding", "multipart/form-data");
form.attr("enctype", "multipart/form-data");
form.attr("target", "postiframe");
form.attr("file", $('#userfile').val());
form.submit();
$("#postiframe").load(function () {
iframeContents = this.contentWindow.document.body.innerHTML;
$("#textarea").html(iframeContents);
});
return false;
});
});
</script>
<form id="theuploadform">
<input id="userfile" name="userfile" size="50" type="file" />
<input id="formsubmit" type="submit" value="Send File" />
</form>
<div id="textarea">
</div>

It's not an official plugin, however here's an example on how you could wrap the form's submitting logic into a plugin.
Example:
<form method="post" enctype="multipart/form-data">
<input name="file" type="file" />
<input type="text" name="test" />
<button type="submit">Submit</button>
</form>
<script>
$('form').submit(function (e) {
//prevent default submit
e.preventDefault();
//submit through frame
$(this).frameSubmit({
done: function (form, frame, options) {
console.log('done!');
},
fail: function (form, frame, options) {
console.log('fail!');
},
always: function (form, frame, options) {
console.log('always!');
}
//custom hasError implementation if needed
//by default if the frame's body HTML contains the text "unexpected error" or "server error"
//it is treated as an error
/*,hasError: function (frame) {
return false;
}*/
});
});
</script>
PLUGIN
!function ($, doc) {
var _frameCount = 0,
_callbackOptions = ['done', 'fail', 'always'],
_hasFailed = function (frame) {
var frameHtml = $(frame).contents().find('body').html();
return /(server|unexpected)\s+error/i.test(frameHtml);
},
_createFrame = function () {
return $('<iframe>').prop('name', 'jq-frame-submit-' + _frameCount++).hide().appendTo(doc.body);
};
$.fn.extend({
frameSubmit: function (options) {
return this.each(function () {
var deferred = $.Deferred(),
form = this,
initialTarget = form.target,
hasTarget = form.hasAttribute('target'),
hasFailed = options.hasFailed || _hasFailed,
//The initial frame load will fire a load event so we need to
//wait until it fires and then submit the form in order to monitor
//the form's submission state.
$frame = _createFrame().one('load', function () {
$frame.one('load', function () {
deferred[hasFailed(this) ? 'reject' : 'resolve'](form, this, options);
$frame.remove();
});
form.submit();
//restore initial target attribute's value
if (hasTarget) form.target = initialTarget;
else form.removeAttribute('target');
});
//attach handlers to the deferred
$.each(_callbackOptions, function (i, optName) {
options[optName] && deferred[optName](options[optName]);
});
//make sure the form gets posted the to iframe
form.target = $frame.prop('name');
});
}
});
}(jQuery, document);

Your form target should be the same as iframe name, for example:
<form target="frame"
action="http://posttestserver.com/post.php?dir=example"
method="post"
enctype="multipart/form-data">
<input name="file" type="file"/>
</form>
<iframe name="frame"></iframe>
And after this you can attach event to input button to listen for 'change'.
Furthemore you can get progress from server using jsonp and all of this will work in any browser event IE3+. Something like this:
$('input').change(function () {
$('form').submit();
});
$.getJSON('/echo/jsonp/?callback=?', function(e, progress) {
console.log(progress);
});

This is a good plugin to upload files using ajax
http://jquery.malsup.com/form/#file-upload

You know instead of fetching the same item multiple times, why not just reuse it:
var form = $('#theuploadform');
form.attr("action", "/ajax/user.asmx/Upload");
form.attr("method", "post");
// and so on
What kind of error are you having? can you post it?
UPDATE
Since you cannot set the attribute yourself here is a work around:
Put the form in an iframe, and attach an onchange event to the input button.
when the user select a file, you trigger the necessary code to upload the file (submit), then the parent window can close the iframe.

Related

Firebase not creating users [duplicate]

How would I go about preventing the page from refreshing when pressing the send button without any data in the fields?
The validation is setup working fine, all fields go red but then the page is immediately refreshed. My knowledge of JS is relatively basic.
In particular I think the processForm() function at the bottom is 'bad'.
HTML
<form id="prospects_form" method="post">
<input id="form_name" tabindex="1" class="boxsize" type="text" name="name" placeholder="Full name*" maxlength="80" value="" />
<input id="form_email" tabindex="2" class="boxsize" type="text" name="email" placeholder="Email*" maxlength="100" value="" />
<input id="form_subject" class="boxsize" type="text" name="subject" placeholder="Subject*" maxlength="50" value="FORM: Row for OUBC" />
<textarea id="form_message" class="boxsize" name="message" placeholder="Message*" tabindex="3" rows="6" cols="5" maxlength="500"></textarea>
<button id="form_send" tabindex="5" class="btn" type="submit" onclick="return processForm()">Send</button>
<div id="form_validation">
<span class="form_captcha_code"></span>
<input id="form_captcha" class="boxsize" type="text" name="form_captcha" placeholder="Enter code" tabindex="4" value="" />
</div>
<div class="clearfix"></div>
</form>
JS
$(document).ready(function() {
// Add active class to inputs
$("#prospects_form .boxsize").focus(function() { $(this).addClass("hasText"); });
$("#form_validation .boxsize").focus(function() { $(this).parent().addClass("hasText"); });
// Remove active class from inputs (if empty)
$("#prospects_form .boxsize").blur(function() { if ( this.value === "") { $(this).removeClass("hasText"); } });
$("#form_validation .boxsize").blur(function() { if ( this.value === "") { $(this).parent().removeClass("hasText"); } });
///////////////////
// START VALIDATION
$("#prospects_form").ready(function() {
// DEFINE GLOBAL VARIABLES
var valName = $('#form_name'),
valEmail = $("#form_email"),
valEmailFormat = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
valMsg = $('#form_message'),
valCaptcha = $('#form_captcha'),
valCaptchaCode = $('.form_captcha_code');
// Generate captcha
function randomgen() {
var rannumber = "";
// Iterate through 1 to 9, 4 times
for(ranNum=1; ranNum<=4; ranNum++){ rannumber+=Math.floor(Math.random()*10).toString(); }
// Apply captcha to element
valCaptchaCode.html(rannumber);
}
randomgen();
// CAPTCHA VALIDATION
valCaptcha.blur(function() {
function formCaptcha() {
if ( valCaptcha.val() == valCaptchaCode.html() ) {
// Incorrect
valCaptcha.parent().addClass("invalid");
return false;
} else {
// Correct
valCaptcha.parent().removeClass("invalid");
return true;
}
}
formCaptcha();
});
// Remove invalid class from captcha if typing
valCaptcha.keypress(function() {
valCaptcha.parent().removeClass("invalid");
});
// EMAIL VALIDATION (BLUR)
valEmail.blur(function() {
function formEmail() {
if (!valEmailFormat.test(valEmail.val()) && valEmail.val() !== "" ) {
// Incorrect
valEmail.addClass("invalid");
} else {
// Correct
valEmail.removeClass("invalid");
}
}
formEmail();
});
// Remove invalid class from email if typing
valEmail.keypress(function() {
valEmail.removeClass("invalid");
});
// VALIDATION ON SUBMIT
$('#prospects_form').submit(function() {
console.log('user hit send button');
// EMAIL VALIDATION (SUBMIT)
function formEmailSubmit() {
if (!valEmailFormat.test(valEmail.val())) {
// Incorrect
valEmail.addClass("invalid");
} else {
// Correct
valEmail.removeClass("invalid");
}
}
formEmailSubmit();
// Validate captcha
function formCaptchaSubmit() {
if( valCaptcha.val() === valCaptchaCode.html() ) {
// Captcha is correct
} else {
// Captcha is incorrect
valCaptcha.parent().addClass("invalid");
randomgen();
}
}
formCaptchaSubmit();
// If NAME field is empty
function formNameSubmit() {
if ( valName.val() === "" ) {
// Name is empty
valName.addClass("invalid");
} else {
valName.removeClass("invalid");
}
}
formNameSubmit();
// If MESSAGE field is empty
function formMessageSubmit() {
if ( valMsg.val() === "" ) {
// Name is empty
valMsg.addClass("invalid");
} else {
valMsg.removeClass("invalid");
}
}
formMessageSubmit();
// Submit form (if all good)
function processForm() {
if ( formEmailSubmit() && formCaptchaSubmit() && formNameSubmit() && formMessageSubmit() ) {
$("#prospects_form").attr("action", "/clients/oubc/row-for-oubc-send.php");
$("#form_send").attr("type", "submit");
return true;
} else if( !formEmailSubmit() ) {
valEmail.addClass("invalid");
return false;
} else if ( !formCaptchaSubmit() ) {
valCaptcha.parent().addClass("invalid");
return false;
} else if ( !formNameSubmit() ) {
valName.addClass("invalid");
return false;
} else if ( !formMessageSubmit() ) {
valMsg.addClass("invalid");
return false;
} else {
return false;
}
}
});
});
// END VALIDATION
/////////////////
});
You can prevent the form from submitting with
$("#prospects_form").submit(function(e) {
e.preventDefault();
});
Of course, in the function, you can check for empty fields, and if anything doesn't look right, e.preventDefault() will stop the submit.
Without jQuery:
var form = document.getElementById("myForm");
function handleForm(event) { event.preventDefault(); }
form.addEventListener('submit', handleForm);
Add this onsubmit="return false" code:
<form onsubmit="return false">
That fixed it for me. It will still run the onClick function you specify.
Replace button type to button:
<button type="button">My Cool Button</button>
One great way to prevent reloading the page when submitting using a form is by adding return false with your onsubmit attribute.
<form onsubmit="yourJsFunction();return false">
<input type="text"/>
<input type="submit"/>
</form>
You can use this code for form submission without a page refresh. I have done this in my project.
$(function () {
$('#myFormName').on('submit',function (e) {
$.ajax({
type: 'post',
url: 'myPageName.php',
data: $('#myFormName').serialize(),
success: function () {
alert("Email has been sent!");
}
});
e.preventDefault();
});
});
This problem becomes more complex when you give the user 2 possibilities to submit the form:
by clicking on an ad hoc button
by hitting Enter key
In such a case you will need a function which detects the pressed key in which you will submit the form if Enter key was hit.
And now comes the problem with IE (in any case version 11)
Remark:
This issue does not exist with Chrome nor with FireFox !
When you click the submit button the form is submitted once; fine.
When you hit Enter the form is submitted twice ... and your servlet will be executed twice. If you don't have PRG (post redirect get) architecture serverside the result might be unexpected.
Even though the solution looks trivial, it tooks me many hours to solve this problem, so I hope it might be usefull for other folks.
This solution has been successfully tested, among others, on IE (v 11.0.9600.18426), FF (v 40.03) & Chrome (v 53.02785.143 m 64 bit)
The source code HTML & js are in the snippet. The principle is described there.
Warning:
You can't test it in the snippet because the post action is not
defined and hitting Enter key might interfer with stackoverflow.
If you faced this issue, then just copy/paste js code to your environment and adapt it to your context.
/*
* inForm points to the form
*/
var inForm = document.getElementById('idGetUserFrm');
/*
* IE submits the form twice
* To avoid this the boolean isSumbitted is:
* 1) initialized to false when the form is displayed 4 the first time
* Remark: it is not the same event as "body load"
*/
var isSumbitted = false;
function checkEnter(e) {
if (e && e.keyCode == 13) {
inForm.submit();
/*
* 2) set to true after the form submission was invoked
*/
isSumbitted = true;
}
}
function onSubmit () {
if (isSumbitted) {
/*
* 3) reset to false after the form submission executed
*/
isSumbitted = false;
return false;
}
}
<!DOCTYPE html>
<html>
<body>
<form id="idGetUserFrm" method="post" action="servletOrSomePhp" onsubmit="return onSubmit()">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<input type="submit" value="Submit">
</form>
</body>
</html>
The best solution is onsubmit call any function whatever you want and return false after it.
onsubmit="xxx_xxx(); return false;"
Most people would prevent the form from submitting by calling the event.preventDefault() function.
Another means is to remove the onclick attribute of the button, and get the code in processForm() out into .submit(function() { as return false; causes the form to not submit. Also, make the formBlaSubmit() functions return Boolean based on validity, for use in processForm();
katsh's answer is the same, just easier to digest.
(By the way, I'm new to stackoverflow, give me guidance please. )
In pure Javascript, use: e.preventDefault()
e.preventDefault() is used in jquery but works in javascript.
document.querySelector(".buttonclick").addEventListener("click",
function(e){
//some code
e.preventDefault();
})
The best way to do so with JS is using preventDefault() function.
Consider the code below for reference:
function loadForm(){
var loginForm = document.querySelector('form'); //Selecting the form
loginForm.addEventListener('submit', login); //looking for submit
}
function login(e){
e.preventDefault(); //to stop form action i.e. submit
}
Personally I like to validate the form on submit and if there are errors, just return false.
$('form').submit(function() {
var error;
if ( !$('input').val() ) {
error = true
}
if (error) {
alert('there are errors')
return false
}
});
http://jsfiddle.net/dfyXY/
$("#buttonID").click(function (e) {
e.preventDefault();
//some logic here
}
If you want to use Pure Javascript then the following snippet will be better than anything else.
Suppose:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Form Without Submiting With Pure JS</title>
<script type="text/javascript">
window.onload = function(){
/**
* Just Make sure to return false so that your request will not go the server script
*/
document.getElementById('simple_form').onsubmit = function(){
// After doing your logic that you want to do
return false
}
}
</script>
</head>
<body>
</body>
</html>
<form id="simple_form" method="post">
<!-- Your Inputs will go here -->
<input type="submit" value="Submit Me!!" />
</form>
Hope so it works for You!!
Just use "javascript:" in your action attribute of form if you are not using action.
In my opinion, most answers are trying to solve the problem asked on your question, but I don't think that's the best approach for your scenario.
How would I go about preventing the page from refreshing when pressing the send button without any data in the fields?
A .preventDefault() does indeed not refresh the page. But I think that a simple require on the fields you want populated with data, would solve your problem.
<form id="prospects_form" method="post">
<input id="form_name" tabindex="1" class="boxsize" type="text" name="name" placeholder="Full name*" maxlength="80" value="" required/>
<input id="form_email" tabindex="2" class="boxsize" type="text" name="email" placeholder="Email*" maxlength="100" value="" required/>
<input id="form_subject" class="boxsize" type="text" name="subject" placeholder="Subject*" maxlength="50" value="FORM: Row for OUBC" required/>
<textarea id="form_message" class="boxsize" name="message" placeholder="Message*" tabindex="3" rows="6" cols="5" maxlength="500"></textarea>
</form>
Notice the require tag added at the end of each input. The result will be the same: not refreshing the page without any data in the fields.
<form onsubmit="myFunction(event)">
Name : <input type="text"/>
<input class="submit" type="submit">
</form>
<script>
function myFunction(event){
event.preventDefault();
//code here
}
</script>
function ajax_form(selector, obj)
{
var form = document.querySelectorAll(selector);
if(obj)
{
var before = obj.before ? obj.before : function(){return true;};
var $success = obj.success ? obj.success: function(){return true;};
for (var i = 0; i < form.length; i++)
{
var url = form[i].hasAttribute('action') ? form[i].getAttribute('action') : window.location;
var $form = form[i];
form[i].submit = function()
{
var xhttp = new XMLHttpRequest();
xhttp.open("POST", url, true);
var FD = new FormData($form);
/** prevent submiting twice */
if($form.disable === true)
return this;
$form.disable = true;
if(before() === false)
return;
xhttp.addEventListener('load', function()
{
$form.disable = false;
return $success(JSON.parse(this.response));
});
xhttp.send(FD);
}
}
}
return form;
}
Didn't check how it works. You can also bind(this) so it will work like jquery ajaxForm
use it like:
ajax_form('form',
{
before: function()
{
alert('submiting form');
// if return false form shouldn't be submitted
},
success:function(data)
{
console.log(data)
}
}
)[0].submit();
it return nodes so you can do something like submit i above example
so far from perfection but it suppose to work, you should add error handling or remove disable condition
Sometimes e.preventDefault(); works then developers are happy but sometimes not work then developers are sad then I found solution why sometimes not works
first code sometimes works
$("#prospects_form").submit(function(e) {
e.preventDefault();
});
second option why not work?
This doesn't work because jquery or other javascript library not loading properly you can check it in console that all jquery and javascript files are loaded properly or not.
This solves my problem. I hope this will be helpful for you.
I hope this will be the last answer
$('#the_form').submit(function(e){
e.preventDefault()
alert($(this).serialize())
// var values = $(this).serialize()
// logic....
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="the_form">
Label-A <input type="text" name='a'required><br>
Label-B <input type="text" name="b" required><br>
Label-C <input type="password" name="c" required><br>
Label-D <input type="number" name="d" required><br>
<input type="submit" value="Save without refresh">
</form>
You can do this by clearing the state as below. add this to very beginning of the document.ready function.
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}

How to check status without loop and not have application freeze

I am not a javascript coder, but was trying to figure out a solution with using HTML Web Forms and Javascript... However, I am using a while loop to keep checking the status of a submitted job, but because I am doing this, the page freezes. Is there way to check the status without having the page freeze?
<!DOCTYPE html>
<html>
<body>
<p><span style="background-color:{color}; border-radius:3px; color:#ffffff; float:right; font-size:16px; padding:2px 4px 2px 4px"><a id='downLoad' href="" download='file' style='display:none' target='_blank'>Save file As</a></span><span style="font-size:24px"><span style="color:#d52b40">Print Survey Report </span></span></p>
<p>Enter the project <b>Print ID</b> and <b>File Name</b> then submit the report for print. Repot may take a few minutes, but a <b>Save File As link</b> will show when ready for download. Right click and select <b>Save Link As</b></p>
<form id='printSurvey'>
<input type="hidden" id="portalUrl" name="portalUrl" value="https://transportation.bd.esri.com/portal">
<input type="hidden" id="templateItemId" name="templateItemId" value="a19dc0354ade4e9da65086453d89aa4a">
<input type="hidden" id="surveyItemId" name="surveyItemId" value="901946f3a7f940f4bab7bbda9d7595e3">
<input type="hidden" id="featureLayerUrl" name="featureLayerUrl" value="https://transportation-rh.bd.esri.com/server/rest/services/Geotech/GeotechProjectInfoPointSDE/FeatureServer/2">
<input type="hidden" id="token" name="token" value="toekn was removed">
<input type="hidden" id="outputFormat" name="outputFormat" value="docx">
<input type="hidden" id="uploadInfo" name="uploadInfo[type]" value="arcgis">
<input type="hidden" id="uploadInfo" name="uploadInfo[parameters][folderId]" value="6128cd36706f40ddaaa387e9296032a9">
<input type="hidden" id="uploadInfo" name="uploadInfo[parameters][conflictBehavior]" value="rename">
<label for="queryParameters">Print ID:</label>
<input type="text" id="queryParameters" name="queryParameters[objectIds]" placeholder="i.e 1"><br><br>
<label for="outputReportName">Report Name:</label>
<input type="text" id="outputReportName" name="outputReportName" placeholder="Logging Report Name"><br><br>
<input type="hidden" id="outputPackageName" name="outputPackageName" >
<input type="submit" type="buton" value="Submit">
</form>
<script>
document.getElementById("outputReportName").addEventListener('focusout',function () {
document.getElementById("outputPackageName").value = this.value;
});
const downLoadTag = document.getElementById('downLoad');
function httpGet(url){
let xmlHttpReq = new XMLHttpRequest();
var url = url +'?portalUrl=https://transportation.bd.esri.com/portal&token=token was removedenter code here'
xmlHttpReq.open("GET", url, false);
xmlHttpReq.send(null);
return JSON.parse(xmlHttpReq.responseText);
}
window.addEventListener("load", () => {
function sendData() {
const XHR = new XMLHttpRequest();
// Bind the FormData object and the form element
const FD = new FormData(form);
// Define what happens on successful data submission
setTimeout(XHR.addEventListener("load", (event) => {
//alert(event.target.responseText['jobId']);
var responseArray = JSON.parse(event.target.responseText);
var jobID = responseArray['jobId'];
var urlPath = 'https://survey123.arcgis.com/api/featureReport/jobs/'+jobID
var status = 'esriJobExecuting'
alert('Report is being generated... This may take several minutes');
var countEnd = 0
while (status != 'esriJobSucceeded') {
var getRep = httpGet(urlPath)
if (getRep['jobStatus'] == 'esriJobSucceeded'){
var itemID = getRep['resultInfo']['resultFiles'][0]['id'];
var urlBeg = 'https://transportation.bd.esri.com/portal/sharing/rest/content/items/';
var urlEnd = '/data?token=token was removed';
downLoadTag.href = urlBeg +itemID+urlEnd;
//console.log(getRep['resultInfo']);
status = getRep['jobStatus'];
//console.log(getRep);
alert('Report is ready for download')
};
};
downLoadTag.style='display:show';
}), 5);
// Define what happens in case of error
XHR.addEventListener("error", (event) => {
alert('Oops! Something went wrong.');
});
// Set up our request
XHR.open("POST", 'https://survey123.arcgis.com/api/featureReport/createReport/submitJob');
// The data sent is what the user provided in the form
XHR.send(FD);
};
// Get the form element
const form = document.getElementById("printSurvey");
// Add 'submit' event handler
form.addEventListener("submit", (event) => {
event.preventDefault();
sendData();
});
});
</script>
</body>
</html>
I struggled with the same problem recently. There is a Web Workers API. It does everything in the background and doesn't block the main thread. It is easy to learn and understand. Just google Web Workers API and you will get it!

Submit HTML Form to firestore with Validation without a action [duplicate]

How would I go about preventing the page from refreshing when pressing the send button without any data in the fields?
The validation is setup working fine, all fields go red but then the page is immediately refreshed. My knowledge of JS is relatively basic.
In particular I think the processForm() function at the bottom is 'bad'.
HTML
<form id="prospects_form" method="post">
<input id="form_name" tabindex="1" class="boxsize" type="text" name="name" placeholder="Full name*" maxlength="80" value="" />
<input id="form_email" tabindex="2" class="boxsize" type="text" name="email" placeholder="Email*" maxlength="100" value="" />
<input id="form_subject" class="boxsize" type="text" name="subject" placeholder="Subject*" maxlength="50" value="FORM: Row for OUBC" />
<textarea id="form_message" class="boxsize" name="message" placeholder="Message*" tabindex="3" rows="6" cols="5" maxlength="500"></textarea>
<button id="form_send" tabindex="5" class="btn" type="submit" onclick="return processForm()">Send</button>
<div id="form_validation">
<span class="form_captcha_code"></span>
<input id="form_captcha" class="boxsize" type="text" name="form_captcha" placeholder="Enter code" tabindex="4" value="" />
</div>
<div class="clearfix"></div>
</form>
JS
$(document).ready(function() {
// Add active class to inputs
$("#prospects_form .boxsize").focus(function() { $(this).addClass("hasText"); });
$("#form_validation .boxsize").focus(function() { $(this).parent().addClass("hasText"); });
// Remove active class from inputs (if empty)
$("#prospects_form .boxsize").blur(function() { if ( this.value === "") { $(this).removeClass("hasText"); } });
$("#form_validation .boxsize").blur(function() { if ( this.value === "") { $(this).parent().removeClass("hasText"); } });
///////////////////
// START VALIDATION
$("#prospects_form").ready(function() {
// DEFINE GLOBAL VARIABLES
var valName = $('#form_name'),
valEmail = $("#form_email"),
valEmailFormat = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
valMsg = $('#form_message'),
valCaptcha = $('#form_captcha'),
valCaptchaCode = $('.form_captcha_code');
// Generate captcha
function randomgen() {
var rannumber = "";
// Iterate through 1 to 9, 4 times
for(ranNum=1; ranNum<=4; ranNum++){ rannumber+=Math.floor(Math.random()*10).toString(); }
// Apply captcha to element
valCaptchaCode.html(rannumber);
}
randomgen();
// CAPTCHA VALIDATION
valCaptcha.blur(function() {
function formCaptcha() {
if ( valCaptcha.val() == valCaptchaCode.html() ) {
// Incorrect
valCaptcha.parent().addClass("invalid");
return false;
} else {
// Correct
valCaptcha.parent().removeClass("invalid");
return true;
}
}
formCaptcha();
});
// Remove invalid class from captcha if typing
valCaptcha.keypress(function() {
valCaptcha.parent().removeClass("invalid");
});
// EMAIL VALIDATION (BLUR)
valEmail.blur(function() {
function formEmail() {
if (!valEmailFormat.test(valEmail.val()) && valEmail.val() !== "" ) {
// Incorrect
valEmail.addClass("invalid");
} else {
// Correct
valEmail.removeClass("invalid");
}
}
formEmail();
});
// Remove invalid class from email if typing
valEmail.keypress(function() {
valEmail.removeClass("invalid");
});
// VALIDATION ON SUBMIT
$('#prospects_form').submit(function() {
console.log('user hit send button');
// EMAIL VALIDATION (SUBMIT)
function formEmailSubmit() {
if (!valEmailFormat.test(valEmail.val())) {
// Incorrect
valEmail.addClass("invalid");
} else {
// Correct
valEmail.removeClass("invalid");
}
}
formEmailSubmit();
// Validate captcha
function formCaptchaSubmit() {
if( valCaptcha.val() === valCaptchaCode.html() ) {
// Captcha is correct
} else {
// Captcha is incorrect
valCaptcha.parent().addClass("invalid");
randomgen();
}
}
formCaptchaSubmit();
// If NAME field is empty
function formNameSubmit() {
if ( valName.val() === "" ) {
// Name is empty
valName.addClass("invalid");
} else {
valName.removeClass("invalid");
}
}
formNameSubmit();
// If MESSAGE field is empty
function formMessageSubmit() {
if ( valMsg.val() === "" ) {
// Name is empty
valMsg.addClass("invalid");
} else {
valMsg.removeClass("invalid");
}
}
formMessageSubmit();
// Submit form (if all good)
function processForm() {
if ( formEmailSubmit() && formCaptchaSubmit() && formNameSubmit() && formMessageSubmit() ) {
$("#prospects_form").attr("action", "/clients/oubc/row-for-oubc-send.php");
$("#form_send").attr("type", "submit");
return true;
} else if( !formEmailSubmit() ) {
valEmail.addClass("invalid");
return false;
} else if ( !formCaptchaSubmit() ) {
valCaptcha.parent().addClass("invalid");
return false;
} else if ( !formNameSubmit() ) {
valName.addClass("invalid");
return false;
} else if ( !formMessageSubmit() ) {
valMsg.addClass("invalid");
return false;
} else {
return false;
}
}
});
});
// END VALIDATION
/////////////////
});
You can prevent the form from submitting with
$("#prospects_form").submit(function(e) {
e.preventDefault();
});
Of course, in the function, you can check for empty fields, and if anything doesn't look right, e.preventDefault() will stop the submit.
Without jQuery:
var form = document.getElementById("myForm");
function handleForm(event) { event.preventDefault(); }
form.addEventListener('submit', handleForm);
Add this onsubmit="return false" code:
<form onsubmit="return false">
That fixed it for me. It will still run the onClick function you specify.
Replace button type to button:
<button type="button">My Cool Button</button>
One great way to prevent reloading the page when submitting using a form is by adding return false with your onsubmit attribute.
<form onsubmit="yourJsFunction();return false">
<input type="text"/>
<input type="submit"/>
</form>
You can use this code for form submission without a page refresh. I have done this in my project.
$(function () {
$('#myFormName').on('submit',function (e) {
$.ajax({
type: 'post',
url: 'myPageName.php',
data: $('#myFormName').serialize(),
success: function () {
alert("Email has been sent!");
}
});
e.preventDefault();
});
});
This problem becomes more complex when you give the user 2 possibilities to submit the form:
by clicking on an ad hoc button
by hitting Enter key
In such a case you will need a function which detects the pressed key in which you will submit the form if Enter key was hit.
And now comes the problem with IE (in any case version 11)
Remark:
This issue does not exist with Chrome nor with FireFox !
When you click the submit button the form is submitted once; fine.
When you hit Enter the form is submitted twice ... and your servlet will be executed twice. If you don't have PRG (post redirect get) architecture serverside the result might be unexpected.
Even though the solution looks trivial, it tooks me many hours to solve this problem, so I hope it might be usefull for other folks.
This solution has been successfully tested, among others, on IE (v 11.0.9600.18426), FF (v 40.03) & Chrome (v 53.02785.143 m 64 bit)
The source code HTML & js are in the snippet. The principle is described there.
Warning:
You can't test it in the snippet because the post action is not
defined and hitting Enter key might interfer with stackoverflow.
If you faced this issue, then just copy/paste js code to your environment and adapt it to your context.
/*
* inForm points to the form
*/
var inForm = document.getElementById('idGetUserFrm');
/*
* IE submits the form twice
* To avoid this the boolean isSumbitted is:
* 1) initialized to false when the form is displayed 4 the first time
* Remark: it is not the same event as "body load"
*/
var isSumbitted = false;
function checkEnter(e) {
if (e && e.keyCode == 13) {
inForm.submit();
/*
* 2) set to true after the form submission was invoked
*/
isSumbitted = true;
}
}
function onSubmit () {
if (isSumbitted) {
/*
* 3) reset to false after the form submission executed
*/
isSumbitted = false;
return false;
}
}
<!DOCTYPE html>
<html>
<body>
<form id="idGetUserFrm" method="post" action="servletOrSomePhp" onsubmit="return onSubmit()">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<input type="submit" value="Submit">
</form>
</body>
</html>
The best solution is onsubmit call any function whatever you want and return false after it.
onsubmit="xxx_xxx(); return false;"
Most people would prevent the form from submitting by calling the event.preventDefault() function.
Another means is to remove the onclick attribute of the button, and get the code in processForm() out into .submit(function() { as return false; causes the form to not submit. Also, make the formBlaSubmit() functions return Boolean based on validity, for use in processForm();
katsh's answer is the same, just easier to digest.
(By the way, I'm new to stackoverflow, give me guidance please. )
In pure Javascript, use: e.preventDefault()
e.preventDefault() is used in jquery but works in javascript.
document.querySelector(".buttonclick").addEventListener("click",
function(e){
//some code
e.preventDefault();
})
The best way to do so with JS is using preventDefault() function.
Consider the code below for reference:
function loadForm(){
var loginForm = document.querySelector('form'); //Selecting the form
loginForm.addEventListener('submit', login); //looking for submit
}
function login(e){
e.preventDefault(); //to stop form action i.e. submit
}
Personally I like to validate the form on submit and if there are errors, just return false.
$('form').submit(function() {
var error;
if ( !$('input').val() ) {
error = true
}
if (error) {
alert('there are errors')
return false
}
});
http://jsfiddle.net/dfyXY/
$("#buttonID").click(function (e) {
e.preventDefault();
//some logic here
}
If you want to use Pure Javascript then the following snippet will be better than anything else.
Suppose:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Form Without Submiting With Pure JS</title>
<script type="text/javascript">
window.onload = function(){
/**
* Just Make sure to return false so that your request will not go the server script
*/
document.getElementById('simple_form').onsubmit = function(){
// After doing your logic that you want to do
return false
}
}
</script>
</head>
<body>
</body>
</html>
<form id="simple_form" method="post">
<!-- Your Inputs will go here -->
<input type="submit" value="Submit Me!!" />
</form>
Hope so it works for You!!
Just use "javascript:" in your action attribute of form if you are not using action.
In my opinion, most answers are trying to solve the problem asked on your question, but I don't think that's the best approach for your scenario.
How would I go about preventing the page from refreshing when pressing the send button without any data in the fields?
A .preventDefault() does indeed not refresh the page. But I think that a simple require on the fields you want populated with data, would solve your problem.
<form id="prospects_form" method="post">
<input id="form_name" tabindex="1" class="boxsize" type="text" name="name" placeholder="Full name*" maxlength="80" value="" required/>
<input id="form_email" tabindex="2" class="boxsize" type="text" name="email" placeholder="Email*" maxlength="100" value="" required/>
<input id="form_subject" class="boxsize" type="text" name="subject" placeholder="Subject*" maxlength="50" value="FORM: Row for OUBC" required/>
<textarea id="form_message" class="boxsize" name="message" placeholder="Message*" tabindex="3" rows="6" cols="5" maxlength="500"></textarea>
</form>
Notice the require tag added at the end of each input. The result will be the same: not refreshing the page without any data in the fields.
<form onsubmit="myFunction(event)">
Name : <input type="text"/>
<input class="submit" type="submit">
</form>
<script>
function myFunction(event){
event.preventDefault();
//code here
}
</script>
function ajax_form(selector, obj)
{
var form = document.querySelectorAll(selector);
if(obj)
{
var before = obj.before ? obj.before : function(){return true;};
var $success = obj.success ? obj.success: function(){return true;};
for (var i = 0; i < form.length; i++)
{
var url = form[i].hasAttribute('action') ? form[i].getAttribute('action') : window.location;
var $form = form[i];
form[i].submit = function()
{
var xhttp = new XMLHttpRequest();
xhttp.open("POST", url, true);
var FD = new FormData($form);
/** prevent submiting twice */
if($form.disable === true)
return this;
$form.disable = true;
if(before() === false)
return;
xhttp.addEventListener('load', function()
{
$form.disable = false;
return $success(JSON.parse(this.response));
});
xhttp.send(FD);
}
}
}
return form;
}
Didn't check how it works. You can also bind(this) so it will work like jquery ajaxForm
use it like:
ajax_form('form',
{
before: function()
{
alert('submiting form');
// if return false form shouldn't be submitted
},
success:function(data)
{
console.log(data)
}
}
)[0].submit();
it return nodes so you can do something like submit i above example
so far from perfection but it suppose to work, you should add error handling or remove disable condition
Sometimes e.preventDefault(); works then developers are happy but sometimes not work then developers are sad then I found solution why sometimes not works
first code sometimes works
$("#prospects_form").submit(function(e) {
e.preventDefault();
});
second option why not work?
This doesn't work because jquery or other javascript library not loading properly you can check it in console that all jquery and javascript files are loaded properly or not.
This solves my problem. I hope this will be helpful for you.
I hope this will be the last answer
$('#the_form').submit(function(e){
e.preventDefault()
alert($(this).serialize())
// var values = $(this).serialize()
// logic....
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="the_form">
Label-A <input type="text" name='a'required><br>
Label-B <input type="text" name="b" required><br>
Label-C <input type="password" name="c" required><br>
Label-D <input type="number" name="d" required><br>
<input type="submit" value="Save without refresh">
</form>
You can do this by clearing the state as below. add this to very beginning of the document.ready function.
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}

Meteor: form with two submit buttons (determine button clicked in event handler)

I have a simple form with two inputs: "title" and _"description", and two buttons: "save" (save for later) and "submit". For both I would want to get the values of my form fields and insert/update my collections accordingly.
<template name="NewScenarioForm">
<form id="newScenarioForm" >
<textarea type="text" id="title" name="title" rows="1" cols="75" placeholder="Type to add a title"></textarea><br/>
<textarea type="text" id="description" name="description" rows="4" cols="100" placeholder="Type to add a description" ></textarea><br/>
<input type="submit" id="saveScenarioButton" name="action" title="Save Scenario" value="Save" />
<input type="submit" id="submitScenarioButton" name="action" title="Submit for approval" value="Submit" />
</form>
</template>
Right now I'm detecting the event like this:
"click #saveScenarioButton": function(event, template) {
event.preventDefault();
var title = template.find("#title").value;
var description = template.find("#description").value;
...
//Do stuff with this information to persist information
Meteor.call("saveScenario", title, description);
....
}
And I need to repeat the whole function for the other button. I would would like to detect the event and determine which button was pressed instead.
I have been struggling with an event handler like:
"submit #newScenarioForm": function(event) {
But then I don't know how to determine the button clicked, since I can't figure out an event property. Is there a way to determine the button if I wanted to use the form ID in my event handler instead of the ID of each button (or a smarter way to approach this altogether?)?
You could make the event target inputs with type submit:
Template.NewScenarioForm.events({
"click input[type=submit]": function(e) {
if ($(e.target).prop("id") == "saveScenarioButton") {
// Save the scenario
} else if ($(e.target).prop("id") == "submitScenarioButton") {
// Submit the scenario
}
}
});
You could also make it check the clicked button's value, and drop the ID field
Please note that this will not handle other ways of submitting the form, for example the user pressing Enter in an input field. An approach to handle this as well could be to define a few functions:
function scrapeForm() {
// Collects data from the form into an object
}
function saveData() {
var formData = scrapeForm();
// More logic to save the data
}
function submitData() {
var formData = scrapeForm();
// More logic to submit the data
}
Template.NewScenarioForm.events({
"click input[type=submit]": function(e) {
if ($(e.target).prop("id") == "saveScenarioButton") {
saveData();
} else if ($(e.target).prop("id") == "submitScenarioButton") {
submitData();
}
},
"submit #NewScenarioForm":
// Default action on submit.
// Either save the data
saveData
// or submit the data
submitData
// or nothing, requiring the user to actually click one of the buttons
function(e) {e.preventDefault();}
});
Why not just give them both the same class like submitForm
<input class="submitForm"** type="submit" id="saveScenarioButton" name="action" title="Save Scenario" value="Save" />
<input class="submitForm" type="submit" id="submitScenarioButton" name="action" title="Submit for approval" value="Submit" />
then have a onClick for .submitForm like so:
$('.submitForm').on('click', function () {...});
and inside the function get id by doing:
var id = $(this).attr('id');
full code:
$('.submitForm').on('click', function () {
var id = $(this).attr('id');
... the rest of your code ...
});
I do this to correctly identify buttons using class or id.
helloWorld.html
<head>
<title>helloWorld</title>
</head>
<body>
<h1>Welcome to Meteor!</h1>
{{> hello}}
</body>
<template name="hello">
<button class="plus5">+5</button>
<button class="minu5">-5</button>
<button id="plus1">+1</button>
<button id="minu1">-1</button>
<p>You've pressed the button {{counter}} times.</p>
</template>
helloWorld.js
if (Meteor.isClient) {
// counter starts at 0
Session.setDefault('counter', 0);
Template.hello.helpers({
counter: function () {
return Session.get('counter');
}
});
Template.hello.events({
'click button.plus5': function () {
Session.set('counter', Session.get('counter') + 5);
},
'click button.minu5': function () {
Session.set('counter', Session.get('counter') - 5);
},
'click button#plus1': function () {
Session.set('counter', Session.get('counter') + 1);
},
'click button#minu1': function () {
Session.set('counter', Session.get('counter') - 1);
}
});
}
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
});
}
click .plus5, click #plus1 also work.

Submitting form after using e.preventDefault();

I have a form that I am stopping from submitting with e.preventDefault(). (I've also tried return false).
I would manually tell the form to submit after a short delay, using the code:
$('form').delay(2000).submit();
Unfortunately, e.preventDefault() seems to disable the form from submitting even if it explicitly submitted using the submit() function.
Any idea how I can combine these intentions? I'd like to show a loading screen for a couple of seconds.
Thanks!
$("form").on('submit.blocker', function (e) {
setTimeout(function () {
$("form").off('submit.blocker').trigger('submit');
}, 2000);
e.preventDefault();
});
Try this.
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function ()
{
var okToSubmit = false;
$('form').submit(function (e)
{
if ( ! okToSubmit)
{
e.preventDefault();
var $form = $(this);
setTimeout(function ()
{
okToSubmit = true;
$form.submit();
}, 2000);
}
});
});
</script>
<form action="somewhere">
<input type="text" name="something" />
<input type="submit" />
</form>
Above code is tested.
$('form').on('submit', function(e) {
if (!e.isTrigger) {
setTimeout(function() {
$("form").trigger('submit');
}, 2000);
e.preventDefault();
}
});
you may want to try this it works for me:
<form name="demo" action="111" onSubmit="fun();return false">
<input type="text" name="name1" />
<input type="submit" />
</form>
and in the javascript
fun()
{
var x= document.forms["demo"];
setTimeout(x.submit(),2000);//time in milliseconds
}

Categories