How trigger on submit function manually? - javascript

I have submit function that is triggered on submit button inside of the form. Here is example:
$(document.body).on('submit', '#myfrm', submitFrm);
function submitFrm(e){
e.preventDefault();
var frmData = $(this).serialize();
$.ajax({
type: 'POST',
url: 'ajax/form_data.cfm',
data: frmData
}).done(function(data){
//data saved
}).fail(function(jqXHR, textStatus, errorThrown){
alert('Error: '+errorThrown);
});
}
}
Now I would like to trigger submitFrm() function from another function like this:
function Cancel() {
submitFrm();
}
This will throw an error that e doesn't exist. I guess that submit needs to be triggered manually. Is there a way to do that with JQuery?

The error happens because you are calling submitFrm without passing the event (e). The event argument is passed by JavaScript to the function when the submit event occurs. If you call the function manually you do not have the event.
What you can do is to use JQuery to get a reference to the form element ($('#myfrm')) and trigger the submit event on hit:
function Cancel() {
$('#myfrm').submit();
}
In this way the submit event is triggered on the form and the submitFrm handler is called with the event in input.

function Cancel() {
$('#myfrm').submit();
}
according to https://api.jquery.com/submit/

Related

using jQuery, how to wait for onChange event to finish before form submit event is fired

Suppose there is a textbox in my webpage and I have attached an 'change' event on this textbox using jQuery.
$('.myFormClass').on('change', '.amount', function () {
// Some AJAX call here, and the response is assigned to a variable
});
And I have a form submit event as well,
$('.myFormClass').on('submit', 'form', function (e) {
// some code in which I use the response from the earlier AJAX call returned against 'change' event
});
The issue is that the 'change' event works fine individually but when form submitted they are fired almost simultaneously and till the time when AJAX call against the 'change' event is returned back (supposed to be), the form had already been submitted by then so I can't use the AJAX response, which is needed before the form submission.
Is there something built-in jQuery for this situation? If no, any alternate efficient solution?
Store the ajax promise and wait for its resolve in the form submit handler
let amountReady = null;
$('.testForm').on('change', '.amount', function(ev) {
amountReady = $.ajax({
method: 'POST',
url: 'https://httpbin.org/post',
data: {
amount: $(this).val()
}
});
});
$('.testForm').on('submit', 'form', function(e) {
e.preventDefault();
if (!amountReady) return;
amountReady.then((amountAjaxResult) => {
console.log('submit now', amountAjaxResult.form.amount);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="testForm">
<form>
<input type="number" class="amount" />
<button type="submit">Submit</button>
</form>
</div>
Add a button. When the user click the button a boolean is set to tru and if it is true then only submit will happen otherwise only onchange function will work not the submit function.
var sub=false;
$(document).ready(function(){
$('button').click(function(){sub=true;console.log(sub)})
$('.myFormClass').on('change', '.amount', function () {
// Some AJAX call here, and the response is assigned to a variable
console.log('changed')
});
$('.myFormClass').keypress((e)=>{if(e.keyCode=='13'){e.preventDefault();console.log('not submitted on enter')}})
$('.myFormClass').click( function (e) {
e.preventDefault();
console.log("submit cancelled")
if(sub)
$(this).submit();
// some code in which I use the response from the earlier AJAX call returned against 'change' event
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="myFormClass">
aa
<input class="amount">
<input type="submit">
</form>
<button>Want to submit the form?</button>
You can use:
function method1(){
// some code
}
function method2(){
// some code
}
$.ajax({
url:method1(),
success:function(){
method2();
}
})
Or nested function after a function is done with:
function test () {
console.log('test');
}
function test2 (callback) {
console.log('test2');
callback();
}
test2(test);
Might be related

Ajax form is sent twice if validation errors take place

I know about event.preventDefault() and event.stopImmediatePropagation(). But it doesn't work for me. In my case I have such ajax call:
$('#templateConfirmDialog').on('show.bs.modal', function (event) {
$(this).find('.modal-yes').click(function(){
var form = form2js('search_form', '.', true, function (node) {}, false);
var requestData = JSON.stringify(form, replacer);
var $formErrors = $('.search_form').find('.alert-danger');
event.preventDefault();
event.stopImmediatePropagation();
$.ajax({
type: 'POST',
contentType : "application/json",
url: '/fraud/template/testCreate',
data: requestData,
dataType: 'json',
success: function (data) {
$formErrors.text('');
//if no errors just reload
if (data === undefined || data.length === 0) {
location.reload();
}
else {
//else bind error messages
data.forEach(function(error) {
$('#new-' + error.field + '-error').text(error.defaultMessage);
})
}
}
});
});
My problem is that the ajax call is prevented as much times as I made attempts to input data. If I entered invalid data once - ajax is called twice. If twice - 3 times. What may be a reason of such behavior?
Every time this event happens:
$('#templateConfirmDialog').on('show.bs.modal', function (event) {
You bind a new click event handler:
$(this).find('.modal-yes').click(function(){
So if you show.bs.modal twice, then you have two click event handlers both submitting the AJAX request. Instead, just bind the click event handler once to the target clickable element, instead of binding it every time the modal is displayed.
Replace this:
$('#templateConfirmDialog').on('show.bs.modal', function (event) {
$(this).find('.modal-yes').click(function(){
//...
});
});
With this:
$('#templateConfirmDialog').find('.modal-yes').click(function(){
//...
});
Or, if that element is dynamically added to the DOM, this:
$(document).on('click', '#templateConfirmDialog .modal-yes', function(){
//...
});
That way there's just a single click event handler created when the page loads, rather than adding a new handler every time you display the modal.

Ajax not loading in IE

Here is the script. It works fine in all other browsers, so I thought it was a cache problem but not really. I have been banging my head for hours and nothing is working.
$.ajaxSetup({
cache: false
});
$("#send").live('click', function () {
console.log("AAAAA");
$("#loader").show();
$form = $('#reservationForm');
$inputs = $form.find('input[name^="entry"]'),
serializedData = $('#reservationForm :input[name^="entry"]').serialize();
console.log(serializedData);
serializedData += "&pageNumber=0&backupCache=1&submit=Submit";
// fire off the request to /form.php
$.ajax({
url: "https://docs.google.com/spreadsheet/formResponse?formkey=d",
// url: "https://docs.google.com/spreadsheet/formResponse?formkey=d;ifq",
type: "post",
data: serializedData,
// callback handler that will be called on success
success: function (response, textStatus, jqXHR) {
// log a message to the console
console.log("Hooray, it worked!");
$("#loader").hide();
document.getElementById('error<?php echo"$uname";?>').innerHTML = error;
$("#success").fadeIn();
setTimeout(function () {
$("#success").fadeOut();
}, 5000);
},
// callback handler that will be called on error
error: function (jqXHR, textStatus, errorThrown) {
// log the error to the console
console.log("The following error occured: " + textStatus, errorThrown);
alert('Due to an unknown error, your form was not submitted, please resubmit it or try later.');
},
// callback handler that will be called on completion
// which means, either on success or error
complete: function () {
// enable the inputs
$inputs.removeAttr("disabled");
}
});
// prevent default posting of form
event.preventDefault();
});
console.log is available after you open Developer Tools (F12 to open) in IE. Try turning it on or use an alert instead in your code.
or use a try catch;
try{
console.log('worked')
}
catch(err){
}
And You might want to check if your event variable is undefined:
event= event || window.event;
event.preventDefault();
At the beginning of the script you are not adding the "event" declaration in the handler:
$("#send").live('click', function () {
should be:
$("#send").live('click', function (e) {
And at the end of the script there is a reference for the variable event:
// prevent default posting of form
event.preventDefault();
I think that IE doesn't have a 'preventDefualt' function in the global event object (which you are referencing): this function is added to the "e" event object passed by jQuery. Any way, it should fail too in all other browsers with a "event is not defined". Try this too:
// prevent default posting of form
e.preventDefault();
An additional note: jQuery team currently discourage the use of the "live" event binding function, instead you should use the equivalent form of the "on" function.
IE doesn't understand the content type of response in ajax. So put your dataType value in the request and it should work.
for e.g. -
dataType: ($.browser.msie) ? "text" : "xml"

Change input button's onClick parameter using JavaScript

I'm making an Android Web Application, and I'm using JQuery Mobile. My question is:
Is it possible to change the onClick event's parameter using Javascript?
I will be using Ajax post request to get the primary key attribute of my row from the database. And after getting the primary key, I want to set the parameter of the input button's onClick event.
Here's the structure of my program:
<script>
$.ajax({
type:"POST",
url:"url.php",
dataType:"json",
data:{input:input},
success: function (result)
{
//Set my input button's onclick
}
});
</script>
success: function (result)
{
$("#" + result).click(function () {
// do something
});
}
use this
yourelement.addEventListener('click', yourfunction);
or this
yourelement.addEventListener('click', function() {
//your code here
});
or in jquery
$('yourelement').click(yourfunction)
You can do like this instead:
$('#element').click({id: id}, handleClick);
If, for example, the click handler is somewhere outside the scope:
function clickHandler(ev) {
var id = ev.data.id;
// use id
}

event.preventDefault not working

I have this simple code here, nothing too advanced.
$("input#send").submit(function(event){
event.preventDefault();
$.ajax({
type: 'POST',
url: add.php,
data: data,
success: success,
dataType: dataType
});
});
Whever I click on the "send" button, the event.preventDefault function doesn't work, and the page loads.
Any ideas why?
A form has the submit event, not a button. Plus, an ID should be unique so tag#id can just be #id.
$("#theform").submit(function(event) {
event.preventDefault();
// ...
});
You need to bind to the form's submit event or to the button's click event and call event.preventDefault() if you want to stop the form from submitting:
$('form').bind('submit', function (event) {
event.preventDefault();
});
$('form').find(':submit').bind('click', function (event) {
event.preventDefault();
});
I believe the submit event is for the form element. For an input[type='button'] you might want to use the click event.
Add quotes around 'add.php'
Change the selector in the first line to the id attribute of the form which contains input#send.
The advantage of handling the submit() handler on the form rather than the click handler on the input is that some forms can be submitted by pressing the enter key (when the user is focused on one of the form fields). If you don't have an id attribute, add one or use a different jQuery selector to target the form tag.
$("#myform").submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'add.php',
data: data,
success: success,
dataType: dataType
});
return false;
});
Try using return false instead
$("input#send").submit(function(event) {
$.ajax({
type: 'POST',
url: add.php,
data: data,
success: success,
dataType: dataType
});
return false;
});
If you're using preventDefault I assume that means you do NOT want the default submit action. I would just use a different event instead of using .submit. To me, it's not the submit action that you want to intercept, but rather the click that would normally cause the submit.
$('#inputSend').on('click', function(event) {
event.preventDefault();
//the rest
});
If both return false and event.stopPropagation() don't work, try the following method. Using .on() will make the submit function accessible. Once you change the .submit() to .on("submit"..), you can either use return false or e.stopPropagation().
$(document).on("submit", "input#send", function(event) {
event.stopPropagation();
$.ajax({
type: 'POST',
url: add.php,
data: data,
success: success,
dataType: dataType
});
return false; });

Categories

Resources