Looped ajax only submits sometimes - javascript

I am working on a dynamic page with multiple forms that can be added and removed by the user. My jquery script goes and finds all 'form' elements and submits them with jquerys ajax method. Here is the script
$(document).ready(function () {
(function (){
var id = $(document).data('campaign_id');
$(document).on('click', '#save-button', function () {
$('form').each(function (){
var data = new FormData(this);
var form = $(this);
if(!form.parent().hasClass('hideme'))
{
$.ajax({
url: form.attr('action'),
type: 'POST',
data: data,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
success: function(data, textStatus, jqXHR)
{
console.log('form submitted '+count);
}
});
}
});
window.location.replace('/campaign');
});
})(); //end SIAF
});//end document.ready
The problem occurs that only sometimes the form submits, I can get it to if I click the save button a few times or if I remove the window.location.redirect that runs at the end, I suspect it is something to do with the redirect occurring before the submit, but I am not sure of a solution after going through some of the documentation

You are being caught out by the asynchronous nature of Ajax. Ajax does not work in a procedural manner, unfortunately. Your success method is called as and when the Ajax request has completed, which depends on your internet connection speed and how busy the server is.
It is entirely possible, the javascript completes its each loop and the first ajax request is still sending or waiting for a response. By when the javascript is ready to do a window.location call.
Edit:
Added code to check the number of forms, and the number of ajax requests, once they have all run, it will redirect
$(document).ready(function () {
(function (){
var id = $(document).data('campaign_id');
var numForms = $('form').length;
var numAjaxRequests= 0;
$(document).on('click', '#save-button', function () {
$('form').each(function (){
var data = new FormData(this);
var form = $(this);
if(!form.parent().hasClass('hideme'))
{
$.ajax({
url: form.attr('action'),
type: 'POST',
data: data,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
success: function(data, textStatus, jqXHR)
{
console.log('form submitted '+count);
numAjaxRequests++;
if(numAjaxRequests == numForms) {
window.location.replace('/campaign');
}
}
});
}
});
});
})(); //end SIAF
});//end document.ready

Related

JS / JSON: Cannot redirect to next page after insert data (AJAX JSON)

Based on my question, I have successfully added input data to the database using ajax. However, it cannot redirect to the next page, "viewDetails.html" after inserting the data. Can anyone know how to fix it?
<script>
$('#userForm').submit(function(e){
$.ajax({
type: "GET",
url: "https://yes.hus.com/yesss/husss.asmx/TGA_AppAttendanceInsert?",
data:$('#userForm').serialize(),
beforeSend: function(){
console.log("Pending to send");
},
success: function(response){
console.log("Pending to send" + response);
window.location.href = "viewDetails.html";
return true;
},
});
});
</script>
Add e.preventDefault() after submit function line.
Like
<script>
$('#userForm').submit(function(e){
e.preventDefault();
$.ajax({
type: "GET",
url: "https://yes.hus.com/yesss/husss.asmx/TGA_AppAttendanceInsert?",
data:$('#userForm').serialize(),
beforeSend: function(){
console.log("Pending to send");
},
success: function(response){
console.log("Pending to send" + response);
window.location.href = "viewDetails.html";
return true;
},
});
});
</script>
When you use element.submit function, javascript will automatically send request to server side. So usually you don't need an ajax function inside it. Except you need to do something after request.
With e.preventDefault(), submit default function will stop and go to your ajax function.
Also you don't need a question marks on url. Ajax will generate it automatically.

Ajax success function doesn't work second time

I have made a form submit with AJAX, the first time it submits, it has the success function, however the second time it prints the success data in accept_friend.php instead of the #requests_container, like a normal PHP form.
$('.accept_friend').submit(function(){
var data = $(this).serialize();
$.ajax({
url: "../accept_friend.php",
type: "POST",
data: data,
success: function( data )
{
$('#requests_container').html(data);
},
error: function(){
alert('ERROR');
}
});
return false;
});
here is accept_friend.php
<?php
session_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require "classes/class.requests.php";
require "classes/db_config.php";
$current_user = $_POST['current_user'];
$friend_id = $_POST['friends_id'];
$requests = new Requests($DB_con);
if($_SERVER["REQUEST_METHOD"] == "POST"){
$requests->accept($current_user, $friend_id);
}
?>
It seems that you are replacing the entire html in your $('#requests_container') and I am assuming that the .accept_friend button is also inside the same container.
If this is the case then try replacing your code with
$('#requests_container').on('submit', '.accept_friend', function(){
var data = $(this).serialize();
$.ajax({
url: "../accept_friend.php",
type: "POST",
data: data,
success: function( data )
{
$('#requests_container').html(data);
},
error: function(){
alert('ERROR');
}
});
return false;
});
This will keep your event alive even after the form button is removed and put back in the DOM
I've tested this and it does work for me (Firefox)
after you've clobbered your form, rebind the submit event to the submitter function
$('.accept_friend').submit(function submitter() {
var data = $(this).serialize();
$.ajax({
url: "../accept_friend.php",
type: "POST",
data: data,
success: function(data) {
$('#requests_container').html(data);
setTimeout(function() { // may not be needed
$('.accept_friend').submit(submitter); // rebind submit
}, 0);
},
error: function(){
alert('ERROR');
}
});
return false;
});

