Form is being Submitted every time The button is clicked - javascript

I am having a form in which I am saving 2 files and a field. The problem I am facing is every time I click the submit button the form is getting submitted. Although The text field is resetting, the file still consists the value of previous record. How to reset the file here once the form is submitted.
HTML
<form id="formOrder" autocomplete="off" method="POST" enctype="multipart/form-data">
<div class="row row-sm">
<div class="col-lg-8">
<div class="row row-sm">
<div class="col-lg-6">
<div class="input-group mb-4">
<input aria-label="Invoice ID" id="invoiceId" name="invoiceId" class="form-control" placeholder="Invoice ID" type="text">
<span class="text-danger"></span>
</div>
</div>
</div>
</div>
<div class="col-lg-4">
<div>
<div class="input-group mb-3">
<div class="input-group file-browser">
<input id="imageLabel" type="text" class="form-control browse-file" placeholder="Select Order Image" readonly>
<label class="input-group-btn">
<span class="btn btn-default">
Browse <input type="file" name="image[]" id="orderImage" style="display: none;" multiple>
</span>
</label>
</div>
<div class="orderImagePreview">
</div>
</div>
</div>
</div>
</div>
<div class="form-group mb-0 mt-3 justify-content-end">
<div>
<input type="submit" id="_add" name="_add" class="btn btn-primary btn-size" value="Add"/>
</div>
</div>
</form>
JQUERY
// BUTTON CLICK SUBMISSION
$(document).ready(function(e){
$("#_add").click(function(){
$("#formOrder").on('submit', function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: '../order/add.php',
data: new FormData(this),
dataType: 'json',
contentType: false,
cache: false,
processData:false,
async: false,
autoUpload: false,
success: function(response){
$('.statusMsg').html('');
if(response.status == 1){
$('#formOrder')[0].reset(); //FORM TO RESET AFTER SUBMISSION
$('.statusMsg').html('<p class="alert alert-success">'+response.message+'</p>');
alert('received');
$('.orderImagePreview').empty();
document.getElementById('#orderImage').value= null; //TO MAKE THE IMAGE LABEL EMPTY
}else{
$('.statusMsg').html(alert(response.message));
}
$('#formOrder').css("opacity","");
$(".submit").removeAttr("disabled");
}
});
});
});
});
// Multiple images preview in browser
$(function() {
var imagesPreview = function(input, placeToInsertImagePreview) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
}
reader.readAsDataURL(input.files[i]);
}
}
};
$('#orderImage').on('change', function() {
imagesPreview(this, 'div.orderImagePreview');
$( 'div.orderImagePreview' ).empty();
});
});
$('#orderImage').on("change", function(){
var input = document.getElementById ("imageLabel");
var imageCount = $(this)[0].files.length;
if(imageCount > 0){
input.placeholder = imageCount+" Image Attached";
}else{
input.placeholder = "Select Order Image";
}
});
Where I am making the mistake? The debugging should be to reset the form with file or the method of form submission? Thanks in Advance.

