What is the method to retrieve just plain text (String) from an Ajax URL response?

I'm still learning how to use Ajax. My current project involves populating a dropdown based on the selected value from another dropdown in HTML. The issue I'm facing is that, while I am able to get the desired output, it includes unwanted HTML formatting.

Below is the JavaScript code I am using -

    function showHint(str)
{  
//  alert("Ajax - " + str);

var xmlhttp;
if (str.length==0)
  { 
  document.getElementById("txtHint").innerHTML="";
  return;
  }

if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }


  xmlhttp.open("GET","AjaxCall.jsp?q="+str,true);
  xmlhttp.send();

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    { 
     alert("xmlhttp.responseText - " +  xmlhttp.responseText  ); 
    }
  }


}

Currently, in the xmlhttp.responseText alert, I receive the following output -

I only require the output as follows -

D1&&&D2&&&D3&&&D4

I wish to eliminate the extra HTML code being returned.

This is what my AjaxCall.jsp looks like -

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

 <%@ page import="com.Search.Struts2.AccessCheckComponent"%>
 <%@ page import="java.util.*"%> 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>

<%
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
response.setDateHeader("Expires", 0); // Proxies.
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setContentType("text/plain");

%>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<%

System.out.println("-------------------jsp -------------- " );  

String cpmt = request.getParameter("q");
System.out.println("cpmt -!!Ajax - jsp !! " + cpmt);    

String deckStr = AccessCheckComponent.CheckCompartmentDeckRelationship(cpmt);
System.out.println("deckList -!!Ajax - jsp !! " + deckStr); 

  response.getWriter().write(deckStr.toString());  

%>

</body>
</html>

Answer №1

The reason you are receiving HTML is because your JSP is sending it back in the response. To resolve this issue, you should adjust the contentType of the page to text/plain and eliminate all HTML elements from the JSP (such as <!DOCTYPE...>, <html>, etc.). Simply output

D1&&&D2&&&D3&&&D4
.

A more efficient solution would be to create a basic Servlet. This will help you avoid the excess overhead that comes with using JSP.

Answer №2

To extract only the deckStr.toString(), simply eliminate the unnecessary code from your jsp file:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

 <%@ page import="com.Search.Struts2.AccessCheckComponent"%>
 <%@ page import="java.util.*"%> 

<%
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
response.setDateHeader("Expires", 0); // Proxies.
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setContentType("text/plain");

System.out.println("-------------------jsp -------------- " );  

String cpmt = request.getParameter("q");
System.out.println("cpmt -!!Ajax - jsp !! " + cpmt);    

String deckStr = AccessCheckComponent.CheckCompartmentDeckRelationship(cpmt);
System.out.println("deckList -!!Ajax - jsp !! " + deckStr); 

  response.getWriter().write(deckStr.toString());  

%>

By doing this, you will only see the required data.

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

"npm is the go-to tool for managing client-side JavaScript code

As I delved into a document outlining the npm Developer Guide, a question sprang to mind. Is it within the realm of possibility to construct a web client application using javascript/css/html with npm at the helm? And if so, might there be examples avail ...

The datatable fails to load correctly when called using ajax in CodeIgniter

With a set of 2000 data entries, I decided to utilize the datatables plug-in for display purposes. The initial implementation using a simple source code worked like a charm - features such as searching, pagination, and sorting functioned flawlessly. View ...

Navigating the world of updating problems with Express.js

Currently, I am working on a MEAN stack project and facing challenges with the routing for updating. Saving operations are functioning correctly. In my Angular controller, I have defined the following scope method in which staff represents the object subm ...

I am experiencing an issue where my Laravel website does not refresh automatically

Having trouble with the URL (url: "/ultimo-pedidox"). It seems to be loading correctly, but the view isn't refreshing as expected. @extends('store/template') @section('content') <div style="margin-top: 55px;" ...

Utilizing Typescript in tandem with an external library through es6 modules

Is there a recommended method for incorporating Typescript with non-module libraries like PixiJS and SortableJS without using webpacker? I'm looking to utilize es6 modules but want to avoid cumbersome solutions. What would be the best approach in this ...

