Form Submit Multiple Time On Multiple Click Of Button - javascript

I am trying to create exception by submiting form using AJAX and exception is also created when button
<button type="button" onclick="submitForm()" class="btn btn-s-md btn-primary saveButton mb-10 "><i class="fa fa-save fa-fw"></i>Save</button>
is clicked and onclick the function function submitForm() is executed.
The problem is that on multiple click of button the form is submitted as well which i don't want.
Below is my form
<form asp-action="CreateException" asp-controller="Attorney" method="post" role="form" enctype="multipart/form-data" id="attorneyExceptionForm">
<div class="panel panel-default">
<div class="panel-body">
<div class="row">
<div class="col-md-3 col-lg-3 col-sm-12">
<div class="form-group">
<label asp-for="Description" class="control-label ">Description<span class="requAstrik">*</span></label>
<input asp-for="Description" class="form-control " />
<span asp-validation-for="Description" class="text-danger"></span>
</div>
</div>
<div class="col-md-3 col-lg-3 col-sm-12">
<div class="form-group">
<label asp-for="Exception" class="control-label ">Exception<span class="requAstrik">*</span></label>
<select id="slctExceptionA" class="form-control select2" asp-for="Exception" style="color: #444 !important;width:100%;" asp-items="#(new SelectList(#ViewBag.ExcsList, "ExcId", "ExcDescription" ))"></select>
<span id="attorneyExceptionError" asp-validation-for="Exception" class="text-danger"></span>
</div>
</div>
</div>
</div>
</div>
<div class="form-group">
<button type="button" onclick="submitForm()" class="btn btn-s-md btn-primary saveButton mb-10 "><i class="fa fa-save fa-fw"></i>Save</button>
</div>
</form>
Below is my js function
<script>
function submitForm() {
debugger;
var datastring = $("#attorneyExceptionForm").serialize();
var validForm = $("#attorneyExceptionForm").valid();
if (!validForm) { return false; }
$.ajax({
type: "POST",
url: "/Attorney/CreateAttorneyException",
data: datastring,
dataType: "json",
success: function (data) {
debugger;
if (data.success.Result) {
debugger;
$("#myModal5").modal('hide');
var grid = $("#AttorneyExceptionGrid").dxDataGrid('instance');
grid.refresh();
showNotification("Exception saved successfully", "success");
}
else {
debugger;
showNotification(data.success.MessageBody + " is required ", "warning");
}
},
error: function (data) {
debugger;
showNotification("Please input the required field", "warning");
}
});
}
</script>

You can disable the button in the first click and enable it again when the ajax response arrive.
<button type="button" onclick="submitForm(this)" class="btn btn-s-md btn-primary saveButton mb-10 "><i class="fa fa-save fa-fw"></i>Save</button>
function submitForm(e) {
$(e).prop("disabled", true);
//more code
}
And enable it again in the success or error ajax method
$(e).prop("disabled", false);

Related

HTML required attribute not working with AJAX submission