One submit button for multiple forms. Master save strategy,

Picture below shows simplification of the html page layout I am working with. It has 3 forms, every form has it's own submit button and can be submitted individually. At the top of the page "Master Save" is located. This button should save all 3 forms.
Every form have submit() function overloaded and they look like this:
form1.submit(function () {
Form1SubmitOverloaded(this);
return false;
});
Form1SubmitOverloaded = function (form) {
$.post(form.action, $(form).serialize(), function (data) {
//DOM manipulation, etc/
}).fail(function () {
//error parsing etc.
});
return false;
};
After pressing "Master Save" I want to submit forms in order 1 > 2 > 3. But I want Form 2 to wait until form 1 has ended.
Form1 submitted >> Form2 submitted >> Form3 submitted.
$('#masterSave').click(function () {
$('#form1').submit();
$('#form2').submit(); // wait until form1 ended
$('#form3').submit(); // waint until form2 ended
return false;
});
Please provide method to order submits in 'click' function as presented.
Thanks.
.post() method doesn't look to have a synch property. But .ajax() has.
I suggest you use the .ajax() method instead of the .post() shortcut method. That way you could force ajax to be synchronious
$.ajax({
[...]
async : false
}
you can use something like this
Form1SubmitOverloaded();
$.ajax({
type: "POST",
url: test1.php,
data: $( "#form1" ).serialize(),
success: function(){
Form2SubmitOverloaded();
$.ajax({
type: "POST",
url: test2.php,
data: $( "#form2" ).serialize(),
success: function(){
Form3SubmitOverloaded();
$.ajax({
type: "POST",
url: test2.php,
data: $( "#form2" ).serialize(),
success: function(){
alert("All submit successfully");
}
});
}
});
}
});

cancel page loading state in ajax

I have a script which handles post form and uses document.write with event.preventDefault
<script type="text/javascript">
$(document).ready(function(){
$('#myForm').submit(function(event) {
var form = $(this);
var request = $.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).success(function(result) {
document.write(result);
});
event.preventDefault();
});
});
</script>
After I press submit and call document.write - my browser enters in infinite loading page state. If I remove preventDefault() - it works, but I need it for other script part to work..
Is there a way to cancel page loading state right after document.write ?
I can't see why event.preventDefault would be a problem here... Try the following code :
$(document).ready(function () {
$('#myForm').submit(function (event) {
event.preventDefault();
var form = $(this);
var request = $.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).complete(function (result) {
$("body").html(result);
});
});
});
with complete instead of success to be sure that you haven't an error in your AJAX.

Check if some ajax on the page is in processing?

I have this code
$('#postinput').on('keyup',function(){
var txt=$(this).val();
$.ajax({
type: "POST",
url: "action.php",
data: 'txt='+txt,
cache: false,
context:this,
success: function(html)
{
alert(html);
}
});
});
$('#postinput2').on('keyup',function(){
var txt2=$(this).val();
$.ajax({
type: "POST",
url: "action.php",
data: 'txt2='+txt2,
cache: false,
context:this,
success: function(html)
{
alert(html);
}
});
});
Suppose user clicked on #postinput and it takes 30 seconds to process.If in the meantime user clicks on #postinput2 . I want to give him an alert "Still Processing Your Previous request" . Is there a way i can check if some ajax is still in processing?
Suppose I have lot of ajax running on the page. Is there a method to know if even a single one is in processing?
You can set a variable to true or false depending on when an AJAX call starts, example:
var ajaxInProgress = false;
$('#postinput2').on('keyup',function(){
var txt2=$(this).val();
ajaxInProgress = true;
$.ajax({
..
..
success: function(html) {
ajaxInProgress = false;
Now check it if you need to before a call:
if (ajaxInProgress)
alert("AJAX in progress!");
Or, use global AJAX events to set the variable
$( document ).ajaxStart(function() {
ajaxInProgress = true;
});
$( document ).ajaxStop(function() {
ajaxInProgress = false;
});

Categories

Resources