Issues encountered when trying to refresh a form using HtmlUnit in combination with Ajax

Trying to complete and submit an HTML form using HtmlUnit, encountering issues with retrieving a select element loaded via <body onLoad="...">.

The Issue: Unable to access the desired select element through methods like getSelectByName or getChildElements (ElementNotFoundException thrown), despite data being present in org.apache.http.wire log.

When inspecting page.asXml(), only the original HTML document is displayed.

Sample Code:

public static void main(final String[] args) throws Exception {

    final URL url = new URL("http://www.rce-event.de/modules/meldung/annahme.php?oid=471&pid=1&ac=d98482bbf174f62eaaa4664c&tkey=468&portal=www.dachau.de&ortsbox=1&callpopup=1");

    final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_3_6); // also tried FIREFOX_3
    webClient.setAjaxController(new NicelyResynchronizingAjaxController());

    final HtmlPage page = webClient.getPage(url);
    webClient.waitForBackgroundJavaScript(10000); // also attempted Thread.sleep()

    // replaced 'page' with webClient.getCurrentWindow().getEnclosedPage() - same issue
    final HtmlForm form = page.getFormByName("formular");

    // ElementNotFoundException occurs at this point:
    final HtmlSelect select = form.getSelectByName("event.theme");
    final HtmlOption option = select.getOptionByText("Sport/Freizeit");
    final Page newPage = select.setSelectedAttribute(option, false);

    // submission process, etc.
}

Stacktrace:

Exception in thread "main" com.gargoylesoftware.htmlunit.ElementNotFoundException: elementName=[select] attributeName=[name] attributeValue=[event.theme]
at com.gargoylesoftware.htmlunit.html.HtmlForm.getSelectByName(HtmlForm.java:449)
at Xyzzy.main(Xyzzy.java:58)

Attempted solutions from various sources including here, here, and here without success.

Update:

Simplified code and initiated a bounty.

Answer №1

Your issue arises from the fact that the select field labeled "event.theme" is only populated once the select field named "event.datapool" has a value of "1" selected.

To resolve this, you must change the value of the select field "event.datapool" to "1":

[........]
final HtmlSelect selectBase = form.getSelectByName("event.datapool");
final HtmlOption optionBase = selectBase.getOptionByText("Freizeit / Tourismus");
final Page newPage = selectBase.setSelectedAttribute(optionBase, true);
[........]

However, there might be complications because the data for the select field "event.theme" is loaded using ajax. This means that your java "HtmlSelect" class may not load the select field "event.theme" in the form like Javascript does with direct user interaction.

A potential solution could be:

1. Access the page "http://www.rce-event.de/modules/meldung/annahme.php?oid=471&pid=1&ac=d98482bbf174f62eaaa4664c&tkey=468&portal=www.dachau.de&ortsbox=1&callpopup=1" 
2. Visit the page "http://www.rce-event.de/modules/meldung/js/xmlhttp_querys.php?get_kat=1&time=1338409551228&id=1&block=kat" > this will provide the data/values for the "event.theme" select field
3. Utilize the data retrieved in step 2 to update the content of the page accessed in step 1 by adding a "select list with id and name set to <event.theme>" within the HTML element "kat_content"

Once completed, your form or webpage should now include the new select field "event.theme," and as a result, the following code should operate without errors.

final HtmlSelect select = form.getSelectByName("event.theme");
final HtmlOption option = select.getOptionByText("Sport/Freizeit");
final Page newPage = select.setSelectedAttribute(option, false);

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 Combining Chrome driver service with desired capabilities for headless mode using xvfb?

I am looking to combine the functionalities of ChromeDriverService with either chromeOptions or DesiredCapabilities in order to run the browser in xvfb. Below is a snippet of code related to ChromeDriverService that I had previously used without selenium ...

Is it possible to utilize the same class name for multiple Ajax requests?

