I can't submit the form even though I used preventDefault, (page refreshed and doesn't take any action) My form inputs are filled dynamically here is my code.
HTML
<div class="modal-body">
<form id="update_form">
<!-- loaded below -->
</form>
</div>
another request that fill my form data
#csrf
<div class="form-row">
<div class="form-group col-md-6">
<input type="hidden" name="request_type" value="{{RegisterTypesNames::Faculty}}">
<label>University</label>
<select name="university" class="custom-select" id="university{{$action}}">
<option selected value="1">University of Cansas</option>
</select>
</div>
<div class="form-group col-md-6">
<label>Faculty</label>
<input type="text" class="form-control" name="faculty" id="faculties{{$action}}">
</div>
<div class="form-group col-md-6">
<label>Init</label>
<input type="text" class="form-control" name="short_name" id="short_names{{$action}}">
</div>
</div>
<button type="submit" class="btn btn-primary"><span class="fa fa-save"></span> Save</button>
And jquery code
$('#update_form').submit(function (e) {
$.ajax({
url: '/update_data',
type: "POST",
data: $('#update_form').serialize(),
dataType: "json",
success: function (data) {
console.log(data.result);
}
});
e.preventDefault();
});
Note: I use multiple partial forms like this all others works fine
I can't submit the form even though I used preventDefault, (page refreshed and doesn't take any action)
Interpretation: the statements "page refreshed" and "used preventDefault" indicate that the problem is that the code inside the $("#id").submit( is not firing and the page's default submit is kicking in hence the "page refreshed".
As the jquery event is not firing, it likely means that the HTML does not exist when the script runs. This can usually be handled by putting in a doc.ready; OP indicates that it's already in doc.ready.
The alternative is to use event delegation. Though it's not clear if the code is running before the HTML is generated or if the HTML is added after (subtle difference).
The solution for event delegation is to use:
$(document).on("submit", "#update_form", function(e) {
e.preventDefault();
$.ajax({...
});
Related
I'm building a support contact form where the user can upload files. The file upload is managed using AJAX: the user can upload the files, then submit the form at their convenience. The current layout that works is, however, not aesthetic: the upload input is below the form submit button.
I read about nested forms and the new form attribute and I thought this would do the trick:
<form action="" method="post" enctype="multipart/form-data" id="main-form">
...
<form action="/upload_file_ajax.php" method="post" id="file-upload-form">
<div class="form-group row mb-3 mb-3">
<label class="col-sm-3 col-lg-3 col-form-label" for="file"><?php echo $label['attach-file']; ?></label>
<div class="col-sm-8 col-lg-7">
<input class="form-control custom-file-input" name="file" id="file" type="file" form="file-upload-form" />
</div>
</div>
</form>
<div class="form-group row">
<div class="col-4 offset-3">
<button type="submit" name="submit" class="btn btn-outline-success" form="main-form"><?php echo $label['submit-button']; ?></button>
</div>
</div>
</form>
I have added the form attribute to every input and button. However, the inner form ("file-upload-form") won't submit at all when I add the file.
Could it be because this is an auto-submit input, i.e. the Javascript triggers the AJAX when the file is selected? This is the trigger line:
$('#file-upload-form').on('change', function(e){
...
As soon as I move the nested form below the closing </form> tag of the main form, it works.
If the aesthetic layout can be achieved in any other way, e.g. the file upload input can appear above the Submit button without nesting the forms, please let me know.
EDIT: This is the revised Javascript that takes care of the file upload via AJAX. I have removed the inner form tags as advised but the input still won't submit.
$(function(){
// listen for input changes (when a file is selected)
$('#file-upload-input').on('change', function(e){
//var formData = new FormData();
// file has been selected, submit it via ajax
$.ajax({
type: 'POST',
url: "/upload_file_ajax.php",
data: new FormData(this),
cache: false,
contentType: false,
processData: false,
success: function(data){
// the upload_file_ajax.php endpoint returns the file name and a status message for the uploaded file
console.log(data.filename, data.message);
// we then inject these into the main data form
var $hiddenInput = $('<input type="hidden" name="uploads[]" value="'+data.filename+'">');
$('#main-form').append($hiddenInput);
// show a thumbnail maybe?
var $thumbnail = $('<img src="/uploaded_files/'+data.filename+'" width="40" height="40" />');
$("#preview").append($thumbnail);
$("#status").html(JSON.stringify(data.message));
// reactivate file upload form to choose another file
$('#file-upload-input').val('');
},
error: function(){
console.log("error");
}
});
});
});
This is what the revised HTML looks like:
<form action="" method="post" enctype="multipart/form-data" id="main-form">
... (other inputs here)...
<div class="form-group row offset-3 mb-3">
<div class="col-12" id="preview"></div>
<div class="col-12" id="status"></div>
</div>
<div class="form-group row mb-3 mb-3">
<label class="col-sm-3 col-lg-3 col-form-label" for="file"><?php echo $label['attach-file']; ?></label>
<div class="col-sm-8 col-lg-7">
<input class="form-control custom-file-input" name="file" id="file" type="file" id="file-upload-input" form="file-upload-form" />
</div>
</div>
<div class="form-group row">
<div class="col-4 offset-3">
<button type="submit" name="submit" class="btn btn-outline-success" form="main-form"><?php echo $label['submit-button']; ?></button>
</div>
</div>
</form>
Here is how I solved my problem. I found the answer here, on SO, but can't find the link to the post any more.
The problem with uploading a file independently, without submitting the form or without having <form>...</form> tags, is that FormData(); does not contain the file as it does when the <form>...</form> tags are present. So, you need to append the file to it.
Here is my entire jQuery code that takes care of the file upload. On success, it creates additional form input tags containing the uploaded files info, so that I can submit them together with the form. It also creates a thumbnail for each uploaded image, and a Delete button next to the input in case the user changes their mind.
$('#file-upload-input').change(function(){
var file_data = $('#file-upload-input').prop('files')[0];
var form_data = new FormData();
// pass the file itself – needed because the input is submitted without <form> tags
form_data.append('file', file_data);
// pass website language variable to the PHP processor to load the correct language file
form_data.append('lang', '<?php echo $lang; ?>');
$.ajax({
url: "/ajax_upload_file.php",
type: "POST",
data: form_data,
cache: false,
contentType: false,
processData: false,
success: function(data){
// the upload_file_ajax.php endpoint returns the file name and a status message for the uploaded file
console.log(data.filename, data.message);
// we then inject these into the main data form
var $hiddenInput = $('<div class="input-group mb-1"><input class="form-control" readonly type="text" name="uploads[]" value="'+data.filename+'" /><input type="button" name="delete_'+data.filename+'" id="delete_'+data.filename+'" value="Delete" class="delete btn btn-outline-danger ms-2" /></div>');
$('#uploaded_files').append($hiddenInput);
// show a thumbnail if the uploaded file is an image
var $thumbnail = $('<img src="/uploaded_files/'+data.filename+'" height="75" id="img_'+data.filename+'" class="me-1" />');
$("#preview").append($thumbnail);
// print a status message returned from the PHP processor
$("#status").html(data.message);
// reactivate file upload form to choose another file
$('#file-upload-input').val('');
},
error: function(){
console.log("error");
}
});
});
This is the relevant HTML. It contains divs for the inputs containing the uploaded files names, for the thumbnails (called "preview"), and for the status message returned from the PHP script.
<div class="form-group row offset-2 mb-3">
<div class="col-sm-8 col-lg-7" id="uploaded_files">
</div>
</div>
<div class="form-group row offset-2 mb-3">
<div class="col-12" id="preview"></div>
</div>
<div class="form-group row offset-2 mb-3">
<div class="col-12" id="status"></div>
</div>
<div class="form-group row mb-3 mb-3">
<label class="col-sm-3 col-lg-2 col-form-label" for="file"><?php echo $label['attach-file']; ?></label>
<div class="col-sm-8 col-lg-7">
<input class="form-control custom-file-input" name="file" type="file" id="file-upload-input" />
</div>
</div>
I am currently developing a web application using ASP.NET Core v2.2.
I'm having troubles in one of my forms where I have several "multiselect" (using bootstrap-select selectpicker). The problem is that the form doesn't allow users to not select any options in a multiselect before being submitted.
Here's an example of one of my multiselects that I'd like to be "optional" :
<form asp-controller="Home" asp-action="Index" method="post" role="form" id="bsForm">
<div class="row row-mb-2">
<div class="col col-sm-4">
<label class="col-form-label" style="float:left">Product :</label>
</div>
<div class="col">
<select asp-for="product.ProductId"
class="form-control selectpicker" multiple data-live-search="true"
style="display: initial !important"
asp-items="#(new SelectList(ViewBag.ListOfProducts,"ProductId","ProductName"))">
<option data-hidden="true"></option>
</select>
</div>
</div>
<div class="row">
<input type="submit" value="Submit" class="btn btn-primary" style="width:25%" />
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
$('.selectpicker').selectpicker();
});
</script>
When I'm looking into it (by inspecting the element), it looks like there is some kind of validator running and forbidding users to let these selectpickers not selected.
If you have any idea of how to disable this validator (or just the fact of forcing users to select a value), I would be grateful.
Thanks in advance !
Edit :
So I've found something that does the trick. I think that by doing so I removed every existing validations conditions. Here's what I did :
<script type="text/javascript">
$(document).ready(function () {
$('#bsForm').validate({
rules: {
}
});
});
</script>
Since this is kind of a butchering solution, I'm still looking for a better solution.
jsfiddle demo: https://jsfiddle.net/zpufky7u/1/
I have many forms on the site, which was working fine, but just suddenly angular is binding all the forms with class="ng-pristine ng-valid"
Is this a setting or what can cause angular to auto-bind forms?
I'm using angular version: angular#1.4.7
Following is my form, as you can see there is no model inside form
<form name="app_bundle_notification_type" method="post">
<div class="row">
<div class="col-sm-8">
<div class="form-group">
<div class="checkbox">
<label class="required">
<input type="checkbox" id="app_bundle_notification_type_isNewsletter" name="app_bundle_notification_type[isNewsletter]" required="required" value="1" checked="checked">
Yes, I would like to receive email newsletter for new deals, coupons and news.
</label>
</div>
</div>
</div>
</div>
<div class="row m-y-1">
<div class="col-sm-12">
<button type="submit" class="btn btn-success">Save</button>
</div>
</div>
<input type="hidden" id="app_bundle_notification_type__token" name="app_bundle_notification_type[_token]" class="form-control" value="b-_qAF6LHFy_GtPlsFG3iguhVXfGsj38TXm22Ke8j0k">
</form>
Angular app.js
define(['angular'], function() {
var app = angular.module("myApp", []);
app.init = function () {
angular.bootstrap(document, [app.name]);
};
return app;
});
So far I found the issue, if you do angular.bootstrap(document, [app.name]); then it is binding the form. it was not causing this issue before.
Presuming you are using a form tag around your form, Angular automatically adds those classes to each ng-model inside your form.
This allows you much more control over the elements inside your form to perform any validation or logic you want your form to capture or enforce before submitting.
Much of it is listed in the docs here
https://docs.angularjs.org/api/ng/directive/form
For this reason, Angular prevents the default action (form submission
to the server) unless the <form> element has an action attribute
specified.
New version accepts empty action="", check release version at https://github.com/angular/angular.js/pull/3776
Seems there are a ton of answers to nearly identical questions, but I can't seem to solve this. Please forgive me if you've seen this a thousand times:
I have a form I need to submit using ajax, but I can't get it to do it properly. It needs to submt, and not refresh (as you'd expect), but it doesn't seem to matter what I do, all I can get it to do is append the POST to the current URL of the page. I've stripped the form down to the bare minimum, and am still getting this result, so I must be doing something really wrong. Any help is appreciated, thanks!
<html>
<body>
<form class="form horizontal" id="logForm">
<fieldset>
<div class="control-group">
<div style="float: left">
<label for="from">Start Date: </label>
<div class="controls">
<input type="text" id="from" name="from" />
</div>
<label for="to">End Date:</label>
<div class="controls">
<input type="text" id="to" name="to" />
</div>
</div>
</div>
</fieldset>
<div class="form-actions">
<button type="submit" class="btn btn-primary" id="subButton" style="float: left">Search!</button>
</div>
</form>
<script>
$("#logForm").submit(function() {
$.ajax({
url: 'logQuery.php',
type: 'get',
dataType: 'json',
data: $('form#logForm').serialize(),
success: function(html) {
alert('worked good');
return false;
}
});
});
</script>
</body>
</html>
Change your script add ready and return false on proper line. You return false when asynchronus operation is done which may be after the function returns. That is why you don't prevent the standard behaviour of submit event.
Return should be inside submit() function.
Hint:
You don't need to use form#logForm because there is only one element with id=logForm (it should be at least) #logForm is enough.
Also always use document.ready when you binding events to elements. This will make you sure that all elements on site are loaded so you can bind events to them.
You can use also preventDefault() but return false is good too.
$(function (){
$("#logForm").submit(function() {
$.ajax({
url: 'logQuery.php',
type: 'get',
dataType: 'json',
data: $('form#logForm').serialize(),
success: function(html) {
alert('worked good');
}
});
return false;
});
});
I have this form:
<div class="row border-tb">
<form id="test-form" action="/test/insert" method="post" class="form-inline offset4 span16">
<div class="box-suggest span13 border-tb">
<input type="text" name="test" value="" id="test" class="span13" placeholder="proviamo con il test"/>
</div>
<button style="margin-left: 5px;" id="send-button" type="submit" class="btn"> <i class="icon-plus"></i> </button>
</form>
</div>
and this mootools event for capture keyup:
$('test').addEvent("keyup",function(event){
event.stop();
alert("Why after this alert redirect on url: test/insert ??????");
})
My problem is that event.stop() doesn't prevent form submit when I press ENTER key.
I have try also event.stopPropagation() and event.preventDefault() but nothing. It always redirect on url: "test/insert" when I press ENTER key.
Why?
That's because the event is fired on keydown as well, and then a submit event is fired on the form.
Try to add this:
$('test-form').addEvent("submit",function(event){
event.stop();
return false;
});
==================
Edit
The above will prevent all form submitions, since this is probably not what you're after, here's a better simpler solution:
$('test').addEvent("keydown",function(event){
event.stop();
alert("Why after this alert redirect on url: test/insert ??????");
return false;
})
I did not write it before since you might actually need the key UP event and not DOWN, but this just makes more sense.