Exploring Style Attribute Manipulation using vanilla JavaScript on Firefox

I searched for a similar question, but I couldn't find anything quite like it. I'm currently developing a JavaScript Slider plugin for various projects within our company. This requires me to manipulate styles on certain elements in the DOM. I&a ...

Show the result of (Firstname) on the thank you page after the form has been submitted

Need help with a PHP issue; it seems simple but I'm uncertain of the correct method, whether through jQuery or PHP. I have a contact form where I want certain field results to display on the thank you page after submitting the form: Thank you for en ...

Does GIF animation operate on the same thread as JavaScript in all popular web browsers?

When my AJAX request is in progress, an animated GIF is displayed to show activity. However, I have noticed that the animation freezes while the response from the request is being processed by a script that heavily updates the DOM. After researching this ...

Navigate to a different page following a successful login, without needing to refresh the current

Currently working on a login page where I need to redirect the user to another page upon successful login. I attempted using the pathname property for redirection but encountered some issues. If anyone has a recommendation for a library that can assist w ...

What is the process for creating two columns with an input box beneath them?

I am facing a challenge with my code. I am struggling to create the desired design where there are two columns and below them an input box that will be displayed when a button is pressed. The design I am aiming for can be viewed here: enter image descripti ...

Is there a way to transfer data from the controller (in JSON format) and display it in a ListBox within the

As a newcomer to ASP.NET Core, my main goal is to easily populate a listbox with data from a JSON file. Take a look at the controller class below: public class EmployeeController : Controller { public IActionResult Index() { return View() ...

Issues encountered while trying to implement HTML text within span tags

In my code snippet, I am using a span element: <span> {textToRender} </span> The purpose of this code is to render HTML text (as a string) within a span element. some text <br/> some text <br/> some text <ol>text However, wh ...

"Step-by-step guide on implementing a click event within a CellRenderer in Angular's Ag-Grid

paste your code hereI'm currently working on implementing edit and delete buttons within the same column for each row using Angular ag-Grid. To visually represent these buttons, I am utilizing icons. While I have successfully displayed the edit and de ...

The error message "Encountered an issue when trying to access properties of undefined (reading 'getState')" was

Currently working on developing an app that utilizes a Django backend and React frontend. The goal is to enable users to log in, receive refresh and access tokens from Django, store the token in local storage, and redirect authenticated users to a static p ...

Javascript has ceased functioning on the current server, however it is operational on a different

Need a hand with this tricky issue. The company I'm with has its own website. I've been updating pages on the site for the past few days. After finishing my updates and trying to upload the site, all of a sudden, the JavaScript stopped working. ...

Tips for utilizing a printer to print HTML content in PHP

I've stored HTML content in a variable as shown below: $message ="<div> <table align='center'> <tr><td><h1>Tipo de Documentos Report</h1></td></tr> <tr><td>< ...

OctoberCMS Form submission failure (AJAX handler not located)

I recently created a new component within my plugin directory and added the form HTML to default.htm while also including the component in my partial. However, upon submitting the form, I encountered an error message stating: "AjaxHandler Component:onSend ...

Utilize Boolean operators such as AND, OR, and NOT to locate specific keywords within a text, mirroring the search capabilities

Is it possible to perform Google-style searches in strings using operators like "or", "and" and "not" with regular expressions? For instance, I aim to search for the words "Javascript", "PHP" and "Perl" within a given string in these ways: Javascript an ...

CakePHP and nested AJAX forms causing issues in Firefox 3.5

Is it feasible to create a nested ajax form in cakephp that functions properly in Firefox? $ajax->form(form1...) table row $ajax->form(childForm_rowId) $form->end(childForm_rowId) endrow end table $form->end I h ...

How can one update transitive dependencies to a specific newer version in npm to address CVE vulnerabilities?

Here are the packages that require upgrading. I attempted to update the version and signature of the packages listed in package-lock.json. However, whenever I run npm i after modifying package-lock.json, the changes made to package-lock.json disappear. ...