popup dialog on submit - javascript

I have a partial view in MVC2:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<div class="uploader">
<form action="/media/uploader" method="post" enctype="multipart/form-data">
<input id="File1" type="file" name="upfile" />
<input type="submit" value="Upload" />
</form>
</div>
enter code here
I dont know how to do next:
after user press submit button, I would like to validate extension of uploaded file. If extension is valid, I would post uploaded file, but if extension is not suported, I would like to alert user somehow (popup?) and abort submit. I tried some things with jquery, but I just dont understand it enough so I cant make it work.
Thank you for any advice.

I'm not an MVC guy but I know that you have two options that should work here just from the strict JS/FORMS perspective...
The form has an event - onsubmit - if you have an event handler that returns false to the onsubmit event, the submit won't happen. Similarly, if you have an event handler on the submit button's onclick event, returning false will cancel the click, hence, the form post as well.
Here's an example relying on the form's onsubmit:
<form action="/myDir/myPage.ext" method="post" onsubmit="return validForm(window.event);">
....
</form>
If you implement the method validForm it might look something like:
function validForm(e) {
var fullPath = document.getElementById('File1').value;
if (validateFileExtension(fullPath)) {
return true;
} else {
alert('Invalid extension for this file!');
return false;
}
}
function validateFileExtension(fullPath) {
var isValid = false;
// some logic to parse and validate extension
// if the logic passes, we set isValid to true.
return isValid;
}
With the above methods fully implemented, your two options are to use the method in either the submit button's onclick event or in the form's onsubmit event. Either way, you'll want to check the value of the File Input, ensure the extension is what you want, and return false if the extension violates whatever your business rules are. If you return true, the button click/form submit will proceed. If you return false, the form submit or button click (depending on which event you've wired to) will cancel - either way, same result - no form submission without what you want in the file field.
Happy coding.
B

You could use the Ajax Upload plugin which allows you to do this.

Related

Angular still submits the form even when I return false in the handler

I have something like the following:
HTML template:
<form [action]='endpoint' method="post" target="my_iframe" #confirmForm (ngSubmit)="submitConfirmation()">
<button type="submit" (click)="confirmForm.submit()">Submit</button>
</form>
<iframe name="my_iframe"></iframe>
And in the component:
submitConfirmation() {
return false;
}
I've also tried throwing an error:
submitConfirmation() {
throw Error('test');
return false;
}
No matter what I do, the form still submits! Every resource I found online tells me that if I return false in the submit handler, the form will not be submitted. Could this have something to do with the iframe? (it's required for reasons I won't get into). The method definitely runs, I have checked and triple checked.
On a related note, do I actually need (click)="confirmForm.submit() on the submit button?
EDIT: I just tried removing (click)="confirmForm.submit() and now I'm even more confused! When I removed that binding, the button still works, the method submitConfirmation still gets called, but now the form fails to submit regardless of whether I return false or not.
Just need to preventDefault on the triggering event. Your component class should look like:
submitConfirmation(event) {
event.preventDefault();
// other stuff
}
To use that will require passing in the $event parameter from the component template:
<form ... (ngSubmit)="submitConfirmation($event)">
<button type="submit">Submit</button>
</form>
No need for (click)="confirmForm.submit(). Buttons within a form will default to a type of submit (explicitly set type="button" otherwise) and this will trigger the (ngSubmit) event.

How do I stop bots from using .submit() to bypass my 'required' fields?