$("#_add").click(function(){
$("#formOrder").on('submit', function(e){
Just create a submit handler when the document loads.
Don't add it when the button is clicked.

Related

How to store imported files through input in a list temporary and then pass the list to post request using Javascript or jQuery?

I want to use this list because before submitting I might remove a few and add more files to the list. When I use the input to get the files it has only the last imported files, not the previous ones but I want to preserve the previous ones as well cause I want to add or subtract images or pdf files to list before submission.
HTML Code:
//<form method="POST" id="medical_record_form" enctype="multipart/form-data" '>
<div class="card">
<div class="card-body">
<div class="row form-row">
<div class="col-12 col-md-12">
<div class="form-group">
<label>Title</label>
<input type="text" name="title" id="title" class="form-control">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Medical Documents</label>
<div class="upload-img">
<div class="change-photo-btn">
<span><i class="fa fa-upload"></i> Upload File</span>
<input id="medical_documents" name="medical_documents"
type="file" multiple accept="image/*,.pdf"
onchange="readURL(this);" class="upload">
</div>
<small class="form-text text-muted">All Image Types Are Allowed, Plus
PDF Files</small>
</div>
</div>
<div class="upload-wrap" id="documets_wrapper">
<!-- the images preview goes here which is handled by javascript -->
</div>
</div>
</div>
</div>
</div>
<div class="submit-section">
<button type="submit" id="medical_submit_button" class="btn btn-primary submit-btn">Save
Changes</button>
</div>
</form>
Javascript code:
'''
// Fields
const medicalForm = document.getElementById('medical_record_form');
const title = document.getElementById('title');
const medicalDocuments = document.getElementById('medical_documents');
var filesList = [];
function readURL(input) {
if (input.files && input.files[0]) {
for (let i = 0; i < input.files.length; i++) {
filesList.push(event.target.files[i]); // not working
var tempHtml = '<div class="upload-images" id="image_' + i + '">' +
'<img src="' + URL.createObjectURL(event.target.files[i]) + '" alt="Upload Image">' +
'<i class="far fa-trash-alt"></i>' +
'</div>';
$('#documets_wrapper').append(tempHtml);
}
}
}
$("#medical_submit_button").on('click', function () {
medicalForm.addEventListener('submit', (e) => {
e.preventDefault();
const formData = new FormData();
formData.append('csrfmiddlewaretoken', theToken);
formData.append('title', title.value);
formData.append('medical_documents', filesList);
$.ajax({
type: 'POST',
url: addUrl,
contentType: false,
// contentType: 'multipart/form-data', // tried this one also
processData: false,
data: formData,
success: function (response) {
console.log('value of response');
console.log(response);
},
error: function (error) {
console.log('error: ', error);
},
cache: false,
contentType: false,
processData: false,
});
})
})
'''

How to submit multiple forms in single submit

I have the following form created in my HTML, this will be submitted to "url 'submitrecord'". This will work fine for single entry per HTML. How can I add multiple entries of this type and submit at once.
Code:
<form method='POST' action="{% url 'submitrecord' %}">
<div class="row">
<div class = "col-md-1 form-group">
<input type="text" class="form-control" name="EntryNo" placeholder="EntryNo"/>
</div>
<div class = "col-md-2 form-group">
<input type="text" class="form-control" name="MedicineName" placeholder="MedicineName"/>
</div>
<button type="submit" class="btn btn-default">Done</button>
</div>
</form>
I found this answer but still it isnot sending the request to my URL.
<script>
$(document).ready(function(){
var called = 0;
ajax_recaller = function(forms){
$.ajax({
type: "POST",
data: forms[called].serialize(),
url: forms[called].attr('action'),
success: function(data) {
called++;
if(called < forms.length) {
ajax_recaller(forms);
} else {
called=0; // set called value to 0 again
alert('All forms has been submitted!');
}
}
});
}
$(document).on('click','.submitforms',function(){
var x=0;
$('.ajax_form').each(function(){
forms[x] = $(this);
x++;
});
ajax_recaller(forms);
});
});
</script>

UPDATE form modal bootstrap in codeigniter using AJAX

Been struggling with this for about few hours. I'm attempting to have a modal drop down (Twitter bootstrap modal) that contains a form to choose a category of user. This is built in CodeIgniter. But when i try to save form's value using AJAX, the SUCCESS function won't run without alert(). I'm sorry for my bad grammar, i hope you can understand what i mean.
i need for your help...
view (kasir_halaman.php):
<div id="editModal" class="modal fade" role="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title"><span class="glyphicon glyphicon-plus"></span> Ubah Kasir</h3>
</div>
<div class="modal-body">
<form action="#" id="editform" method="post" enctype="multipart/form-data">
<div class="form-group">
<label>Nama</label> <span class="error" id="report1"></span>
<input type="text" id="editnama" name="nama" class="form-control" maxlength="100" required>
</div>
<div class="form-group">
<label>E-mail</label>
<input type="email" id="editemail" name="email" class="form-control" maxlength="150" required>
</div>
<div class="form-group">
<label>Kategori</label>
<select class="form-control" name="kategoripetugas" id="editkategori" required>
<option value=""> -- Pilih Kategori -- </option>
<option value="1">Admin</option>
<option value="2">Kasir</option>
</select>
</div>
<button type="submit" class="btn btn-primary" style="width:100%;">Simpan</button>
</form>
</div>
</div>
</div>
</div>
controller (kasir.php):
public function updatePetugas($id)
{
$nama_petugas = $this->input->post('nama');
$email_petugas = $this->input->post('email');
$kategori_petugas = $this->input->post('kategoripetugas');
$data = array('nama'=>$nama_petugas, 'email'=>$email_petugas, 'kategori'=>$kategori_petugas);
$update = $this->Crud->update(array('idpetugas'=>$id), 'petugas', $data);
if($update){
echo 1;
}else{
echo 2;
}
}
javascript (petugas.js) :
$(document).ready(function(){
var check1=0; var id;
$("#nama").bind("keyup change", function(){
var nama = $(this).val();
$.ajax({
url:'kasir/cekData/kasir/nama/'+nama,
data:{send:true},
success:function(data){
if(data==1){
$("#report1").text("");
check1=1;
}else{
$("#report1").text("*nama petugas sudah terpakai");
check1=0;
}
}
});
});
$(".edit").click(function(){
id = $(this).attr('id');
$.ajax({
url:'kasir/getData/'+id,
data:{send:true},
success:function(data){
$("#editnama").val(data['nama']);
$("#editemail").val(data['email']);
$("#editkategori").val(data['kategori']);
}
});
});
$("#editform").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url:'kasir/updatePetugas/'+id,
data:formData,
type:'POST',
contentType: false,
processData: false,
success:function(data){
if(data==1){
$("#editModal").hide();
window.location.reload(true);
}else if(data==2){
alert('gagal');
}
}
});
alert("success!"); // if i remove this alert, the success function won't run or executed
});
});
you can solve this a few ways, what is actually happening is that you are submitting the data via ajax as well as submitting the form itself.
using e or the event
$("#editform").submit(function(e){
e.preventDefault();
or by returning false on submit
});
//alert("success!"); we can comment this out because it will work now without the alert holding the page
return false;
});
in either case you can remove your alert.

