I have fetched the data from database using ajax and i am showing it to the user using javascript confirm dialog. But even after user selects cancel option, form is being submitted, but I want to submit a form only when user wants to proceed further by selecting OK in confirm box. Here is my code
<form class="form-horizontal form-bordered" method="post" id="ncell" action="formaction">
<input type="hidden" name="_token" value="{{csrf_token()}}">
<div class="form-group">
<label class="col-md-3 control-label" for="inputSuccess">Amount</label>
<div class="col-md-6">
<select class="form-control mb-md" name="amount" id="amount">
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
<option value="50">50</option>
</select>
</div>
</div>
<div class="input-group mb-md">
<button type="submit" class="btn btn-warning btn-sm" id="sub">Submit</button>
</div>
</form>
and my javascript
<script>
$("#ncell").submit(function(e){
var selectedVal= $("select option:selected").val();
$.ajax({
type:"GET",
url: "/getdollarvalue",//put y
data:{ value:selectedVal},
contentType: "application/json; charset=utf-8",
dataType: "Json",
success: function(result){
return confirm(result.nrs); // Note Send the Json Object from the server side
}
});
e.preventDefault();
});
</script>
I am now getting the confirm dialog when user clicks the submit button. I just want to proceed further only when user clicks OK in confirm dialog.
<script>
$("#ncell").submit(function(e){
var selectedVal= $("select option:selected").val();
$.ajax({
type:"GET",
url: "/getdollarvalue",//put y
data:{ value:selectedVal},
contentType: "application/json; charset=utf-8",
dataType: "Json",
success: function(result){
if(confirm(result.nrs)){
$("#ncell").submit();
}
}
});
return false;
});
</script>
or you can use e.preventDefault(); in place of return false.
You can change the button type of your button from submit to button like
<input type="button" class="btn btn-warning btn-sm" id="sub"/>
to avoid automatic submit
If you want to submit the form when the user presses the ok button, you will need to bind a click event to the ok button to submit the form.
See example below.
$('.ok-btn').click(function(){
var data = $('form').serialize();
// your ajax to submit the form and handle the response.
$.ajax({
})
});
hope this help.
You can put ajax call in function and call it from confirm dialog function
also you should add return false on submit click to prevent the default form submit action:
$('#submit').on('click', function() {
confirmFunction('Are you sure you want to...');
return false;
}
function confirmFunction(message) {
//show confirm dialog ( ok - cancel )
$('#confirm').show();
$('#confirm p').innerHTML(message);
$('.ok').on('click', function(){
ajaxSubmit();
$('#confirm').hide();
});
$('.cancel').on('click', function(){
$('#confirm').hide();
});
}
function ajaxSubmit() {
var selectedVal = $("select option:selected").val();
$.ajax({
type: "GET",
url: "/getdollarvalue", //put y
data: {
value: selectedVal
},
contentType: "application/json; charset=utf-8",
dataType: "Json",
success: function(result) {
return confirm(result.nrs);
}
});
};
Related
I am having a form in which once I submit, all would go back blank as initial. I have implemented Sumo Select plugin for the dropdowns. When the form is submitted no changed on dropdown's value or text. No attempts are helping here. I will share the code below
HTML
<div class="col-lg-6">
<div class="input-group mb-3">
<select value="" name="_fromDrop" id="_fromDrop" class="SlectBox form-control">
<?php echo load(); ?>
</select>
</div>
</div>
JQUERY FORM SUBMISSION
$(document).ready(function(e){
$("#form").on('submit', function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: '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){
$('#form')[0].reset(); //FORM TO RESET AFTER SUBMISSION
$('.statusMsg').html('<p class="alert alert-success">'+response.message+'</p>'); // REPONSE MESSAGE
postOrderSave(); //TEST METHOD TO RESET DROPDOWN
}else{
$('.statusMsg').html(alert(response.message));
}
$('#form').css("opacity","");
$(".submit").removeAttr("disabled");
}
});
});
});
Method to RESET
function postOrderSave(){
//Order From
$('#_fromDrop[value="Name List"]').text('Name List');
}
Where am I making the Mistake? Please help on this.
If you look at that plugin documentation to set selected value in your select-box you can use :
$('select.SlectBox')[0].sumo.selectItem('Name List');
My Ajax request works correctly when I use change and the input is checkbox, but my Ajax request does not work when use input type submit !!
I want my type in the input submit and when I do this the Ajax request will not work and the page will reload.
$(document).on('change','.filter-form',function(event){
event.preventDefault();
$.ajax({
type:'GET',
url:'filter/',
data : $(this).serialize(),
dataType: 'json',
success: function (data) {
$('#product-main').html(data['form']);
},
error: function (data) {
alert("error" + data);
}
});
});
my form :
<form action="" class="filter-form">
<input type="submit" name="price" value="new">
<input type="submit" name="discount" value="discount">
<input type="submit" name="old" value="old">
</form>
I don't think submit buttons trigger the change event, so you'll have to listen for something else, also .serialize() do not give you the name/value pair of submit buttons.
Use the click event on the buttons and use the element properties to get the data to post.
$(document).on('click','.filter-form input[type=submit]',function(event){
event.preventDefault();
$.ajax({
type:'GET',
url:'filter/',
data : {[this.name]: this.value}
dataType: 'json',
success: function (data) {
$('#product-main').html(data['form']);
},
error: function (data) {
alert("error" + data);
}
});
});
First added a clicked property to the identify which submit is clicked. Then used the clicked property to get the value & name of the submit to pass in form submit event handler.
$(document).ready(function(){
// To identify which submit is clicked.
$("form.filter-form input[type=submit]").click(function() {
$("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
$(this).attr("clicked", "true");
});
// Form submit event handler
$("form.filter-form").submit(function(event) {
event.preventDefault();
$clickedInput = $("input[type=submit][clicked=true]");
dataString = {[$clickedInput.prop('name')]: $clickedInput.val()};
console.log('dataString', dataString);
$.ajax({
type:'GET',
url:'filter/',
data : dataString,
dataType: 'json',
success: function (data) {
$('#product-main').html(data['form']);
},
error: function (data) {
console.log("error" + data);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="filter-form">
<input type="submit" name="price" value="new">
<input type="submit" name="discount" value="discount">
<input type="submit" name="old" value="old">
</form>
I want to perform a submit with AJAX and select list. I made a simple alert but nothing. Did I misss something ?
This is my html:
<form id='bill_action' action='post'>
<input type='hidden' name='bill_id' value='".$v1['id']."'>
<select name='action' onchange='this.form.submit()'>
<option value='test1'>test1</option>
<option value='test2'>test2</option>
</select>
</form>
my JS:
$("#bill_action").submit(function() {
alert('hello world'); //for test
$.ajax({ //make ajax request to bill_action.php
url: "bill_action.php",
type: "POST",
dataType:"json", //expect json value from server
data: bill_id
}).done(function(data){
//on Ajax success
})
})
try this :
<form id='bill_action' action='post'>
<input type='hidden' name='bill_id' value='".$v1['id']."'>
<select name='action' onchange='myfunction'>
<option value='test1'>test1</option>
<option value='test2'>test2</option>
</select>
</form>
function myfunction() {
alert('hello world'); //for test
$.ajax({ //make ajax request to bill_action.php
url: "bill_action.php",
type: "POST",
dataType:"json", //expect json value from server
data: bill_id
}).done(function(data){
//on Ajax success
})
}
I submit the form when trigger submit. How ever I cannot create user record. I show you the code.
<form method="POST" id="form_1" action="../api.php" enctype="multipart/form-data" novalidate="novalidate">
<input type="text" name="name" id="name" value="Amy" readonly="readonly">
<input id="fileBox" class="fileUpload" type="file" name="img" accept="image/*" required>
<input type="hidden" name="isSubmit" value="1"/>
</form>
<a id="btnSubmit" href="javascript:void(0)">Submit</a>
In js file:
$('#form_1').submit(function(){
var formData = new FormData((this)[0]);
$.ajax({
type: "POST",
url: "../../api.php",
data: { action: "isSubmit", formData: formData},
processData:false,
contentType:false,
success: function(data){
$("#thankyou").show();
}
})
return false;
});
$("#btnSubmit").click(function(){
var name = $("#name").val();
$.ajax({
type: "POST",
url: "../../api.php",
data: { action: "checkInputData", name: name}
})
.done(function(data){
data = $.parseJSON(data);
if ( data.status == 0 ){
$('#form_1').trigger('submit');
}
api.php :
if( $action == "isSubmit"){
$name= isset($_POST["name"])?$_POST["name"]:null;
createUser($conn, $name);
}
I found the the flow of the submit is not correct.
The flow of the above code is when I trigger submit then fall into success show thankyou div, but didn't create user record.
however if I removed the "return false" in ajax, the flow will becomes : trigger submit then fall into success show thankyou div then redirected to api.php then finished. In this case I can create the user record.
My target result should be I trigger submit then fall into success show thankyou div and create user record. How can I do this? And what's the differnce between having and without the "return false".
If i have something like:
<form method="post" id="customForm" action="">
//stuff
<div id="copiar">
<button class="button" href="#" id="btnAdd0">
<span class="icon icon3"> </span>
</button>
<button class="button" href="#" id="btnDel0">
<span class="icon icon58"> </span>
</button>
<button class="submeter">
<span class="label">Send</span>
</button>
</div>
</form>
and:
<script type="text/javascript">
$(document).ready(function() {
$("#customForm").submit(function() {
var formdata = $("#customForm").serializeArray();
$.ajax({
url: "validation.php",
type: "post",
dataType: "json",
data: formdata,
success: function(data, data1) {
//stuff
});
return false;
});
});
</script>
At the moment, the three buttons send the form. My idea is only permit the submit action in this button:
<button class="submeter">
<span class="label">Send</span>
</button>
I already tried $("#customForm > #copiar > button.submeter").submit(function() {
but the page is reloaded. So isn't working.
Any idea ?
You have to stop the other buttons from submitting first and then do your submit. Also when using an ID for your selector there really isn't any need to combine it with another ID like #customForm > #copiar "
Try this:
$(document).ready(function() {
$("#customForm").submit(function(e) {
e.preventDefault();
var formdata = $("#customForm").serializeArray();
$.ajax({
url: "validation.php",
type: "post",
dataType: "json",
data: formdata,
success: function(data, data1) {
//stuff
}
});
});
$("#customForm button").click(function(e) {
var me = $(this);
e.preventDefault();
if(me.hasClass("submeter")) $("#customForm").submit();
});
});
And as has already been pointed out, you don't need/want the href="#"
In order to prevent the default behavior of the form, you must use preventDefault() as follows:
$(document).ready(function() {
$("#customForm").submit(function(e) {
e.preventDefault();
var formdata = $("#customForm").serializeArray();
$.ajax({
url: "validation.php",
type: "post",
dataType: "json",
data: formdata,
success: function(data, data1) {
//stuff
});
});
$("#customForm button.submeter").click(function() {
$("#customForm").submit();
});
});
What is exactly the purpose of first two button element with the href attribute? I suspect you're using a button instead of a regular link only for a formatting/visual reason.
Anyway for your purpose, just add the attribute type="submit" to the last button and remove the submit handler you've defined for this button, it should work fine.
edit. you also need to call the preventDefault() method to stop page reload, as pointed out by phil klein