I have a form which is producing a lot of spam. I have made all inputs required and have attached a captcha. This has not had any affect.
I assume the bots are using form.submit() as for some reason this bypasses all my required fields AND also bypasses my onsubmit="check(e)"
I cannot seem to grab this event .submit() by any means. Does anyone know how to catch this event and make sure it is cancelled. I want the only way to submit the form is through clicking the submit button.
$("#myForm").submit(function(event) {
console.log("Handler for .submit() called.");
if (CaptchaInput.value == "") {
event.preventDefault();
}
});
My code that was supposed to catch a .submit() call and prevent the form submission. This function is never triggered.
<form target="hidden_iframe"
onsubmit="if (CaptchaInput.value == '') { why += '- Please Enter CAPTCHA Code.\n'; alert(why); return false; };return checkform(this)" id="myForm">
You cannot. I can submit your form without a browser, or with JavaScript disabled. Anyone can just send an HTTP POST request to your server, without going through any client-side process you may introduce.
The solution to your problem is to also verify on the server, and don't rely on the client side validation to have completed successfully (or indeed, even to have been run at all).
Treat client-side validation as a convenience to your users, they see the error immediately without having to retype and resubmit the entire form.
You can define the onsubmit attribute of the form, to run a function that validates your input. The browser will submit the form only if that function returns true.
UPDATE:
You can define the action only after the form has been validated.
So, your html will look something like this:
<form id="myForm" onsubmit="return checkRecaptcha()" action="disabled">
<input type="text" name="myTextInput" value="">
<input type="submit" value="Submit">
</form>
And your javascript code, that defines the function will look like this:
function checkRecaptcha() {
if (CaptchaInput.value == "") {
document.getElementById("myForm").action="myCorrectUrl";
return true;
} else {
alert("not allowed");
return false;
}
}
Then for catching the submit function:
document.getElementById("myForm").submit = function () {
console.log("catched");
return false;
}

Submit form with jquery which has multiple submit buttons without click trigger?

Imagine this :
<form id="form">
<input type="text">
<button type="submit" name="submit1" value="1">something1</button>
<button type="submit" name="submit2" value="2">something2</button>
<button type="submit" name="submit3" value="3">something3</button>
</form>
First of all when I write $('#form').submit() which submit value will be sent? the first one?
Second of all How can I submit the form without the click trigger event with the value I want? Is it possible at all? For example submitting the form with the 2 submit value.
The reason I want do this is to have confirmation popup with sweetalert before sending my form so here it is :
$('form').on('submit',function(e){
form = $(this);
e.preventDefault();
swal({'some dialog'},function(isConfirm)
{
if(isConfirm)
form.submit;
\\If I use the click trigger I will get stuck in here again.
})
});
There is an alternative - use the FormData You can create an instance of a FormData, add your html form, modify entries, and send it. Everything is under your control here then.
EDIT: Based on your edit, it seems you have the problem of resubmitting the form. You can handle it like this.
var form = document.querySelector('form');
form.addEventListener('submit', {
confirmed: false,
handleEvent: function (event) {
if (this.confirmed)
return;
event.preventDefault();
doconfirm((confirmed) => {
if (confirmed) {
this.confirmed = true;
form.submit();
}
})
}
}, false);
Or you can solve your problem by unbinding the submit handlers after validation and submit it again: $('form').off('submit').submit()
As #Scott Marcus explained, the value of named buttons will be submitted when the form is sent to the server. However in your case, this won't help because you want to perform some logic before submitting it to the server.
The issue is that jQuery has no way to determine which button was clicked because it doesn't provide the submit button values when you look at the form data via $.serialize(), and there is no easy cross-browser friendly way to check the button that triggered the $.submit() event without using click.
So, the only workaround would be to handle the click event of the 3 buttons and store some value that is checked before you submit the form as described in this answer: How can I get the button that caused the submit from the form submit event?
Example: http://codeply.com/go/Wj85swRyfX
Let's take your questions one at a time...
First of all when I write $('#form').submit() which submit value will
be sent? the first one?
When a form is submitted, ALL form elements that nave a NAME attribute will submit their value (even if the value is an empty string) to the form's ACTION destination. So, in your case, all 3 of your buttons have a name attribute and so all 3 buttons will submit their name/value pairs.
Usually, we don't put a name attribute on the submit button because we only want it to trigger the submit, not actually use it as a data container. And, we usually include only a single submit button under most circumstances.
Second of all How can I submit the form without the click trigger
event with the value I want? Is it possible at all? For example
submitting the form with the 2 submit value
You would use:
$('#form').submit()
to manually cause the submit, but you'd need to have an if() statement that has logic that determines which value is appropriate to submit. Instead of the value being stored in a button, you could use a hidden form field, like this:
<form id="form">
<input type="text">
<input type="hidden" name="hidden" value="">
<button type="submit">something3</button>
</form>
JavaScript:
$("#form").on("submit", function(evt){
// Stop the form submission process
evt.preventDefault();
// Logic that sets hidden input field to correct value:
if(condition1){
$("input[type=hidden]").attr("value", "1");
} else if(condition2) {
$("input[type=hidden]").attr("value","2");
} else {
$("input[type=hidden]").attr("value","3");
}
// Manually submit the form
$("#form").submit();
});
I suggest to use hidden input tag to make the logic clear.

