Managing JSON responses from a server using Javascript

I have encountered various similar issues, but none of them have provided a solution for my specific question. On my server, I generate a JSON string and place it in the response:

List<String> list = getSomeList();
JSONArray jsArray = new JSONArray(list);
System.out.println(jsArray);
response.setContentType("application/json");
response.getWriter().write(jsArray.toString());

However, in my javascript handling function, when I attempt to alert the response, it alerts the entire page!

function handleResponse(){    
 if(http.readyState == 4 && http.status == 200){  
  var response = http.responseText;
   if(response){ 
     alert(response); //alert all page!
     var list = JSON.parse(response.toJSON()); //does not work! 
 }       
} 

Question: How can I isolate just the jsArray in JavaScript?

P.S. My understanding is that my JSON.parse(response.toJSON()) fails because the response contains the entire page?

Answer №1

Please note: I am not familiar with java programming language.

On the server-side, it seems like the issue may be that your response is not properly closed after writing your JSON Array, which could allow other text (such as HTML) to be written. You can try the following solution:

response.setContentType("application/json");
response.getWriter().write(jsArray.toString());
response.getWriter().close();

As for the client-side, remember that responseText is a string and does not have a toJSON() function defined. Simply use:

var list = JSON.parse(http.responseText);

and you should be good to go.

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

The $resource.query function will now return an array of characters instead of a single string when splitting strings

Recently, I've been working on utilizing an Angular $resource in my project. Here's a snippet of the code: angular.module('app') .factory('data', function ($resource) { var Con = $resource('/api/data', {}, { ...

Modifying a div element upon the successful completion of an ajax/json request

Currently, I have a form on my webpage for creating a new album. Alongside this form, there is also a delete album form. After successfully creating an album, I want to automatically update the checkbox list in the delete album form with the details of the ...

Locate the div in the array that includes ValueA, and save ValueB from it into a new variable

When the button is clicked, I retrieve the current value of a Select control using the following code... $('#myBtn').on('click', function (clickEvent) { var nameSelected = document.getElementById('mySelectControl').getEle ...

Data is stored in Django Fullcalendar without saving it in the database, instead a primary key is generated

I am currently facing an issue where the actual data is not being saved in the database. Whenever I click the register button after inputting the data, an empty data entry gets saved and a primary key is created. There are no error messages being displayed ...

difficulty in making an https request

My application was developed using OFFICEjs and was functioning properly on LOCALHOST. However, last week it suddenly started throwing an error message - "XHR Error." This issue arose out of nowhere, as I hadn't made any changes to the code over the w ...

Exploring nested objects within an array with LoganSquare

Struggling with parsing JSON data received from the server. My model includes: @JsonField(name = "skills") private ArrayList<Skill> skills; which contains fields: @JsonObject public class Skill { @JsonField private int skillID; @JsonFi ...

Is it possible to make a Venmo API call from the client side without worrying about Access-Control-Allow

Currently, I am developing a small web application using Ember.js and Firebase. At the moment, I do not have a framework in place. My goal is to leverage Venmo's OAuth and API to retrieve usernames, emails, and friends' information. So far, I hav ...

Generate dynamic routes in Next.js only when needed

I'm currently working on a project using NextJS to create a frontend for a database that contains thousands of products, with the expectation of significant growth. The site/products/ route is functioning well, but I wanted to add a route to view indi ...

Is it possible for the JavaScript code to cease execution once the tab is closed?

I am working on a JavaScript code snippet that is designed to execute once a component finishes loading: function HelloThere() { React.useEffect(() => { setTimeout(() => { // code to make a server call to write data to DB ...

Implement the anti-flickering script for Google Optimize in a NextJS/ReactJS environment

While working on a NextJS/ReactJS project, I am experimenting with setting up Google Optimize for some tests. One issue I have encountered is the flickering effect that occurs when Optimize changes visual elements during experiments. To address this probl ...

Combining arrays of objects into one single array

I possess a large array of intricately nested objects, akin to this (imagine adding 76 more products for a clearer picture): [ { "ProductID": 11, "ProductName": "Queso Cabrales", "SupplierID": 5, "CategoryID": 4, "QuantityPerUnit": " ...

Guide on updating variable columns using a JSON object from the request body in a C# web API, utilizing LINQ to SQL

At the moment, I have a code that allows me to update a record like this: //POST: api/Cicmpies/testname [HttpPost("{cmp_name}")] public async Task<IActionResult> UpdateCicmpy([FromRoute] string cmp_name, [FromBody] Cicmpy cicmpy) ...

Updating databases with the click of a checkbox

Currently, I am developing a program for monitoring cars as part of my thesis. My current focus is on user management, and I have come across an issue where the database needs to be updated when the status of a checkbox changes. To visualize checkboxes, y ...

Having trouble editing the Ajax URL in your WordPress plugin?

I recently created and installed a new Plugin in my WordPress site, only to realize that I had the wrong ajax URL set up. After making the necessary changes to the URL in the file, I encountered an issue where the plugin was still not using the updated URL ...

What is the best method for accessing a value in IndexedDB while utilizing service workers?

I am feeling overwhelmed by the concepts of IndexedDB and serviceworkers as I try to transform them into a functional application. Despite my extensive research, including studying various examples, I am struggling to integrate the two technologies effecti ...

Experiencing disconnection from SQL server while utilizing the Express.js API

Im currently working on an API that retrieves data from one database and posts it to another database, both located on the same server. However, I am facing issues with the connections. Initially, everything works fine when I run the app for the first time ...

The issue with Bootstrap 5 navbar dropdown links not functioning on screens smaller than 576px

I'm completely new to this. I managed to set up a functional navbar with a dropdown feature that consists of 3 links. When expanded, each dropdown link displays a card upon clicking, revealing contact information. Everything works perfectly fine...exc ...

How to toggle between checked and unchecked states using jQuery within AngularJS?

After reloading, the checkbox should maintain its checked or unchecked state. This functionality can be achieved using a directive controller. var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {}, $checkboxes = $("#c ...

Click here for more information in JavaScript Reading Link

I am trying to implement a feature where I only display half of the text from a Biography field on the first page, and have a continue reading link that reveals the rest of the text when clicked. I would like to accomplish this using HTML. Can anyone p ...

Converting JSON information into an array within the Swift3 programming language

Having trouble converting my JSON response to an array, as I'm getting an error indicating that the items in the array are nil func getcomments(){ RestApiManager.sharedInstance.getComments(TUTORIAL_ID: id){ response in let comment ...