Ajax Syntax Error: Unexpected Token U

I have been struggling all day with an issue while trying to send json data via ajax to Express. Here is how my ajax code looks like:

$('#saveClause').click(function () {
    var username = document.getElementById('postUserName').innerHTML;
    var clauseTitle = document.getElementById('modalTitle').innerHTML;
    var clauseDescription = document.getElementById('modalDescription').innerHTML;
    var clauseText = document.getElementById('modalText').innerHTML;

    $.ajax({
        url: "/classes/updateAssignment",
        type: "post",
        dataType: "json",
        data: {
            username: username,
            title: clauseTitle,
            description: clauseDescription,
            text: clauseText
        },
        cache: false,
        contentType: "application/json",
        complete: function () {
          console.log("complete");  
        }, 
        success: function () {
            console.log("success");
        },
        error: function () {
            console.log("Process Error");
        }

    });
});

This is what my Express Classes routes look like:

router.post('/updateAssignment', function (req, res) {
    console.log(req.body.username)
    console.log(req.body.title);
    console.log(req.body.description);
    console.log(req.body.text);
    res.type('json');
    res.send({
        some: JSON.stringify({
            response: 'json'
        })
    });


});

When I sent a postman post request to the URL with this JSON object:

{
    "username":"testing",
    "title":"123",
    "description":"j456",
    "text":"seven"
}

Express was able to log all the details in the console without any issues, so it seems like there might be a problem with my ajax request as it's giving me an unexpected token u error. Any suggestions on what might be causing this?

Answer №1

Consider deleting the contentType: "application/json",

If Postman was used without headers, it's probable that this is causing the parsing to fail.

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

What is the best way to securely store a JWT token in an HTTP only cookie?

My approach in building an app involved using a JWT from the server after logging in successfully to authorize access to any /api route on my Express.js backend server. In contrast, AngularJS stored this token in session storage and utilized an auth inter ...

Setting the selected value of a static select menu in Angular 2 form

I'm having an issue with my Angular 2 form that includes a static select menu. <select formControlName="type" name="type"> <option value="reference">Referentie</option> <option value="name">Aanhef</option> &l ...

Can you explain the meaning of <!-- in javascript?

Have you ever noticed the <!-- and --> characters being used around JavaScript code like this: <script type="text/javascript"> <!-- function validateForm() { if(document.pressed == 'Submit') { ...

Determine if offcanvas element is visible upon initialization in Bootstrap 5 Offcanvas

I have a search-filter offcanvas div for location and property type on this webpage: On larger screens (desktop), the offcanvas is always visible, but on smaller screens (mobile), it is hidden and can be toggled with a button. This functionality works per ...

What could be causing ng-submit to not successfully transmit data?

I'm currently going through this Yeoman tutorial, but I'm encountering some issues. The new todo is not being added to the $scope.todos as expected, and I'm struggling to identify the reason behind it. You can access the code here: Upon c ...

What's the process for changing this arrow function into a regular function?

Hello from a child component in Vue.js. I am facing an issue while trying to pass data from the parent via sensorData. The problem lies in the fact that the arrow function used for data below is causing the binding not to occur as expected. Can anyone gu ...

Is using $timeout still considered the most efficient method for waiting on an Angular directive template to load?

When it comes to waiting for a directive's template to render, our team has been following the approach of enclosing our DOM manipulation code in a $timeout within the directive's link function. This method was commonly used in the past, but I&ap ...

Continuous scroll notification within the fixed menu until reaching the bottom

I'm looking to achieve a scrolling notification message that stays fixed at the bottom of a top-fixed menu while the body content continues to scroll normally. Here's an example in this fiddle: HTML: <div class="menu-fixed">I am a fixed me ...

Fetching weather data from the Darksky.com API in JSON format

My goal is to retrieve weather data in JSON format from the Darksky.com API. To do this, I first successfully obtained my latitude and longitude using the freegoip.com API. However, the Darksky API requires both longitude and latitude before it can provid ...

Invalid mime type for HTML5 mode

I have successfully set up my redirect, but now all my style sheets are being served as text/html because they are going through core.index. Strangely, I only get this error for style sheets and not for JS files. How can I fix this issue? Error: Res ...

Wrapping a group of elements with opening and closing tags using jQuery

I have a collection of distinct elements, like so: <section class="box-1"></section> <section class="box-2"></section> <section class="box-3"></section> My objective is to enclose all three elements within a div with a ...

Tips for storing HTML form data in a local JSON file without the need for PHP or Node.js dependencies

I'm interested in saving any information panel in an HTML file to a local JSON file. For example, if there are blocks like this: <div class="panel"> <div> <input type="text" name="producttype" id=&q ...

Do you need to redeclare the type when using an interface with useState in React?

Take a look at this snippet: IAppStateProps.ts: import {INoteProps} from "./INoteProps"; export interface IAppStateProps { notesData: INoteProps[]; } and then implement it here: useAppState.ts: import {INoteProps} from "./interfaces/INo ...

Using angular.copy function to copy an array with a custom property

Let's use the example below to illustrate an issue: var ar = [4, 2, 3]; ar.$x = 'something'; var br = angular.copy(ar); console.dir(br); After copying ar to br, the $x property is no longer present. This is because when Angular copies an a ...

Is this code in line with commonly accepted norms and standards in Javascript and HTML?

Check out this Javascript Quiz script I created: /* Jane Doe. 2022. */ var Questions = [ { Question: "What is 5+2?", Values: ["7", "9", "10", "6"], Answer: 1 }, { Question: "What is the square root of 16?", Values: ["7", "5", "4", "1"], Answer: ...

Angular2's $compile directive functions similarly to AngularJS 1's $compile directive

I am currently in the process of migrating my project from Angular 1 to Angular 2 and I am in need of a compile directive. However, I am struggling to rewrite it to achieve the same functionality as before. app.directive("compile", compile); compile.$inje ...

Troublesome php ajax application failing to function

Despite creating a simple PHP and AJAX application, I am encountering issues and unable to identify the root cause. Below is my code snippet: <?php $grId = $_GET["groupId"]; $limit = $_GET["limit"]; if ($limit <= 0) { $limit = 10; } $serverna ...

Struggling to retrieve data from a JSON array structure in CodeIgniter

I've got this JSON array tree passed to a view in a variable: [{ "root":"0", "id":"19", "name":"Rose", "childs":[{ "root":"19", "id":"22", "name":"Ceema", ...

Is there a way for me to extract a smaller segment from an ID label?

I am working on a web development project and I have a set of buttons within a specific section. Each button has an id in the format of #balls-left-n, where n ranges from 1 to 15. My goal is that when a user clicks on one of these buttons, I want to extra ...

Is there a way to extract information from an HttpClient Rest Api through interpolation?

I am currently facing an issue with a component in my project. The component is responsible for fetching data from a REST API using the HttpClient, and the data retrieval seems to be working fine as I can see the data being logged in the Console. However, ...