I have some code as such to submit multiple forms on my page at once:
$('.photo-edit-form form').ajaxSubmit({
success: function() { console.log('success'); },
error: function() { console.log('error'); }
});
However, no matter how many forms I have, I only ever get one success print out. I've found that I can fix it by using .each on the selected forms like so:
$('.photo-edit-form form').each(function() {
$(this).ajaxSubmit({
success: function() { console.log('success'); },
error: function() { console.log('error'); }
});
});
Is this a problem with the ajaxForm plugin or is this a misunderstanding on my part about how jQuery works? Any input would be greatly appreciated.
The code for the plugin acts like it handles any number at once, but it basically comes down to this:
$.ajax(options);
And the data in that option set comes from .formToArray() which only deals with the first element in the set:
var form = this[0];
So for your question, yes, this is a problem with the plugin, .ajaxSubmit() only works on a single <form> at a time, it doesn't have a .each() internally like most plugins would.
as far as I see it ajaxSubmit does not handle each result from the selector.
Related
I did on a project many forms with its "" in the part of page (generated by php) that add specific function to it per form id and are working, for example:
$("#fregistrazione").submit(function(event){
...
}
I did the same with an html part loaded with ajax request but is not working.
I thinked to do in a different way with the same function called by many form submit, instead having one different defined for any form on any form submit, call a function with additional parameter that do the specific form things with less code duplication but I'm unable to have it working.
I did many try, for example:
<form id="f_man-marker_edit-marker" method="post" action="#" onsubmit="TM.editMarker(this)">
...
...
TM.editMarker = function(rform){
// Abort any pending request
if (request) { request.abort(); }
let form = $(rform);
// Let's select and cache all the fields
let inputs = form.find("input, select, button, textarea");
// Serialize the data in the form
let serializedData = form.serialize();
// Let's disable the inputs for the duration of the Ajax request.
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
inputs.prop("disabled", true);
request = $.ajax({
url: "ajax.php?req=man-marker_edit-marker",
type: "post",
data: serializedData,
dataType: "html"
});
request.done(function (response){
$("#ajaxoutput2").empty().append(response);
$("#ResultModal2").modal("show");
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.error(
"Ajax man-marker_edit-marker request failed. The following error occurred: "+
textStatus, errorThrown
);
});
request.always(function () {
inputs.prop("disabled", false);
});
};
but on submit reload the page with parameters as "get" in url and didn't execute the edit marker function.
Can someone please tell me what I did wrong and how to do a correct call of a function from the form submit instead do a .submit on any form id containing dozens of duplicate lines for each form and not working if generated by a code that is received through ajax request?
Thanks for any reply and sorry for my bad english.
EDIT:
I did what suggested by ChrisG and I tried to add a parameter in TM.editMarker but I not found how to maintain correctly event as first parameter and add 2 other parameters.
For example adding 1 parameter:
TM.editMarker = function (e, ajax_request) {
...
I tried (even if IDE gave me event as deprecated):
$('#f_man-marker_edit-marker').on('submit', TM.editMarker(event, 'man-marker_edit-marker'));
And also without but in both case don't work.
EDIT2:
solved with:
$('#f_man-marker_edit-marker').on('submit', function(e){
TM.editMarker(e, $(this), 'man-marker_edit-marker');
});
...
TM.editMarker = function (e, form, ajax_request) {
...
but I'm open to better solutions.
Simple Answer:
You manipulated the DOM, so your selector is not there yet on event-binding.
Use a parent selector thats already there like document
$(document).on("submit", "#fregistrazione", function(event){
event.preventDefault(); // stop the form submitting if needed
...
});
this way it will work
I am using a Bootstrap modal to display an ASP.Net MVC5 form, the form is inserted dynamically into a div using a jquery ajax call to the relevant controller and then opened.
I need to intercept the submission of the form so I would like to bind to the submit event of the form in jquery but have so far only been able to bind to the submit event of all forms since the dynamic forms are of course not present when the main view is rendered e.g.
$('form').submit(...)
rather than
$('#serverForm').submit(...)
Whilst this sort of works, it has a problem in that I actually have 3 different dynamic forms in this view which can be shown using modal popups, thus I need to do one of 2 things:
A) (ideally)manage to intercept the submit event for each form.
B) in the global form event handler, identify which form has been submitted.
I have tried every option I can imagine to use option A including adding the binding to the code which pops the modal. all without success.
I am currently trying to go with option B so that I can then decide where to post the form. This does at least get called when a form is submitted but my problem is that I cannot get the id or name of the form which has been submitted and thus have no way of knowing which one it is.
I have the following handler:
<script>
$(function () {
$('form').submit(function(e) {
// this is always null
var id = $(this).attr('id');
$.ajax({
url: '#Url.Action("EditServer", "AccountAdmin")',
data: new FormData(this),
...
});
});
});
</script>
Within this handler I have tried the following (plus a few more!) to get the form's id:
this.id
$(this).id
$(this).attr('id');
$(this).prop('id');
I have tried adding the handler after the ajax call to populate the modal like this:
$(".server-link").click(function (event) {
event.preventDefault();
$.ajax({
url: $(this).attr("href"),
cache: false,
type: "GET",
dataType: "html",
success: function (data, textStatus, XMLHttpRequest) {
$('#serverDiv').html(data);
$('#serverModal').modal('show');
$('form').submit(function (e) {
var id = $(this).attr(id);
// test to see if handler called
alert(id);
});
},
error: function (jgXHR, textStatus, errorThrown) {
//The commented out message is full of Html but includes compilation errors etc from the server
//alert('An error occured: ' + jgXHR.responseText);
alert(textStatus + ':' + errorThrown);
}
});
});
It's driving me bonkers! I have tried every combination of ideas from various posts with no joy. I need to post using FormData (in one case at least) because there is a file upload (an image) involved. Any assistance is much appreciated.
The problem is that your JavaScript code is running before the form has actually been added to the page. When using AJAX, you need to run whatever JavaScript you need in the callback:
$.get('/some/url', function (result) {
$('#whatever').html(result);
$('form').submit(function(e) {
var id = $(this).prop('id');
// do whatever with id
});
});
Use this instead:
var id = $(e.target).attr('id');
I am using ASP.Net MVC and jQuery 1.8.2
I have a form with a button that calls this javascript when it is clicked:
$(function () {
$('#SearchButton').click(function () {
var data = $('#FilterDefinition :input').serialize() + "&PageNumber=1";
$.post('#Url.Action("Search")', data, LoadContentCallback);
$("#SearchResults").show();
});
});
This calls an MVC Controller Action which returns a PartialViewResult
On the Layout page I have the following JavaScript code:
//Add a custom header to all AJAX Requests
$(document).ready(function () {
$.ajaxSetup({
beforeSend: function(xhr) {
debugger;
if ($('[name=__RequestVerificationToken]').length) {
var token = $('[name=__RequestVerificationToken]').val();
xhr.setRequestHeader('__RequestVerificationToken', token);
}
}
});
});
When the button is clicked for the first time, the beforeSend function is called correctly. However, if the button is clicked more than once (for example they change the search criteria and search again) then the beforeSend function never gets called again and the validate anti-forgery fails.
I tried using the ajaxSend event instead and I got the same results.
Any help is solving this problem would be greatly appreciated.
Thanks!
It turns out the problem was that the partial view that was being rendered was referencing a different version of jQuery. I removed this reference and everything started working correctly.
Thanks!
I would avoid using $.ajaxSetup if possible. I would just setup your beforeSend in the actual POST request.
I basically copied an entire form submission code I had up and running on a Website and pasted it into a blank file in order to modify its contents and save some time. IN THEORY, then, if the original file stopped normal form submission from opening up the Action target file while still completing the submission, this one should do the same.
However, I can't get it to work like it did. I can't stop the submission from leaving the current window.
Can anyone please point me toward what I'm doing wrong?
(Aside from the PHP code I'm using the jQuery Validation Plugin, same as I was using in the previous form that worked as expected.)
Form HTML code:
<form id="form" class="appintro" method="post" action="manageform.php" enctype="multipart/form-data"></form>
JS
$.validator.setDefaults({
submitHandler: function() { //<-- Handler called by jQuery Validation once form is validated
$('.msg.sending').fadeIn(200);
$.ajax({
type: 'POST',
url: form.attr('action'),
data: form.serialize(),
success: function() {
alert('Success')
},
error: function() {
alert('Failure')
}
});
return false; //<-- This should stop the normal submission...
}
});
I've also already tried calling the AJAX outside of the validator code, i.e. using $("form").submit(function(event)..., etc. Also tried setting data to form.serializeArray(), as recommended in some other SO post... Nothing does it.
Thanks in advance for your help!
EDIT 1
I've set up this jsFiddle to test it out in a simpler version. No matter what I place in AJAX's url, I get an error. If I fill the form's action, then I can't catch the submission.
Edit 2
Ok while fixing some bugs in my version of your js fiddle, I figured what the issue is.
This line is missing the form parameter
submitHandler: function() {
It should look like this:
submitHandler: function(form) {
Next, to call serialize, you need to wrap make it a jquery object. The form passed in by jquery validate is just a regular form object and not a jquery one. So you need to do this.
data: $(form).serialize(),
If you call form.serialize, you should get this error in Chrome: Uncaught TypeError: Object #<HTMLFormElement> has no method 'serialize', which could explain why your browser is reloading.
Edit 1
I looked at your fiddle and I found some bugs, but I'm not sure they fix your problem. I feel like I just fixed some errors specific to jsfiddle.
Here is a link to an updated fiddle that works: http://jsfiddle.net/JSuUL/6/
Here is the code with some annotations
$.validator.setDefaults({
// Need to pass in form variable
submitHandler: function (form) {
alert('Sending...')
$.ajax({
type: 'POST',
// First off changed this to make the request work
// http://doc.jsfiddle.net/use/echo.html
url: '/echo/html/',
// Instead of form, I used $(form) to reference the form as a jquery object.
data: $(form).serialize(),
success: function () {
alert('Success!')
},
error: function () {
alert('Failure!')
}
});
return false;
}
});
$(document).ready(function () {
// I added a "#" here so we can grab the form. Your jsfiddle had $(form)
$("#form").validate({
rules: {
name: {
required: true,
minlength: 2
},
surname: {
required: true,
minlength: 2
},
}
});
});
I have a web application which uses a lot of AJAX to display pages.
In my javascript I have a feature which gets all the elements that have a certain class (testClass). It does a bunch of stuff with these classes but that's not necessary for my problem.
At the moment my function runs when the DOM is ready and it works great. However, I need my function to run when AJAX returns a new page to the browser as it could contain elements with testClass.
Is there a way I can listen if a certain DOM element is added? I basically need a way to recognise a DOM change, when this change has happen run my function.
Or is there a way I can listen for the addition of elements with class testClass?
If it help here is a snippet of my code:
execute = function () {
var found = false;
$('.testClass').each(function () {
//bunch of code
});
}
$(document).ready(function () {
execute();
});
Try with ajax success method
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
alert('Load was performed.');
}
});