form submitting twice via ajax POST

Inserting into mysql using php file called via AJAX. Before insert statement php code performs select query to find duplicate records and continue to insert statement.
Issue: When calling php file from ajax. it executed twice and getting response as duplicate record.
well i tried error_log from insert function its called twice.
Trigger point of form validation
$("#load-modal").on("click","#addcountryformsubmitbtn",function(e){
e.preventDefault();
var $form = $("#addcountryform"), $url = $form.attr('action');
$form.submit();
});
This is how form submitted after validation:
}).on('success.form.bv', function(e){
e.preventDefault();
var $form = $("#addcountryform"), $url = $form.attr('action');
$.post($url,$form.serialize()).done(function(dte){ $("#load-modal").html(dte); });
});
using bootstrapvalidator, Core PHP, mysqli, Chrome Browser.
Actual JS:
$(document).ready(function() {
$php_self_country="<?php echo $_SERVER['PHP_SELF']."?pg=countrycontent"; ?>";
$("#country-content").load($php_self_country,loadfunctions);
$("#country-content").on( "click", ".pagination a", function (e){
e.preventDefault();
$("#country-loading-div").show();
var page = $(this).attr("data-page");
$("#country-content").load($php_self_country,{"page":page}, function(){
$("#country-loading-div").hide();
loadfunctions();
});
});
$("#country-content").on("click","#closebtn",function(e){
e.preventDefault();
$("#country-content").load($php_self_country,loadfunctions);
});
});
function loadfunctions(){
$("[data-toggle='tooltip']").tooltip();
$("#country-content").on("click","#addcountrybtn, #addcountrylargebtn",function(e){
e.preventDefault();
$.ajax({
url: $php_self_country,
type: "POST",
data: { 'addcountry':'Y' },
dataType: "html",
cache: false
}).done(function(msg){
$("#load-modal").html(msg);
$("#load-modal").modal('show');
$('input[type="radio"]').iCheck({ checkboxClass: 'icheckbox_minimal', radioClass: 'iradio_minimal' });
modalvalidation();
}).fail(function() {
$("#load-modal").html( "Request Failed. Please Try Again Later." );
});
});
$("#country-content").on("click",".tools a",function(e){
e.preventDefault();
var recordid = $(this).attr("record-id");
$.ajax({
url: $php_self_country,
type: "POST",
data: { 'modifycountry':recordid },
dataType: "html",
cache: false
}).done(function(msg){
$("#load-modal").html(msg);
$("#load-modal").modal('show');
$('input[type="radio"]').iCheck({ checkboxClass: 'icheckbox_minimal', radioClass: 'iradio_minimal' });
modalvalidation();
}).fail(function() {
$("#load-modal").html( "Request Failed. Please Try Again Later." );
});
});
$("#load-modal").on("click","#addcountryformsubmitbtn",function(e){
e.preventDefault();
var $form = $("#addcountryform"), $url = $form.attr('action');
$form.submit();
});
$("#load-modal").on("hide.bs.modal", function () {
window.location.href=$php_self_country_pg;
});
}
function modalvalidation(){
$('#addcountryform').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
[-------Validation part comes here----------]
}
}).on('success.form.bv', function(e){
e.preventDefault();
var $form = $("#addcountryform"), $url = $form.attr('action');
$.post($url,$form.serialize()).done(function(dte){ $("#load-modal").html(dte); });
});
}
HTML
this html is called on button click addcountrybtn via AJAX and write in to div load-modal which is in base html file.
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title"><i class="fa fa-exchange"></i> <?php echo COUNTRYLABEL; ?></h4>
</div>
<div class="modal-body">
<form role="form" method="POST" action="self.php" name="addcountryform" id="addcountryform" class="form-horizontal">
<div class="form-group">
<div class="col-xs-3">
<label for="countryname" class="pull-right">Country Name</label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="countryname" placeholder="Enter Country Name">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-3">
<label for="crncyname" class="pull-right">Currency Name</label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="crncyname" placeholder="Enter Currency Name">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-3">
<label for="crncycode" class="pull-right">Currency Code</label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="crncycode" placeholder="Enter Currency Code">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-3">
<label for="forrate" class="pull-right">Foreign Currency Rate<?php echo isset($icon)?$icon:''; ?></label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="forrate" placeholder="Enter Foreign Currency Rate.">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-3">
<label for="taxpercent" class="pull-right">Tax %</label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="taxpercent" placeholder="Enter Tax Percentage">
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer clearfix">
<button type="button" class="btn btn-danger pull-right" id="addcountryformsubmitbtn">Add</button>
</div>
</div>
Note:- in Database point of view code works as expected.
Couple of things that I have seen could possibly be the cause.
If you are using IE, I have seen that perform a GET immediately before doing a POST (to the same URL, with the same data being sent over), so it could be worth trying to check for that on your server (and ignore the GET)
Something else it maybe to add the following to the end of your button click events after the AJAX call (actually, normally I'd put the first line at the top with the prevent default, and the return statement obviously goes very last)...
e.stopImmediatePropagation();
return false;

Repeating data after form submit

I have 4 links ( view car, hand car, retrieve car and add car). Every link is load by Ajax. The problem is in (add car), the first time I click submit the data gets recorded in the database once ... when I click (view car) and go back to (add car) and submit the form again it adds the data to the database 3 times. Also when I press (view car) and back to add car and submit the from again it records the data 6 times.
ajax.js
$(document).ready(function(){
$('#viewCar').click(function(){
$("#show").load('view');
});});//end click
$(document).ready(function(){
$('#handCar').click(function(){
$("#show").load('handcar');
});//end load
});//end click
$(document).ready(function(){
$('#retrieveCar').click(function(){
$("#show").load('retrieve');
});//end load
});//end click
$(document).ready(function(){
$('#addCar').click(function(){
enter code here $("#show").load('add');
});//end load
});//end click
$(document).ready(function(){
$("#submit").click(function(e)
{
e.preventDefault();
var postData = $('#cForm').serialize();
var formURL = 'car/add';
var LT = $("#LT").val();
var LN = $("#LN").val();
if(LT == ''|| LN == '')
{
console.log('error some form is empty !!');
}
else
{
$.ajax({
url : formURL,
type: "POST",
data : postData,
success:function()
{
$('#cForm').find("input[type=text]").val(" ");
console.log('saved !!');
}
});
}
return null;
}); //end click
}); //end of ready
car_links.html
<div class="container">
<ul class="ul">
<li class="li"><a id="viewCar" href="#" >view cars</a></li>
<li class="li"><a id="handCar" href="#">hand car</a></li>
<li class="li"><a id="retrieveCar" href="#">retrieve car</a></li>
<li class="li"><a id="addCar" href="#">add a car</a></li>
</ul>
car_add.html
<div class="col-md-4 col-md-offset-4">
<form id="cForm" class="form-horizontal" >
<?php echo validation_errors(); ?>
<legend>add a new car</legend>
<div class="form-group">
<label class="col-sm-5 control-label" for="LN">License #:</label>
<div class="col-sm-13">
<input class="form-control form-size" type="text" id="LN" name="LN" value="" /></li>
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label" for="LT">License Ltr:</label>
<div class="col-sm-13">
<input class="form-control form-size" type="text" id="LT" name="LT" value="" />
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label" for="Model">Model:</label>
<div class="col-sm-13">
<select class="form-control form-size" name="Model">
<option value="Toyota"> Toyota</option>
<option value="Audi"> Audi</option>
<option value="Hundai"> Hundai</option>
<option value="BMW"> BMW</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label" for="Year"> Year:</label>
<div class="col-sm-13">
<select class="form-control form-size" name="Year">
<option value="2010"> 2010</option>
<option value="2014"> 2014</option>
</select>
</div>
</div>
<div class="form-actions btn-action">
<button class="btn btn-success" id="submit" value="save" type="button" name="submit">save</button></li>
<button class="btn btn-danger" type="reset" name="reset"> Reset </button></li>
</div>
</form>
</div>
For starters you have each click function in its own .ready function. The .ready function is initiated when the page is loaded. If you want the function to load only on a click then you need to place the click function into a function like this.
$(function() {
$('#viewCar').click(function() {
$("#show").load('view');
});
$('#handCar').click(function() {
$("#show").load('handcar');
});
$('#retrieveCar').click(function() {
$("#show").load('retrieve');
});
$('#addCar').click(function() {
$("#show").load('add');
});
$("#submit").click(function(e) {
e.preventDefault();
var postData = $('#cForm').serialize();
var formURL = 'car/add';
var LT = $("#LT").val();
var LN = $("#LN").val();
if(LT == ''|| LN == '') {
console.log('error some form is empty !!');
} else {
$.ajax({
url : formURL,
type: "POST",
data : postData,
success:function() {
$('#cForm').find("input[type=text]").val(" ");
console.log('saved !!');
}
});
}
return null;
});
}
If that doesn't work or is not what you wanted please leave me a comment.

Categories

Resources