Developing a Spring MVC application that sends a JSON response to an AJAX

I encountered a problem with JSON parsing that resulted in a SyntaxError: "JSON.parse: bad escaped character" while handling an AJAX success event. The AJAX code in question is as follows:

 $("#ajaxform").submit(function(e) {
  $.ajax({
        url : '/cart/add',
        type : 'POST',
        contentType : 'application/x-www-form-urlencoded',
        data : $(this).serializeArray(),
        dataType: 'json',
        success : function(content) {
            $("#result").append(content.addToCartLayer);
            $.fancybox({
                href : '#result',
                showCloseButton : false,
                enableEscapeButton : false,
                hideOnOverlayClick:false
            });
        },
        error : function(xht, status, ex) {
            console.log("error : " + ex);//JSON.parse: bad escaped character
        }
    });

}

The corresponding Java code snippet is as follows:

@RequestMapping(value = "/cart/add", method = RequestMethod.POST, produces = "application/json")
public String addToCart(@RequestParam("productCodePost") final String code, final Model model,
        @Valid final AusAddToCartForm form, final BindingResult bindingErrors, final RedirectAttributes redirectModel)
{
    // MY LOGIC HERE
    return ControllerConstants.Views.Fragments.Cart.AddToCartPopup;
}

The issue arose when attempting to modify the color value of a product in the cart from "RED" to "R'NB," resulting in the AJAX exception being thrown (JSON.parse: bad escaped character).

I have attempted to resolve the problem by adding @ResponseBody to my method, but to no avail.

So, my question is, how can I address this issue? Any additional details or clarification needed, please let me know.

Answer №1

The reason for this issue is the presence of an invalid character in the new color value: "R'NB". JSON is unable to process the ' character. For more information and potential solutions, you can refer to this link: Resolving JSON.parse error due to bad control character in string literal Hopefully, this provides clarity on the matter.

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

Here is a way to transfer the form data from the modal component to the submit handler

I am currently developing a VUE application that includes displaying a team table with information fetched from the backend using axios and django rest_framework. Everything is functioning properly. However, I encountered an issue when clicking on "new ca ...

RequireJS is timing out while loading the runtime configuration

I keep encountering a load timeout error with my run-time configuration, specifically with common.js. Although I have set the waitseconds value to 0 for files loaded from common.js, the loadTimeout issue persists for common.js itself. index.html <scr ...

Consolidate duplicate list entries and adjust the CSS as needed

Imagine I have an array like this: myarray = ["apple", "apple", "apple", "potato", "apple"]; myarray = ["apple", "apple", "apple", "potato", "apple"]; function listCreate(data) { var output = '<ul>'; $.each ...

NodeJS error: The 'error' event was not properly handled, resulting in a throw er

I've developed a basic web application using React, node-postgres, expressJS, and PostgreSQL DB. The app includes two input fields and a button. Upon clicking the button, the values are saved in the database. While running the ExpressJS server with ...

Error: Unable to access undefined properties while trying to read 'add' value. Issue identified in the code related to "classlist.add" function

I am currently facing an issue where I receive the error message: Uncaught TypeError: Cannot read properties of undefined (reading 'add') when trying to add a class to a div using a button. After researching on Stack Overflow, I stumbled upon a ...

What is the best way to restrict the length and number of lines in a textarea based on pixel dimensions?

I am looking to create a textarea where people can select different fonts, such as "sans-serif" and "serif", to type in text. I plan to have buttons labeled "sans-serif" and "serif" that will change the font of the textarea when clicked. However, there ar ...

Uploading files using ReactJS Ajax

I'm having some trouble uploading a file using React and I need help figuring out the best approach. I've been trying to save the file on change, but it doesn't seem to be working correctly. Whenever I try to submit, I keep running into an e ...

Add a fresh category to a JSON document

Combining Express (Node.js) and Mongoose, I am developing a REST API and attempting to implement JWT token-based login. However, I have encountered an issue. Upon executing the code below: const mongoose = require('mongoose'); const User = mongo ...

Retrieve the red, green, and blue components of a color in the RGB format

When I retrieve "rgb(18, 115, 224)" from a DOM element, I need to convert this color to hexadecimal in order to assign it to a span element. To get the hexadecimal equivalent of the color, I can use the following code snippet: "#" + componentToHex(r) + co ...

What's causing the unexpected rendering outcome in Three.js?

Here is a mesh created in Blender: https://i.sstatic.net/KBGM5.jpg Upon loading it into Three.js, I am seeing this result: https://i.sstatic.net/PCNQ8.jpg I have exported it to .obj format and ensured all faces are triangulated. I am not sure why this is ...

When transitioning between single-page Angular applications using Protractor, a "JavaScript error: document unloaded while waiting for result" may be encountered

I came across this article discussing the issue of a Javascript error related to a document being unloaded while waiting for a result: JavascriptError: javascript error: document unloaded while waiting for result Although the solution provided seems to wo ...

Using a function as an argument within an Angular directive

Looking for a solution to pass a promise-returning function into a directive? Here's what I'm currently doing: In the parent controller, I've created a callback: $scope.myCb = function(data) { console.log(data); } Directive Scope: sco ...

Uploaded images from mobile devices appear to be rotated when viewed on desktop browsers like Chrome and Firefox

I'm facing a strange issue where an image uploaded from a mobile device to my website appears rotated on Chrome and Firefox when viewed on a desktop. However, it displays correctly on mobile browsers like Chrome Mobile and Safari Mobile. It seems tha ...

Load Bootstrap 4 Modal with Ajax

I recently upgraded from Bootstrap 3 to Bootstrap 4.1 Within my applications, I utilize ajax loaded modals. In the layout, I have: <div class="modal fade" id="myModalToFillInfo" tabindex="-1" role="dialog" aria-labelledby="myModalToFillInfoLabel" ari ...

Guide on injecting javascript code containing php variables into a php page

I have successfully developed a PHP page and Javascript code that includes some PHP variables. The code is designed to insert PHP variables into the database using Javascript: <?php $id = "Kevin"; $user = "Calvin"; ?> <!-- include jquer ...

`Wordpress: Streamlining Form Submissions with AJAX Technology`

My goal is to create a filter with checkboxes in Wordpress. To start off, I want to test it by sending a variable via ajax when a checkbox is clicked in the form. Below is the form with checkboxes: <form method="post" id="filter"> <input type=" ...

Accessing a TypeScript variable in Angular2 and binding it to the HTML DOM

While I have experience with AngularJS, delving into Angular2 has proven to be a new challenge for me. Understanding the ropes is still a work in progress. In my list of files, there's a home.ts and a home.html Within my home.ts, this snippet reside ...

Is there a more efficient method than creating a separate variable for the navbar on each individual page where it is being utilized?

Apologies for the unclear title, I struggled to find the right wording and decided it would be easier to illustrate with code. Let's assume I have the following routes: router.get('/chest', (req, res)=>res.render('muscles/chest/chest ...

Tips for altering the contents of a state in react by toggling items in and out

Here's a challenge I'm facing: I need to display products based on the checkboxes toggles. If none of the checkboxes are toggled, the product array should be empty. If the men's checkbox is toggled, only men-related products should be shown, ...

execute an operation without navigating away from the page when a comment is created

Hey there! I am currently using Facebook comments on my website and I am looking for a way to send the page URL to my database or a text file without redirecting the page. I have tried various methods but haven't had much luck. Can anyone help me out ...