JSF and Jquery AJAX - How can I make them work together?

ajax, jquery, jsf, jsf-2

Solution

add the `onevent="jsFunctionName"` (no brackets) needed to your `<f:ajax`

and your `jsFunctionName` should look like

function openDeleteDevicesDialog(data) {
    console.log(data.status); //while ,data.status can be 1)"begin" 2)"complete" 3)"success"
    if (data.status === 'begin') {...}
    if (data.status === 'complete') {...}
    if (data.status === 'success') {...}
}

so you should enter this function 3 times

the onclick of the `h:commandButton` is executed before the `f:ajax` even begins...)

Note that usually you will execute your code in the when `data.status === 'success'` , its when your page is done rendering and your DOM is in its final shape/state

also take a look at BalusC answer over here...

Problem

I'm just starting out in JSF, looks awesome, but I can't seem to figure out this last barrier. I'm used to traditional Jquery AJAX function, which is perfect in my book. But I was hoping to find a way to get it to work in harmony with JSF. Here is a scenario to explain my situation. I have a messaging page on my website, where users can send each other messages. So in my xhtml page I have something that looks like this: ``` <h:form> <h:inputTextarea id="newMessageContent" value="#{conversationBean.newMessage}"/> <h:commandButton value="#{siteLang.messages_send}" action="#{conversationBean.sendMessage}"> <f:ajax render=":conversationMessages" execute="newMessageContent"/> </h:commandButton> </h:form> ``` Works great. Users can post their message and it loads it in the conversation div above. But now I need to add some features. - When user clicks, the button and textarea should get disabled to avoid interaction until the action is completed. And a loader should appear - When the JSF finishes it's stuff, the textarea and button should get enabled and the loader should disappear...and the focus goes back to the textarea. In Jquery I would simply do something like this: ``` $.ajax{ beforeSend: function (){ // Disable textarea and button, show loader }, complete: function () { // Do the inverse of above } } ``` Thanks for the help!

Original source

Related problems