Javascript - Statements skipped - javascript

I have a button in my html:
<button id="confirm-download" onclick="submit(getStudentsDetails)" data-dismiss="modal" class="btn btn-success">Confirm</button>
and these are the submit and getStudentsDetails functions
function submit(callback) {
$('#download_resumes').attr('action', '/api/studentsdetails/');
$('#download_resumes').submit();
callback()
}
function getStudentsDetails() {
$('#download_resumes').attr('action', '/api/studentsdetails/');
$('#download_resumes').submit();
}
Now these functions are referring to this form:
<form id = "download_resumes" action="api/" method = "POST">
The problem here is that, only the second api (/api/studentsdetails/) is getting called here. I want both of these apis to be called onClick of the button.
The 2 APIs that need to be called are '/api/resumes/', '/api/studentsdetails/'.

Use Handler of submit and then call your second function like the following
function submit(callback) {
$('#download_resumes').attr('action', '/api/studentsdetails/');
$('#download_resumes').submit(function( event ) {
alert( "Handler for .submit() called." );
callback()
});
}
function getStudentsDetails() {
$('#download_resumes').attr('action', '/api/studentsdetails/');
$('#download_resumes').submit();
}

you can use ajax request to submit form and on success you can call that callback method
function submit(callback) {
//assuming callback is method name you want to call
$.ajax({
url:'/api/studentsdetails/',
data:$('#download_resumes').serialize(),
success:function(response){
window[callback]();
}
});
}
window[callback] (); will call your callbackmethod on success refer this link for more information.

Related

How to trigger another jquery event using the return data of previously executed jquery event

I have a button, for example
<a id="btn" class="button">Submit</a>
When this button is clicked, it triggers a jquery function
for example,
$("#btn").on("click", function() {
$.ajax({
url: 'index.php',
type: 'post',
data: {product_id: 1, qty: 2},
dataType: 'json',
success: function(json) {
if (json['success']) {
console.log('Product added to cart');
}
if (json['error']) {
console.log('Product not added to cart');
}
});
});
Now, I would like to know if it is possible to trigger another jquery event by some other jquery code, once the above function is executed, and I want to use the return values of the previous function without making any changes to the above-mentioned function.
For example, I would like to run the following function immediately after the above jquery event by writing another jquery code and not changing any part of the previous code.
function anotherAction(json_array) {
if (json_array['success']){
//calling another function
}
}
You mean
function anotherAction() {
if (submitBtn() == 'Submitted'){
console.log('Button is submitted');
}
}
But then you need to make str global in scope
Perhaps like this
let str;
$("#btn").on("click", function() {
str = 'Submitted';
});
$("#check").on("click", anotherAction);
function anotherAction() {
console.log('Button has '+(str === 'Submitted' ? "" : "not ")+'been clicked');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn" type="button">Click</button>
<button id="check" type="button">Check</button>
without making any changes to the above-mentioned function.
No. Its not possible. submitBtn function's return value is unused/no-reference/destroyed inside "#btn" click event. So you'll never know what was returned.

How trigger on submit function manually?

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/

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

Pass parameter to bound function

I am running into an issue where I want to pass an 'event' parameter to a function which is being called from a JQuery eventListener.
$('#todoRemove').on('click', this.removeTask(event));
This immediately calls the function when the page is loaded, then does not work when pressing the button which would kick off the event. What can I change to make it so it calls the method in the prototype but passes the event parameter?
TaskCtrlr.prototype = {
init: function () {
this.setupEventHandlers();
},
setupEventHandlers: function () {
$('#addTask').on('click', this.addTask.bind(this));
$('#todoRemove').on('click', this.removeTask.bind(this));
/* $('#todoComplete').on('click', this.completeTask.bind(this));
$('#doneRemove').on('click', this.removeTask.bind(this));*/
},
addTask: function () {
let taskInput = this.view.getTaskInput();
let newTask;
if (this.model.tasks.todo.length == 0) {
newTask = new Task(0, taskInput.title, taskInput.desc, false);
} else {
let id = this.model.tasks.todo[this.model.tasks.todo.length - 1].id + 1;
newTask = new Task(id, taskInput.title, taskInput.desc, false);
}
this.model.addTask(newTask);
this.view.addTodoTask(newTask);
},
completeTask: function (event) {
console.log('wwwwww');
console.log(event.target.id);
},
removeTask: function (event) {
console.log('eeeeee');
console.log(event.target.id);
}
};
EDIT: CURRENT SOLUTION
$('#todoRemove').on('click', event, removeTask);
ERROR:
jQuery.Deferred exception: removeTask is not defined ReferenceError:
removeTask is not defined
Why do you want to pass event? What does it even refer to?
The event object is passed by the caller of the event handler, which is jQuery. You should do exactly the same as you do for the other handlers:
$('#todoRemove').on('click', this.removeTask.bind(this));
jQuery will pass the event object to the function without you having to do anything.
This immediately calls the function when the page is loaded
$('#todoRemove').on('click', this.removeTask(event));
Yes, it will call it because during registering a call back, you are not really registering a callback but calling your function using this code:
this.removeTask(event)
Instead you need to do this. I am not sure what event is but the 2nd argument you can use to pass something to the callback:
$('#todoRemove').on('click', event, removeTask);
And you can define removeTask like this:
function removeTask( event ) {
//...
}
Here is an example you can play with to get comfortable:
function greet( event ) {
alert( "Hello " + event.data.name );
}
$( "button" ).on( "click", {
name: "Karl"
}, greet );
If you do not pass anything, jQuery will still pass the a parameter to you which contains the event info as shown below:
function greet2( event ) {
alert( "Hello " + event.target.id );
}
$( "button" ).on( "click", greet2 );
There is more info here.
<== Fiddle Me ==>

Cannot read property 'preventDefault' of undefined in javascript error

In Console I got following error using e.preventDefault() method
I used e as a function parameter
function function1(e){
e.preventDefault();
}
1533 Uncaught TypeError: Cannot read property 'preventDefault' of undefined.
Called function1 like
Click Me
You have to pass event in the used function:
function1(event); // where you called it
For example:
Click Me
Make sure you call this function within an event handler. Such as :
$(document).click(function(event){
function1(event);
});
I remove event from function and invoke function in this way:
<button class="btn btn-primary" runat="server" id="btnSave" type="submit"
onserverclick="btnSave_OnServerClick" onclick="return
jsFunction();">Save</button>
In JavaScript:
function jsFunction() {
alert('call');
if ($('#form1').bootstrapValidator('validate').has('.has-error').length) {
alert('SOMETHING WRONG');
} else {
alert('EVERYTHING IS GOOD');
__doPostBack('<%=btnSave.UniqueID%>', '');
}
return false;
}
You are writing the function wrong. Suppose you are using function on a particular button click having id as 'clickBtn' then you need to write function like this.
$("#clickBtn").on("click", function(e){
e.preventDefault();
});
You failed to pass the event as a parameter in your in luck event in the html.
So it should be written as the sample below:
Click Me
function function1(event){
e.preventDefault();
}

Categories

Resources