HTML required attribute not working with AJAX submission
I have created a model Form and set its input field to require attribute but its not working with ajax
<div class="modal fade hide" id="ajax-book-model" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="ajaxBookModel">Add New Machine</h5>
<!-- <button type="reset" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> -->
<button type="button" class="btn-close" data-dismiss="modal" aria-label="Close" onClick="window.location.reload();">
</div>
<div class="modal-body">
<form action="javascript:void(0)" id="addEditBookForm" name="addEditBookForm" class="form-horizontal" method="POST">
<input type="hidden" name="id" id="id">
<input type="hidden" name="user_id" id="user_id" value="{{ Auth::user()->id }}">
<div class="row">
<div class="col-sm-12 col-md-4">
<div class="form-group">
<label>Name</label>
<input type="text" id="machine_name" name="machine_name" class="form-control form-control-sm" placeholder="Enter Machine Name" required>
<span class="text-danger">{{ $errors->first('machine_name') }}</span>
</div>
</div>
<div class="col-sm-12 col-md-4">
<div class="form-group">
<label>IOT Device ID</label>
<input type="text" id="iot_device_id" name="iot_device_id" class="form-control form-control-sm" placeholder="Enter IOT Device ID" required>
</div>
</div>
<div class="col-sm-12 col-md-4">
<div class="form-group">
<label>Local device ID</label>
<input type="text" id="local_device_id" name="local_device_id" class="form-control form-control-sm" placeholder="Enter Local Device ID" required>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-sm btn-gradient-danger mb-2" data-dismiss="modal" onClick="window.location.reload();">Close</button>
<button type="submit" id="btn-save" value="addNewBook" class="btn btn-sm btn-gradient-danger mb-2">Save</button>
</div>
</form>
</div>
</div>
</div>
and this is ajax code
i just want to run simpal html required field validation with ajax
$('body').on('click','#btn-save', function (event){
event.preventDefault();
var id = $("#id").val();
var user_id = $("#user_id").val();
var machine_name = $("#machine_name").val();
var iot_device_id = $("#iot_device_id").val();
var local_device_id = $("#local_device_id").val();
$("#btn-save").html('Please Wait...');
$("#btn-save"). attr("disabled", true);
// ajax
$.ajax({
type:"POST",
url: "{{ url('add-update-piezometer') }}",
data: {
id:id,
user_id:user_id,
machine_name:machine_name,
iot_device_id:iot_device_id,
local_device_id:local_device_id,
},
dataType: 'json',
success: function(res){
window.location.reload();
$("#btn-save").html('Submit');
$("#btn-save"). attr("disabled", false);
}
});
});
i just want to run required field validation with ajax i could not find any solution .
Try changing your btn click event to form submit event.
$('body').on('submit', '#addEditBookForm', function (event) {
event.preventDefault();
var id = $("#id").val();
var user_id = $("#user_id").val();
var machine_name = $("#machine_name").val();
var iot_device_id = $("#iot_device_id").val();
var local_device_id = $("#local_device_id").val();
$("#btn-save").html('Please Wait...');
$("#btn-save").attr("disabled", true);
// ajax
$.ajax({
type: "POST",
url: "{{ url('add-update-piezometer') }}",
data: {
id: id,
user_id: user_id,
machine_name: machine_name,
iot_device_id: iot_device_id,
local_device_id: local_device_id,
},
dataType: 'json',
success: function (res) {
window.location.reload();
$("#btn-save").html('Submit');
$("#btn-save").attr("disabled", false);
}
});
});
The following should help: change to a form confirmation event instead of a Click button event. And do not forget to write this code so that the page does not reload:
event.preventDefault();

form submit refresh page

I have this code below working fine in my local PC and local Publish. But when I publish it on another PC as PC Server code below is refresh the page after I click the button log-in.
I also tried the following events e.stopPropagation(), e.stopimmediatepropagation() but it keeps refreshing the page.
JS
$("#frmVerification").on('submit', function (e) {
e.preventDefault();
var elem = $("#frmVerification");
elem.find('.loading').removeClass('hidden');
$.ajax({
url: '../Account/Verify',
data: $(this).serialize(),
type: 'get',
success: function (res) {
console.log(res);
if (res.success) {
setTimeout(function () {
window.location.replace(res.url);
}, 1000);
}
elem.find('.loading').addClass('hidden');
}
});
})
HTML
<form id="frmVerification">
<div class="card-header bg-success-origin">
<div class="card-title">
<label>Login Verification</label>
</div>
</div>
<div class="card-body">
<div class="row">
<div class="col-lg-8">
<label>Verification Code</label>
<div class="input-group input-group-sm">
<input type="text" class="form-control text-uppercase font-weight-bold" name="VerificationCode" placeholder="ENTER VERIFICATION CODE" disabled />
<span class="input-group-btn">
<button type="button" id="btnResendEmail" class="btn btn-flat rounded-right" disabled><i class="fa fa-refresh"></i></button>
</span>
</div>
</div>
<div class="pr-lg-4 pl-lg-4 col-lg-4 mt-4 text-lg-right text-center">
<button type="submit" class="form-control btn btn-success" disabled>Submit<i class="fa fa-refresh loading hidden"></i></button>
</div>
</div>
<div class="text-danger hidden" style="margin-top: 5px; margin-bottom:-20px;background: #94040b26">
<ul id="divVerificationAlert"></ul>
</div>
</div>
</form>
You Can try this.
<form id="frmVerification" onsubmit="return false">

How to return object instead of actual value on ajax call?

