Struggling to implement Ajax functionality with JSF on a Tomcat 7.0 server

I am new to Ajax and struggling to get a simple example to work...

Here is the javascript code:

var xmlRequest;
function refreshContent() 
{
    if (window.XMLHttpRequest) 
    {
        xmlRequest = new XMLHttpRequest();
    } 
    else 
    {
        xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlRequest.onreadystatechange = function() 
    {
        if (xmlRequest.readyState == 4) 
        {
            document.getElementById("tester").innerHTML = xmlRequest.responseText;
        }
    };

    xmlRequest.open("GET", "sample.xhtml", true);
    xmlRequest.send();
}

Now, take a look at the sample xhtml page:

<div id="test">
    SAMPLE CONTENT
</div>
<button type="button" onclick="refreshContent()">Change Text</button>

The JavaScript file has been called.

I have been testing it and it seems like the "xmlRequest.onreadystatechange" is always null and doesn't trigger the function.

Could there be an issue elsewhere, perhaps on the Tomcat server?

Answer №1

The particular element has been identified with an id of test

<div id="test">

However, you are currently trying to locate it using tester

document.getElementById("tester")

Please correct this issue.


On another note, when delving into the realm of ajax, it is advisable to consider utilizing a reliable framework instead of developing one from scratch. A highly recommended option is jQuery for handling ajax tasks. The implementation is straightforward:

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
    $(document).ready(function() {
        $('#change').click(function() {
            $.get('test.xhtml', function(responseText) {
                $('#test').text(responseText);
            });
        });
    });
</script>

<body>
    <div id="test">TEST TEXT</div>
    <button id="change">Change content</button>
</body>

Furthermore, when incorporating ajax within a component-based MVC framework like JSF, maintaining synchronization between client and server-side state can be quite complex. It is advised not to develop this from scratch as well. Consider either upgrading to JSF 2.0 which includes built-in ajax functionality

<h:form>
    <h:commandButton value="Change content" action="#{bean.change}">
        <f:ajax execute="@form" render=":test" />
    </h:commandButton>
</h:form>
<h:panelGroup id="test" layout="block">#{bean.text}</h:panelGroup>

using this approach

public void change() {
    this.text = "new text";
}

Alternatively, if you are still using JSF 1.x, consider implementing an ajax-based component library such as RichFaces, IceFaces, PrimeFaces, and so on.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for inserting an object into an array

Here's the data I received: { 0:{modifierId: 4, modifierName: 'Garlic', modifierPrice: 60 } 1:{modifierId: 1, modifierName: 'Tartar ', modifierPrice: 60} 2:{modifierId: 3, modifierName: 'Herb ', modifierPrice: 60} item ...

I'm receiving identical results from findOne even when using different IDs

I am currently working on creating a new array of products based on a list of different Ids. However, I have encountered an issue where the same product is being returned for all Ids when using the findOne() method. let wishpro = ['632a5e5rtybdaaf ...

Removing duplicate elements from an array using lodash

What is the best way to remove duplicate values from an array? var numbers = [1, 1, 5, 5, 4, 9]; I want my result to be: var numbers = [4, 9]; Is there a method in lodash that can help me achieve this? ...

How come the hook keeps triggering endlessly in a loop when I try to pass the updated props?

I've encountered an issue with a custom hook I created for making HTTP requests. The problem is that the request seems to be firing in an endless loop, and I'm unsure of what's causing this behavior. My intention is for the request to only t ...

Utilizing a React component for interactive button functionality

In my React app, I decided to enhance my buttons by incorporating images using SVG. After discovering that I needed a separate component for my SVG files, I came across this helpful resource and created my own <SVGIcon /> component. However, when at ...

Troubleshooting the issue with UI-Router AngularJS controller not functioning properly in a

Trying to grasp the ins and outs of UI-Router in conjunction with Angular has proven to be quite challenging for me. In my setup, there's an index: <body> <div ui-view></div> <!--Location of file holding app--> <scri ...

Tips for utilizing the @run-at document-start meta-rule

Currently, I am utilizing the following code snippet: Jquery(window).load(function(){ // here is my code for making an AJAX request to retrieve data from the database }); Unfortunately, I have encountered an issue specifically with its function ...

Angular 2 issue with nested form elements

Looking to build a form that includes nested sub/child components within it. Referring to this tutorial: https://scotch.io/tutorials/how-to-build-nested-model-driven-forms-in-angular-2 https://plnkr.co/edit/clTbNP7MHBbBbrUp20vr?p=info List of modificatio ...

Update the label for the weekday on Material UI picker

Is there a way to change the weekday display in Material UI DatePicker from single initial (M, T, W, T, F, S, S) to three-letter initials (MON, TUE, WED, etc)? I want to customize it in my component like this: <DatePicker disablePast disableTool ...

Utilizing API data as props within an Autocomplete component in Reactjs with Material-UI

New to Reactjs, I am currently exploring the implementation of the Autocomplete component from material-ui. My goal is to pass the API link as a prop to the element. However, I'm stuck on how to pass the json label name as a prop to be used in "getOpt ...

Interacting with a Web API using JavaScript following successful authentication with Azure AD B2C

Currently, I am working on a .Net Web App. After going through the authentication process with Azure AD B2C using the Azure AD Connect protocol, my app's controller successfully obtains an access token via the MSAL library (written in C# code) to conn ...

The Div overlay vanishes once the Javascript function is finished running

Initially, take a look at this fiddle: http://jsfiddle.net/ribbs2521/Q7C3m/1/ My attempt to run JS on the fiddle has been unsuccessful, but all my code is present there, so we should be fine. I was creating my own custom image viewer, and everything was ...

Can you elaborate on this specific JavaScript concept?

I'm not very knowledgeable about javascript. Could someone please explain this structure to me? [{a:"asdfas"},{a:"ghdfh",i:54},{i:76,j:578}] What exactly is being declared in this structure? It appears to be an array with 3 elements, correct? Each e ...

Having trouble making class changes with ng-class

I am attempting to change the direction of the arrow in my checkbox by utilizing two classes with the assistance of ng-class. Unfortunately, it is not producing the desired outcome. Below is my code: Note: The angularJS CDN has already been incorporated. ...

How can I include multiple dictionary entries in a JSON file at once?

After attempting to include an array with dictionaries in a JSON file, I encountered multiple errors. This has led me to question whether it is feasible to add dictionaries directly into a JSON file without using Node.JS for data insertion. Here is an exa ...

What could be the reason for v-model not functioning properly within vue.extend?

I've configured a page structure similar to the following: <main id="app"> <div id="mount-place"></div> </main> <script type="text/x-template" id="my-template"> ...some code her ...

Is it possible to generate grid options dynamically for various tables within AngularJS using ui-grid?

I have developed a service for ui-grid table functionality. Currently, I am able to use this service on a single page but now I want to extend its usage to multiple pages, each with different table data. How can I pass grid options and JSON data for multip ...

Displaying numerous database rows through SQL with the aid of PHP and JavaScript (specifically AJAX) on the frontend of a website

I am a beginner in the world of PHP and JavaScript (Ajax) and despite my efforts to find a solution by looking at various posts and websites, I have not been successful. My goal is to display all related database rows on the front end of a website. While ...

Tips for creating a shift function without using the splice method

I'm currently working on creating custom functions for common array operations. I've hit a roadblock trying to reimplement the shift method without using splice. Any tips or guidance on how to approach this challenge would be highly valued. Cust ...

Use Meteor to retrieve the value from the initial collection in order to locate the value in the second collection

Currently, I have two sets of data: Users, containing userId, firstname, and surname. Answers, containing answerId, questionId, and user. In the 'Answers' collection, the 'user' field corresponds to the userId of the user who provide ...