I have created a script to update score1 and score2 in the database with jQuery. Here is my jQuery/AJAX code: $(document).ready(function() { $('#SampleForm').submit( function(event) { var id = $('.id').val(); var sco ...

How to use CakePHP to load a view containing PHP variables and then return it using Ajax

Alright, I've been seriously bothered by this issue for the past couple of days. Let's take a look at my form: echo $this->Form->create(FALSE, array('id' => 'AdminGeneralReport', 'class' => 'Report ...

The Ajax request functions flawlessly on Mozilla but encounters issues on Chrome, causing confusion as it occasionally works

I am using a PHP file with a class and function to store data in the database, accessed via AJAX. While everything works smoothly in Mozilla, Chrome seems to be causing some issues. Strangely, sometimes it works fine, but other times it fails for no appare ...

Is there a workaround for automatically printing generated PDF files (such as labels and packing slips) from the backend to pre-selected printers directly from a browser?

In the process of creating my web application, I am in need of a solution for automatically printing PDF files (such as labels and packing slips) to pre-selected LAN network printers located in my warehouse from the admin backend. I understand that due to ...

jQuery AJAX delivering HTML output upon completion

Currently, I am implementing a jQuery Ajax function to submit the username and password and receive a response. The functionality works seamlessly with the GET method. However, when using the POST method, it successfully sends the data but fails to retur ...

Tips for presenting the retrieved data from the database in a user-friendly format

$ //First step involves running the PHP code that executes the SQL query to retrieve data from the database, storing it in get_row1, and sending it as a response to Ajax$ <?php $connect = mysql_connect("localhost", "root", ""); $data = mysq ...

Dynamic Automatic URL Refresh with Javascript

Hey there! Just joined this community and I'm still a coding newbie. I'm trying to figure out how to make an external JavaScript URL automatically refresh every 30 seconds. The URL looks something like this: domain.com/filename.js The tricky pa ...

Older versions of jquery are compatible with Ajax requests, but newer versions may have some

After updating jQuery to a newer version in an old file that was being enhanced with some new features, the jQuery ajax post function stopped working. Even after attempting to change "success" to "done," the issue remains unresolved. // validate email a ...

Sorting one column in datatables.net triggers sorting in another column

Facing a major issue that I'm struggling with. I am using datatable.net to showcase data retrieved from my MySql database. I have followed the API guidelines meticulously in order to sort columns by name in ascending order (and toggle to descending). ...

"Troubleshooting: Issues with jQuery's .on method when used with dynamically added

I have a large number of <button class="lb"> <div class="l"></div> <div class="c">2</div> <div class="r"></div> </button> Some of these buttons are present in the initial DOM when the page loads, whi ...

Trigger an event upon completion of a write operation in AngularJS

I want to trigger a search after my user finishes typing (without hitting enter) in AngularJS. Here is a simplified version of my HTML: <div ng-class="input-append" ng-controller="searchControl"> <input type="text" ng-model="ajaxSearch" ng-cha ...

Automatically populating state and city fields with zip code information

Starting out in the world of web development, I encountered a challenge with a registration form I'm constructing for our company. For guidance, I referred to this resource: http://css-tricks.com/using-ziptastic/. This project marks my initial interac ...

Tips for efficiently loading data into a vuex module only when it is required and addressing issues with async/await functionality

Is there a method to load all the data for a Vuex store once and only load it when necessary? I believe there is, but I am having trouble implementing it. I'm not sure if it's due to my misunderstanding of Vuex or Async/Await in Javascript promi ...

What is the best way to output partial Haml in a Padrino controller?

Currently, I am working on an Ajax request where the backend may render a partial Haml and send it back. Unfortunately, I encountered the following error: Padrino::Rendering::TemplateNotFound at /feedhtml Below is the snippet of the backend code being ...

Getting the raw exception message in Laravel without any HTML formatting can be accomplished by accessing the `

When interacting with the Laravel backend, I frequently make ajax requests. While processing the request data on the backend, there are instances where exceptions are thrown. By default, Laravel generates HTML pages with exception messages. However, my r ...

Having difficulty selecting a radio button situated in a separate frame

I've encountered an issue while attempting to click on a radio button that is located in a different frame than the parent frame. Even though there are no exceptions thrown when executing the code provided below, the button itself does not get clicked ...

Transferring parameters from a jQuery post function to a controller

I am facing an issue where the controller is not receiving the "name" parameter that I want to send as a parameter. $(document).ready(function () { $("#btn1").click(function () { var name = $("#search").val(); //name = "ali"; alert(name); ...

Easily refresh multiple select options by using the ajax updater function in prototype

After carefully reviewing the documentation for Ajax.Updater(), I noticed that the first argument to the constructor should be container (String | Element) – The DOM element whose contents will be updated as a result of the Ajax request. This can eith ...

Submitting a form into a database with the help of AJAX within a looping structure

Trying to input values into the database using AJAX. The rows are generated in a loop from the database, with each row containing a button column. Clicking on the button submits the values to the database successfully. The issue is that it only inserts va ...