I am facing a challenge with my php page that contains multiple forms sending an exec command to the server:
Form 0, when the RunAll button is clicked -> it should execute all subsequent button commands sequentially using a jQuery class selector loop
Form 1, Button 1 -> Executes Apache shell cmd 1
Form 2, Button 2 -> Executes Apache shell cmd 2
Form3, Button 3 -> Executes Apache shell cmd 3
The goal is for the RunAll button to trigger all requests asynchronously in ajax mode to prevent the page from freezing, while making sure they are executed one after the other. However, the current issue is that the jQuery loop clicks all buttons simultaneously without waiting for each ajax call to finish before moving on to the next.
I have attempted various methods including: 1- Using a global variable in ajax success 2- Utilizing Promises 3- Implementing Async-await
One of the challenges faced is that due to all processes running at the same time, Apache memory gets exhausted.
function submitMultiForm(){
$('.btn-info').each(function() {
asyncClick($(this));
});
}
async function asyncClick(myBttObj)
{
//GET THE SPECIFIC FORM AND TEXT AREA
var myForm = myBttObj.parent();//alert(myForm.attr('id'));
var myFormAreaText = myBttObj.siblings('.myanswer');//alert(myFormAreaText.attr('id'));
//SET icons
var mySpinIcon = myBttObj.siblings('.fa-spin');
var mySuccIcon = myBttObj.siblings('.fa-check');
var myErrIcon = myBttObj.siblings('.fa-times');
var myErrAjxIcon = myBttObj.siblings('.fa-exclamation-triangle');
var url = myForm.attr("action");
var serializedData = myForm.serialize()+'&'+$('#fparam').serialize();
try {
const res = await doAjax(url, serializedData, mySpinIcon, mySuccIcon, myErrIcon,myErrAjxIcon);
//write always the log
var myAreaID = myFormAreaText.attr('id');
//var filtered_data = res.html();
myFormAreaText.append( res );
//(because the url is the same page of the origin of the ajax request)
//brwsr console
console.log(myAreaID)+':';
console.log(res);
//blur off button
myBttObj.blur();
} catch(err) {
console.log(err);
}
}
function doAjax(url, serializedData, mySpinIcon, mySuccIcon, myErrIcon,myErrAjxIcon)
{
let result;
try {
result = $.ajax({ url:url,
type:"post",
data: serializedData,
datatype: 'html',
beforeSend: function() {mySpinIcon.show();mySuccIcon.hide();myErrIcon.hide();myErrAjxIcon.hide()},
success: function(data) {
if ( data.toLowerCase().indexOf("error") >-1 ) {
mySpinIcon.hide();mySuccIcon.hide();myErrIcon.show();myErrAjxIcon.hide();
} else {
mySpinIcon.hide();mySuccIcon.show();myErrIcon.hide();myErrAjxIcon.hide();
}
},
error: function() {mySpinIcon.hide();mySuccIcon.hide();myErrIcon.hide();myErrAjxIcon.show()}
});
return result;
} catch (error) {
console.error(error);
}
}