jquery form - two buttons - one to use ajax, one not

I have a form that I want to use jquery for validation of the form before I submit. If I click on one of the buttons, I have it save the data via an ajax call. For the other button I want to submit the form, but not have it go through ajax, just do a submit the old fashioned way and go to that page.
I had the submitHandler in my validate() function, which works great for doing the ajax stuff, but what about for the other button where I don't want to use ajax? Do I remove the submitHandler portion from the validate() function? If so, then how should I set up for using ajax? Do I put it in the event handler for the click on that button? If so, how should I set it up?
Can't you just create 2 different functions or just one parameterized with a boolean to indicate whether to send ajax request or just submit the form? the latter may be done using the JQuery submit function.
I think the best way is to bind a personal event
$('form').on('submitajax submit', function(e){
if(e.type === 'submitajax'){
//ajaxstuff
}
else{
//classic stuff
}
})
And your ajax button will trigger the submitajax event
Your validation function can be like this:
function bar( ajax )
{
var valid = true, fooForm = $('#fooForm');
// do validation stuff
if( !valid ) return;
if( ajax ){
$.post(fooForm.attr('action'), fooForm.serialize());
}else{
fooForm.submit();
}
}
And your buttons:
<input type="button" value="With Ajax" onclick="bar( true )" />
<input type="button" value="Old Fashion" onclick="bar( false )" />
You need check JavaScript events on submitting form.
Just consider form:
<form class="js-form">
<a class="js-save">Save</a>
<input type="submit" value="Submit"/>
</form>
$('.js-from').on('click', function(event){
if (event.target === event.currentTarget){
# Triggers on click submit input that triggers as part of form and target same
# Call ajax stuff
} else {
# Triggers on click link witch is fired as click as not a part of form
# Call other ajax or link stuff
}
});
One function for cheching if form submit on submit button or link that can do any thing other
I figured it out. In my ajax button click event handlers, I needed to add
event.preventDefault();
Then I could add the $.ajax() call to the one where I wanted to call ajax, and to the other one just did the submit normally.
Thank you for all of your responses, it was an interesting exercise and I learned a bit more about the intricacies of this type of coding.

jquery post works only after alert

I have function that submitted two forms at once. And last (the second) post method does not take effect without alert().
Could you please show me my mistake.
function formFunction() {
...
$.post($("#form1").attr("action"), $("#form1").serialize() );
$.post($("#form2").attr("action"), $("#form2").serialize() );
//alert('done');
}
UPD
this is how function is calling
<form id="form0" name="form0" onsubmit="formFunction()">
<input id="mainFormValue" type="text">
The reason why it is failing is you are not cancelling the original form submission. That means the page is posting back to the server when you click the button. What you need to do is prevent that origial form submission from completing.
If you are adding the event handler with jQuery, you can use preventDefault() to cancel the form submission.
function formFunction(e) {
e.preventDefault();
$.post($("#form1").attr("action"), $("#form1").serialize() );
$.post($("#form2").attr("action"), $("#form2").serialize() );
}
Change the form submission to unobtrusive JavaScript to get the correct event object set by jQuery.
$("#form0").submit(formFunction);
The other solutions is add a return false to the submisison. Just ignore the preventDefault line I suggested above. [bad idea, but will work]
<form id="form0" name="form0" onsubmit="formFunction(); return false">

Categories