Differences between the application/xml and text/xml MIME types

How can I receive an XML response from a servlet? The servlet returns a content type of "application/xml". When using XmlHttpRequest, I am able to get responseText, but not responseXml. Could this be related to the content type or the request type (I'm using GET)?

Thank you in advance!

I have simplified all my files and believe everything is set up correctly. Here is the code:

------- HTML ------

<html>
<head>
<title></title>
<script src="js/jboard_simple.js" type="text/javascript"> </script>
</head>
<body>

    <div id="myDiv">
        <h2>No results yet....</h2>
    </div>

    <form name="searchForm" id="searchForm_id">
        <input type="text" name="searchString" id="searchString_id" />
        <button type="button" onclick="loadXMLDoc()">Perform Search</button>
    </form>

</body>
</html>

------- JavaScript -----------

function loadXMLDoc() {
    document.getElementById("myDiv").innerHTML = "searching...";

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

        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            // Do something here...
            alert(xmlhttp.responseText);
            alert(xmlhttp.responseXml);

            processSearchServletResponse(xmlhttp.responseText);
        }
    }

    // Find teh search string
    var searchString_el = window.document.getElementById('searchString_id');
    var searchString = searchString_el.value;
    alert('searchString: ' + searchString);

    var searchUrl = "/SimpleServlet?searchString=" + searchString;

    xmlhttp.open("GET", searchUrl, true);
    xmlhttp.send();
}

function processSearchServletResponse(xmlTxt) {
    document.getElementById("myDiv").innerHTML = xmlTxt;    
}

------- Servlet --------

import java.io.BufferedOutputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.log4j.LogManager;

public class SimpleServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private static Logger logger = LogManager.getRootLogger();

    public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        BufferedOutputStream bs = null;
        String simpleResponse = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><root>hi</root>";


        try {
            res.setContentType("text/xml");
            res.setCharacterEncoding("UTF-8");

            bs = new BufferedOutputStream(res.getOutputStream());
            bs.write(simpleResponse.getBytes());

        } catch (Exception ex) {
            logger.error("JboardSearchServlet.service(): error = ", ex);
        } finally {

            bs.flush();
            bs.close();
        }
    }
}

Answer №1

Oh no! I finally solved the issue by having someone else take a look.

The problem was that I was using 'responseXml' instead of 'responseXML'. Those pesky uppercase letters =)

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

Having difficulty linking the Jquery Deferred object with the Jquery 1.9.1 promise

I have been developing a framework that can add validation logic at runtime. This logic can include synchronous, asynchronous, Ajax calls, and timeouts. Below is the JavaScript code snippet: var Module = { Igniter: function (sender) { var getI ...

Experiencing issues utilizing vue.js to retrieve information from a REST API

Using vue.js, I am attempting to fetch data from a rest api but encountering issues. Unfortunately, the response data is not being displayed and no error status is shown either. It's puzzling trying to identify what may have gone wrong. Below is my i ...

Tips for finding the index of data in Cesium

After successfully completing the tutorial on building a flight tracker, I am facing a challenge. I want to access the current index of my data at any given time while my app is running cesium and displaying the airplane animation following the flight path ...

What is the process of retrieving an image file in a Java post API when it is being transmitted as form data through Jquery?

I have encountered an issue with fetching file data in my POST API when utilizing three input file fields in JavaScript. The values are being sent using formdata in jQuery upon clicking the submit button, but I am experiencing difficulties in retrieving th ...

The admin-ajax.php file in Wordpress is sending back php code instead of the expected json format

How do I configure WordPress to return JSON on Nginx? When making Ajax calls in my WordPress site, instead of receiving plain JSON, I see <?php JSON. Everything works fine on the site, except for admin-ajax calls. Example of a regular call: https://i. ...

Using jQuery to dynamically retrieve a radio button

After struggling with this issue for quite some time, I have come to the realization that it's too complex for me to handle on my own. I could really use some assistance here. The problem at hand involves a page displaying various products, each of w ...

Comparing Express.js View Engine to Manual Compilation

Currently, I am utilizing Express.js along with the hbs library to incorporate Handlebars templates in my application. Lately, I've delved into establishing a build system using gulp for my app and stumbled upon packages like gulp-handlebars. My query ...

Convert a list into a hierarchical structure of nested objects

Working with angular, I aim to display a nested tree structure of folders in an HTML format like below: <div id="tree"> <ul> <li ng-repeat='folder in folderList' ng-include="'/templates/tree-renderer.html'" ...

Encountering issues with Office.context.document.getFileAsync function

I am experiencing a strange issue where, on the third attempt to extract a word document as a compressed file for processing in my MS Word Task Pane MVC app, it crashes. Here is the snippet of code: Office.context.document.getFileAsync(Office.FileType.Co ...

What is the most efficient way to handle dependencies and instantiate objects just once in JavaScript?

I am interested in discovering reliable and tested design patterns in Javascript that ensure the loading of dependencies only once, as well as instantiating an object only once within the DOM. Specifically, I have the following scenario: // Block A in th ...

Changing an object received as a prop in Vue.js

Is it acceptable to mutate values in a prop when passing an Object reference? In the process of developing a web application that involves passing numerous values to a component, I am exploring the most efficient method of handling value passing between c ...

Is It Possible to Save Data to Local Storage Using Vue.js?

I am currently working on storing data using Vue.js and local storage. By writing localStorage.set('something', 5) in my main.js file, I can view the data in the Chrome dev tools under the 'Storage' section in the 'Application&apo ...

Utilizing AJAX to Extract Data from URL and Dynamically Incorporate Variables in MySQL Query

Having trouble passing URL variables to a MySQL query and have tried solutions using AJAX and JQuery without success. The list is populated via a MySQL query, generating links like this: echo "<td class='listingTextCentre'><a class=&ap ...

Send a StringBuilder message from a JSON object in the MVC controller and display it on the view

I'm having trouble passing a StringBuilder message as extra data back to an ajax call and manipulating it on the client side. Here is how I append the message to the StringBuilder and pass it back: StringBuilder retMessage=new StringBuilder(); retMes ...

Converting XML data into a properly formatted JSON string

Looking to feed XML into an api endpoint, but first need to convert it to a JSON valid string. Many online parsers convert XML to a JSON object with the same structure as the XML, but that's not what I want. I need the XML converted into a string for ...

Display or conceal elements in a v-for select input by leveraging the value of another input with Vue3

In my form, I have two dropdown select option fields generated using loops from predefined constants. One dropdown is for selecting different "sides" and the other for choosing various "caps". When a user selects "2-Sided" in the sides dropdown, I want t ...

Is it possible to store a JWT token in local storage when working with Next.js?

We are considering using Next.js for our application, with a focus on client-side rendering for data fetching. The API we will be interacting with is external and requires authentication to access specific user dashboard content. While the homepage will ...

Ways to obtain an attribute through random selection

Figuring out how to retrieve the type attribute from the first input element: document.getElementById('button').addEventListener('click', function() { var type = document.querySelectorAll('input')[0].type; document.getE ...

Challenges arise when using Bootstrap 4 for country selection

There have been reports that bootstrap 4 country select is not functioning properly. In an effort to troubleshoot, I delved into the documentation to find a solution. To make bootstrap-select compatible with bootstrap 4, refer to: Bootstrap 4 beta-2 ...

Creating a tooltip for a specific cell within an AG grid react component is a useful customization feature

How can I customize the tooltip for a specific row in my AG Grid? I see that there is a tooltipField available in ColDefs, but I want to provide a custom string instead of using a field value. Is there a way to achieve this customization? ...