I am trying to do CRUD using ajax in my php application i have been successful with insert but stuck on update since i will have to send id number to next page to update data.
here is my script
$(document).ready(function(){
// When click the button.
$("[id^=get]").click(function() {
// Assigning Variables to Form Fields
var cid = $(this).val();
if(cid) {
$.ajax({
type: "post",
url: "getsingle.php",
asynch: false,
data: {
"cid": cid
},
success: function(data) {
$("#catname").val(data);
$("#tochange").html("<button id='update' type='button' class='btn btn-success'>Update</button>");
$("#categories").html("");
$("#form_category").append("<div class='form-group m-form__group row'><div class='col-lg-6'><input type='text' id='cid' class='form-control m-input' placeholder='Enter category name' value='"+$(cid)+"' name='cname'><span id='ecname' style='color: red;'> </span></div>");
}
});
} else {
$("#ecname").html("fill category name");
}
});
});
here is button i click which runs this function
<td><button value="'.$category['cid'].'" class="btn btn-primary get" id="get'.$category['cid'].'">edit </button></td>
form which will be for update data.
<div class="m-portlet">
<div class="m-portlet__head">
<div class="m-portlet__head-caption">
<div class="m-portlet__head-title">
<span class="m-portlet__head-icon m--hide">
<i class="la la-gear"></i>
</span>
<h3 class="m-portlet__head-text">
Add Categories
</h3>
</div>
</div>
</div>
<!--begin::Form-->
<form class="m-form m-form--fit m-form--label-align-right m-form--group-seperator" id="form_category" method="post" action="">
<div class="m-portlet__body">
<div class="form-group m-form__group row">
<label class="col-lg-2 col-form-label">
Category Name:
</label>
<div class="col-lg-6">
<input type="text" id="catname" class="form-control m-input" placeholder="Enter category name" name="cname">
<span id="ecname" style="color: red;"> </span>
</div>
</div>
<div class="m-portlet__foot m-portlet__no-border m-portlet__foot--fit">
<div class="m-form__actions m-form__actions--solid">
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-6">
<span id="tochange">
<button id="save" type="button" class="btn btn-success">Save</button>
</span>
<button type="reset" class="btn btn-secondary">
Cancel
</button>
</div>
</div>
</div>
</div>
<!--end::Portlet-->
</div>
</form>
<!--end::Form-->
</div>
on click edit button everything work perfect I get category name on input perfectly also my button changes from save to update, but only input cidgetting value as object not as 1,2,3 etc etc. actual id.
$("[id^=get]").click(function() {
// Assigning Variables to Form Fields
var cid = $(this).val();
if(cid){
$.ajax({
type: "post",
url: "getsingle.php",
asynch: false,
data: {
"cid": cid
},
success: function(data){
$("#catname").val(data);
$("#tochange").html("<button id='update' type='button' class='btn btn-success'>Update</button>");
$("#categories").html("");
$("#form_category").append("<div class='form-group m-form__group row'><div class='col-lg-6'><input type='text' id='cid' class='form-control m-input' placeholder='Enter category name' name='cname'></div>");
$("#cid").val(cid);
}
});
}
else{
$("#ecname").html("fill category name");
}
I have solved it instead giving value within append i gave it separately after it displays working perfectly.

JavaScript Get the closest element and input a value to the input

I have a piece of HTML that looks like this
<div id="imageContent">
<div class="row">
<div class="col-md-5 col-md-offset-1">
<div class="input-group form-group">
<input type="text" class="form-control file-src" id="file1" placeholder="File Thumb Source">
<span class="input-group-btn">
<button class="btn btn-info modal-btn" type="button" data-toggle="modal" data-target="#myModal">Select File</button>
</span>
</div>
</div>
<div class="col-md-5">
<div class="form-group">
<input class="form-control" type="text" placeholder="http://postbackurl.com"/>
</div>
</div>
</div>
</div>
Above that I have a button that looks like this
<div class="row text-center">
<div class="col-md-12">
<button type="button" class="btn btn-wd btn-info btn-fill btn" onclick="add_fields();" rel="tooltip">Add More Images</button>
</div>
</div>
Once that button is pressed I run a function to get the #imageContent div and append a new row with the same as before.
<script type="text/javascript">
function add_fields() {
var div = document.getElementById("imageContent");
div.insertAdjacentHTML('afterend','<div class="row"><div class="col-md-5 col-md-offset-1"> <div class="input-group form-group"><input type="text" class="form-control file-src" id="file1" placeholder="File Thumb Source"><span class="input-group-btn"> <button class="btn btn-info modal-btn" type="button" data-toggle="modal" data-target="#myModal">Select File</button> </span> </div> </div> <div class="col-md-5"> <div class="form-group"> <input class="form-control" type="text" placeholder="http://postbackurl.com"/> </div> </div> </div>');
}
</script>
This works as expected and adds a new row into the imageContent div.
See picture. If I click Select Image, it launches a modal window with all of my images, and when I select one, it runs this piece of js.
onInsertCallback: function (obj){
/** Populate the src **/
currentModalBtn.closest('.input-group').find('input.file-src').val(obj.src);
$('#myModal').hide();
}
The problem I am having is that it does not get the correct input area to insert the value into, and instead always updates the first element. The full js code looks like this.
$(document).ready(function() {
jQuery(document).ready(function() {
/** Keep track of which modal button was clicked. **/
var currentModalBtn;
jQuery('.modal-btn').click(function() {
currentModalBtn = jQuery(this);
});
jQuery('.laradrop').laradrop({
onInsertCallback: function(obj) {
/** Populate the src **/
currentModalBtn.closest('.input-group').find('input.file-src').val(obj.src);
$('#myModal').hide();
},
onErrorCallback: function(jqXHR, textStatus, errorThrown) {
// if you need an error status indicator, implement here
//Swal here
swal({
title: 'Error!',
text: 'An Error Occurred',
type: 'error',
showConfirmButton: false,
showCancelButton: true
});
},
onSuccessCallback: function(serverData) {
//
}
});
});
});
My question is, how can I ensure that I get the right input field that the button was clicked on to update that fields value and make sure the others stay as they were.
move var currentModalBtn; outside the ready so it is available to the callback(s)
Also have only one
$(document).ready(function() {
jQuery(document).ready(function() {
you have a mess of jQuery/$ and so on - this will likely work better:
function add_fields() {
var $div = $("#imageContent");
$div.append('<div class="row"><div class="col-md-5 col-md-offset-1"> <div class="input-group form-group"><input type="text" class="form-control file-src" id="file1" placeholder="File Thumb Source"><span class="input-group-btn"> <button class="btn btn-info modal-btn" type="button" data-toggle="modal" data-target="#myModal">Select File</button> </span> </div> </div> <div class="col-md-5"> <div class="form-group"> <input class="form-control" type="text" placeholder="http://postbackurl.com"/> </div> </div> </div>');
}
var currentModalBtn;
$(function() {
/** Keep track of which modal button was clicked. **/
$("#imageContent").on("click",".modal-btn", function() {
currentModalBtn = $(this);
});
$("#test").on("click",function() {
currentModalBtn.closest('.input-group').find('input.file-src').val("hello");
$('#myModal').hide();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="row text-center">
<div class="col-md-12">
<button type="button" class="btn btn-wd btn-info btn-fill btn" onclick="add_fields();" rel="tooltip">Add More Images</button>
</div>
</div>
<div id="imageContent">
<div class="row">
<div class="col-md-5 col-md-offset-1">
<div class="input-group form-group">
<input type="text" class="form-control file-src" id="file1" placeholder="File Thumb Source">
<span class="input-group-btn">
<button class="btn btn-info modal-btn" type="button" data-toggle="modal" data-target="#myModal">Select File</button>
</span>
</div>
</div>
<div class="col-md-5">
<div class="form-group">
<input class="form-control" type="text" placeholder="http://postbackurl.com"/>
</div>
</div>
</div>
</div>
<button type="button" id="test">
click
</button>

passing value from form to modal box in codeigniter

My view Page :
<form id="myForm" >
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="text" class="form-control datepicker pull-right" name="from_date" placeholder="From"> // want this value in my modal box
</div>
</div>
<div class="col-md-6">
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="text" class="form-control datepicker pull-right" name="to_date" placeholder="To"> // want this value in my modal box
</div>
</div>
<div class="col-md-12">
<br/>
<center><button class="btn btn-success" onclick="search_sale_return()"><i class="glyphicon glyphicon-plus"></i> Create New Stock</button></center> // on this click call the modal
</div>
</form>
JavaScript
<!-- Search sale return -->
function search_sale_return()
{
save_method = 'sale_return';
$('#form_sale_return')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('PharmacyController/search_sale_return')?>/" + 1, // bring value from database via controller in json_encode form
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="ph_name"]').val(data.from_date);
$('#modal_sale_return').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Sale return'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
Modal
<!-- Bootstrap Receptionist modal -->
<div class="modal fade" id="modal_sale_return" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">Stock</h3>
</div>
<div class="modal-body form">
<form action="#" id="form_sale_return" class="form-horizontal">
<input type="hidden" value="" name="ph_id"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Medicine Name</label>
<div class="col-md-9">
<input name="ph_name" placeholder="Medicine Name" class="form-control" type="text">
<input name="ph_clinic_id" value="<?php echo $userinfo['id']; ?>" type="hidden">
<span class="help-block"></span>
</div>
</div>
</div>
<div class="col-md-12">
<br/>
<table id="table_account" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Transaction Id</th>
<th>Patient Id</th>
<th>Ammount payed</th>
<th>Time</th>
<th>Action</th>
</tr>
</thead>
</table>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
This is my code , here i would like to get the value from form and than use it in my controller via javascript code and get json data and display it on my modal box
My problem :: on submit either i get link to controller or my modal (i wanna go to controller and from there i wanna go to modal in just one click button)
Fast example:
FORM:
<form id="myForm">
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar">
</i>
</div>
<input type="text" class="form-control datepicker pull-right" name="from_date" placeholder="From" /> // want this value in my modal box
</div>
<div class="col-md-6">
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar">
</i>
</div>
<input type="text" class="form-control datepicker pull-right" name="to_date" placeholder="To" /> // want this value in my modal box
</div>
</div>
<div class="col-md-12">
<br/>
<center>
<button class="btn btn-success" type="submit">
<i class="glyphicon glyphicon-plus">
</i> Create New Stock
</button>
</center>
// on this click call the modal
</div>
</form>
Modal:
<!-- Bootstrap Receptionist modal -->
<div class="modal fade" id="modal_sale_return" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">Stock</h3>
</div>
<div class="modal-body form">
<form action="#" id="form_sale_return" class="form-horizontal">
<input type="hidden" value="" name="ph_id"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Medicine Name</label>
<div class="col-md-9">
<input name="ph_name" placeholder="Medicine Name" class="form-control" type="text">
<input name="ph_clinic_id" value="<?php echo $userinfo['id']; ?>" type="hidden">
<span class="help-block"></span>
</div>
</div>
</div>
<div class="col-md-12">
<br/>
<table id="table_account" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Transaction Id</th>
<th>Patient Id</th>
<th>Ammount payed</th>
<th>Time</th>
<th>Action</th>
</tr>
</thead>
</table>
</div>
</form>
</div>
<div class="modal-footer">
<button type="submit" id="btnSave" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
Script:
<script>
$(function() {
$('form#myForm').on('submit',function(event) {
//get value
event.preventDefault();
var from_date = $(this).find('input[name="from_date"]').val();
var to_date = $(this).find('input[name="to_date"]').val();
//get data $_GET
$.ajax({
url: "<?php echo site_url('PharmacyController/search_sale_return')?>", // bring value from database via controller in json_encode form
type: "GET",
data: {from_date: from_date,to_date:to_date},
dataType: "JSON",
success: function(data) {
var modal = $('#modal_sale_return').modal('show');
modal.find('[name="ph_name"]').val(data.name);
modal.find('.modal-title').text('Sale return');
modal.find('#form_sale_return').trigger('reset');
modal.find('.help-block').empty();
modal.find('.form-group').removeClass('has-error');
//etc
//save in modal
$(modal).on('submit','form#form_sale_return',function(e) {
e.preventDefault();
var form = $(this);
var ph_name = form.find('[name="ph_name"]').val();
//etc
$.ajax({
url: "<?php echo site_url('PharmacyController/save')?>",
type: "post",
data:{ph_name:ph_name},
success: function(response) {
alert('SUCCESS')
},
error: function(xhr) {
alert('ERROR');
}
});
});
$('#modal_sale_return').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Sale return'); // Set title to Bootstrap modal title
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error get data from ajax');
}
});
});
});
</script>
I not tested... you try :)
Use
$('#modal_sale_return').modal();
to manually open the modal
Sending form data to controller :
$('#myForm').submit(function(e){
var ajaxForm = $(this)[0];
var formData = new FormData(ajaxForm);
$.ajax({
url: 'url',
type: 'POST',
data: formData,
success: function (result) {
},
error : function() {
}
});
});

Categories