my following javascript function is sending the form multiple times.
4 to 9 posts at the same time and I cannot get it right now.
Here is the function:
function formModal(url, id, type, text, send_type) {
$(document).ready(function () {
$('#' + id).on('submit', function (e) { //id of form
$.ajax({
url: url, // PHP file
data: $(this).serialize(),
type: send_type,
success: function (data) {
console.log(data);
// Success Alert
swal({
html: true,
title: text,
type: type,
timer: 1500,
showConfirmButton: false
});
setTimeout(function () {
// Refresh after 2 seconds
window.location.href = "";
}, 2200);
},
error: function (data) {
//Error Alert
swal("Oops...", "Something went wrong :(", "error");
}
});
e.preventDefault(); //This is to Avoid Page Refresh and Fire the Event "Click"
});
});
};
The function will be used in a HTML/ PHP Script:
<script> formModal('/dashboard_scripts/module/wiki/edit_wiki_article.php', 'edit_article', 'success', 'Artikel wurde gespeichert', 'GET') </script>
what are you doing in your code , why $(document).ready() inside the function formModal() and then inside that $(document).ready() you are binding submit handler which means every time you call the formModal() you are binding a submit event handler and thats the main reason of multiple submits of the form. you should either remove the submit handler from the function and make a simple ajax call or change
$('#'+id).on('submit', function (e) {
to
$('#'+id).off('submit').on('submit', function (e) {
Sweet Alert has nothing to do with the multiple submits of your form
Related
The first time a submit form the success message displays and then fades correctly. If I submit form again then it doesn't work. I want it to repeat the display of message and subsequent fade out after each form submit.
I found this answer
Trying to have a JQuery flash message after an ajax from submit in show again after more than one form submit (in rails)
but couldn't get to work, I'm very new to all this so be gentle ;-)
$(document).ready(function() {
$("#editMember").submit(function(e) {
e.preventDefault();
$.ajax( {
url: "php/adminUpdateMember.php",
method: "post",
data: $("form").serialize(),
dataType: "text",
success: function(strMessage) {
$("#message").text(strMessage);
}
});
});
setTimeout(function() {
$('#message').fadeOut('fast');
}, 4000);
});
Your setTimeout() call is not inside your submit() block. It will trigger the fadeOut 4 seonds after page load, and not be called again.
You might also need to call $('#message').show(), to make the element visible after it's been faded out.
$(document).ready(function() {
$("#editMember").submit(function(e) {
e.preventDefault();
$.ajax( {
url: "php/adminUpdateMember.php",
method: "post",
data: $("form").serialize(),
dataType: "text",
success: function(strMessage) {
$("#message").text(strMessage);
$('#message').fadeIn('fast');
}
});
setTimeout(function() {
$('#message').fadeOut('fast');
}, 4000);
});
});
Why do I get into the loop as many times as I pressed the button "tail_alertlog_button"?
A modal window opens on the button "tail_alertlog_button", I close it and so several times. Then I in this modal window click Submit, and it loops (#modal_NumberLinesAlertLog) as many times as I opened the window with the button "tail_alertlog_button".
$('.tail_alertlog_button').click(function () {
console.log('click tail_alertlog button');
var issure_name = $(this).closest("tr")
.find(".issuer")
.text();
$('.modal-title').text(issure_name);
$("#modal_NumberLinesAlertLog").on('click', '#submit', function () {
console.log('click submit button');
var NumberLinesAlertLog = document.getElementsByName("NumberLinesAlertLog")[0].value;
$("#loading").show();
console.log('show loading from modal_NumberLinesAlertLog');
console.log(issure_name);
console.log(NumberLinesAlertLog);
console.log('before ajax');
$.ajax({
type: 'POST',
async: true,
url: '/tail_alertlog',
cache: false,
data: {
'dbname': issure_name,
'NumberLines': NumberLinesAlertLog
},
success: function (data) {
console.log('success', data);
$("#loading").fadeOut(100);
$('#info_text').text(data);
$('#info_text').val("");
},
error: function () {
console.log('error', arguments);
}
});
console.log('after ajax');
});
});
$('body').on('hidden.bs.modal', '.modal', function () {
$(this).find('#info_text').text("");
console.log(this + 'clear modal');
});
(index):160 click tail_alertlog button
(index):209 [object HTMLDivElement]clear modal
(index):160 click tail_alertlog button
(index):173 click submit button
(index):179 show loading from modal_NumberLinesAlertLog
(index):180 vm_4testing
(index):181 1
(index):182 before ajax
(index):203 after ajax
(index):173 click submit button
(index):179 show loading from modal_NumberLinesAlertLog
(index):180 vm_4testing
(index):181 1
(index):182 before ajax
(index):203 after ajax
(index):173 click submit button
(index):179 show loading from modal_NumberLinesAlertLog
(index):180 vm_4testing
(index):181 1
(index):182 before ajax
(index):203 after ajax
(index):209 [object HTMLDivElement]clear modal
3(index):193 success
I presume the modal is never removed from the DOM.
You're adding another click handler
$("#modal_NumberLinesAlertLog").on('click', '#submit', function () { ... }
each time
$('.tail_alertlog_button').click(function () { ... }
triggers.
I have a Employee page which shows list of employees with an edit option. On clicking the edit button jquery-ajax is used to fetch the data from the server.
The problem is when I click the edit button the event is firing twice.
I am using a seperate js file and is referring the file to the main page.The script was working fine until i moved it to the seperate js file.
The Jquery script is
//ajaxGet on edit button click
$(document).on('click', '.editRole', ajaxGet);
var ajaxGet = function (e) {
var spinner = $(this).parent('div').find('.spinner');
var href = $("#editMenuSettings").data("url");
var menuRoleId = $(this).data('id');
spinner.toggle(true);
var options = {
type: "GET",
url: href,
data: { menuRoleId: menuRoleId }
};
$.ajax(options).success(function (data) {
spinner.toggle(false);
$(".modal-body").html(data);
$(".modal").modal({
backdrop: 'static'
});
});
$.ajax(options).error(function (data) {
spinner.toggle(false);
toastr.error("Oops..Some thing gone wrong");
});
return false;
};
You call $.ajax twice.
At lines
$.ajax(options).success(function(data)...
$.ajax(options).error(function(data)...
you actually make two different AJAX calls - one with success callback only, another one with error callback.
In your case, your call should look like this:
var options = {
type: "GET",
url: href,
data: { menuRoleId: menuRoleId }
};
$.ajax(options)
.success(function (data) {
spinner.toggle(false);
$(".modal-body").html(data);
$(".modal").modal({
backdrop: 'static'
});
})
.error(function (data) {
spinner.toggle(false);
toastr.error("Oops..Some thing gone wrong");
});
return false;
It will set both callbacks to the single AJAX call and execute this one.
Folks,
I'm learning Ajax by tinkering. At first, I had a form with button, which made an Ajax call to a dummy controller action. The HTML and JavaScript on the client side.1
<form method="post">
<button name="btnSaveProject" title="When you save this project, it willl be available for 30 days.">
Save
</button>
</form>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.1.min.js"></script>
<script>
$(document).ready(function () {
$("button[name='btnSaveProject']").click(function () {
console.log("make ajax call");
$.ajax({
url: "/Project/Save",
type: "GET",
timeout: 8000,
cache: false
}).done(function () {
console.log("ajax call successful");
}).fail(function (jqXHR, textStatus) {
console.log("something went awry. " + textStatus);
}).then(function () {
console.log("always just in case");
});
});
});
</script>
A strange thing was happening when I clicked the button. The Ajax call would reach the server (I know thins because I had a break point in the controller action, which triggered). But neither neither .done(), nor .fail(), nor .always() was getting called back on the client-side.
Then I have moved the <button> out of the <form>, and now .done(), and .always() get called back as expected. There seems to be some interplay between the can Ajax call. What is this interplay? Where can I learn more about it? What do I have to do to be able to use Ajax inside a <form>?
Here's the server-side code, but I suspect that it's a non-factor.
// AJAX: /Project/Save
public ActionResult Save() {
System.Threading.Thread.Sleep(600); /// <bring-up>A bit of latency to make the Ajax call more noticeable.</bring-up>
return Json("lorem ipsum", JsonRequestBehavior.AllowGet);
}
1 I have stripped down the code and kept only the parts that I think are applicable to the question. If I have stripped down too much, please let me know: I'll post more code.
You can add a type to your button:
<button type="button" name="btnSaveProject"
or just prevent the defaults of button to submit the form with event.preventDefault():
$("button[name='btnSaveProject']").click(function (e) {
e.preventDefault();
// other code as is
});
Since the button is in a form its default click action is to submit the form, So in your case as soon as the ajax request is sent the actual page is submitted which I think is reloading the page causing the callback handler to unload that is why those are not getting called
One solution is to prevent the default action of the click event by calling event.preventdefault()
$(document).ready(function () {
$("button[name='btnSaveProject']").click(function (e) {
//prevent the default action of the button click which is to submit the form
e.preventDefault()
console.log("make ajax call");
$.ajax({
url: "/Project/Save",
type: "GET",
timeout: 8000,
cache: false
}).done(function () {
console.log("ajax call successful");
}).fail(function (jqXHR, textStatus) {
console.log("something went awry. " + textStatus);
}).then(function () {
console.log("always just in case");
});
});
});
But since you are using a form, instead of a button click event it will be better to use a form submit event like
$(document).ready(function () {
$("form").submit(function (e) {
//prevent the default action of the button click which is to submit the form
e.preventDefault()
console.log("make ajax call");
//your ajax code
});
});
Another option is to set the type of the button to button so that the form submit will not be triggered like
<button type="button" name="btnSaveProject" title="When you save this project, it willl be available for 30 days.">Save</button>
I am making few ajax requests in my jQuery file. On success of these jQuery requests, I wrote few on click events which are not working.
This is my code
$(document).ready(function (){
$.ajax ({
type: "POST",
url: 'myServlet',
async: false,
success: function (response) {
id = parseInt(response);
setOutputEvents();
}
});
function setOutputEvents() {
for (var queryNumber = 0; queryNumber <= id; queryNumber++) {
$.ajax({
type: "POST",
url: 'myOtherServlet',
data: {queryNumber: queryNumber},
success: success,
async: false
});
var success = function (response) {
//some code here
generateTable();
}
}
}
function generateTable () {
//some code here
pagination();
}
function pagination(){
$(".class").click(function(event) {
alert();
});
}
$("#me").on("click", function(){
alert("me is triggered");
});
});
I understand making multiple ajax requests is a bad programming practice but what could be the reason for on click events not getting triggered?
These are the onclick events which are not working.
function pagination(){
$(".class").click(function(event) {
alert();
});
}
$("#me").on("click", function(){
alert("me is triggered");
});
I am using Google Chrome Version 39.0.2171.95 on Windows 7.
Please do let me know if any further information is necessary.
Since you use ajax to load even the initial content it seems, .class / #me html elements likely do not exist on initial page load of the DOM. As you didn't post html, i'm guessing this is the case.
Thus, you need to use a delegated event click handler to respond to it
so, you would change
$("#me").on("click", function(){
to
$(document).on("click", "#me", function(){
and so forth to link it to the parent element that does exist, the document itself.
This would work:
$(".class").on("click", function(){
alert("me is triggered");
});
function generateTable () {
//some code here
pagination();
}
function pagination(){
$(".class").trigger("click");
}
Some notes:
Event handler must be registered before triggering click.
Triggered click selector must match the class which has the click event registered.
Functions must be defined before the usage.