I am facing problems into triggering an ajax call through a hidden command button multiple times inside a javascript loop. Actually The javascript code seems to be executed before the ajax call gets a successful response which has as a result, the value I am processing each time not to be updated before the ajax next request is sent.
Below I am showing an example
.xhtml form code
<h:form id = "jsfform">
<h:inputHidden id="attributes" value="#{myBean.attributesStr}" />
<p:commandButton id="button" update="@form" style="display: none"
ajax="true">
<f:actionListener binding="#{myBean.bindAttributes()}"/>
</p:commandButton>
</h:form>
MyBean.java
@ManagedBean(name = "myBean")
@ViewScoped
public class MyBeanimplements Serializable {
private String attributesStr;
private List<String> attributes;
//getters setters ommitted
public void bindAttributes(){
this.attributes.add(attributesStr);
}
}
.js function triggering the button to make the ajax call
var attributes ="";
function ajaxFunction(){
for(let index = 0; index < 5; index++){
attributes += "a";
document.getElementById('jsfform:attributes').value = attributes
document.getElementById('jsfform:button').onclick(); //trigger the ajax function
}
}
When I am debugging now, my list seems to have the following values
["a","a","a","a","a"]
while I would like my values to be
["a","aa","aaa","aaaa","aaaaa"]
which is caused by the fact that the value that I am binding from the form to the backend variable through the hidden input field is not updated on time because the javascript code executes the ajax requests in sequence before the first request returns its response.
Which are the workarounds in these cases? Thanks in advance :)
What I have tried
I tried to "disable" the button when it is clicked and "re-enable" it on the complete event of my AJAX call and let javascript waiting for my button to be re-enabled but this led to an endless loop.
<h:form id = "jsfform">
<h:inputHidden id="attributes" value="#{myBean.attributesStr}" />
<p:commandButton id="button" update="@form" style="display: none"
ajax="true" oncomplete="this.disabled = false">
<f:actionListener binding="#{myBean.bindAttributes()}"/>
</p:commandButton>
</h:form>
and in javascript waiting for the button to be re-enabled
var attributes ="";
function ajaxFunction(){
for(let index = 0; index < 5; index++){
attributes += "a";
while(true) {
if(document.getElementById('jsfform:button').disabled == false){
document.getElementById('jsfform:attributes').value = attributes
document.getElementById('jsfform:button').onclick(); //trigger the ajax function
document.getElementById('jsfform:button').disabled = true;
break;
}
}
}
}