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

The ng-disabled directive in AngularJS fails to disable the button as expected

I'm having an issue with setting an input button to disabled when a user selects a specific value from a select box: Here is my select menu: <select id="jobstatus" name="jobstatus" ng-model="associate.JobStatus" class="form-control"> & ...

Like button for Facebook located at the bottom of a static webpage

I am facing an issue with my web application where it does not scroll properly, especially when there is a Facebook button at the bottom. The behavior in Chrome and Firefox is inconsistent and causing some trouble. In Chrome, the div repositions correctly ...

Numerous clocks on display

I am trying to display two clocks on my webpage, but for some reason only one clock is showing up. The first clock script is as follows: <script type="text/javascript"> var tmonth=new Array("January","February","March","April","May","June","July"," ...

My function is named, however, the output is recorded prior to the function completing its execution

I've implemented a function named createUser, designed to save user data in the database. If successful, it should return true; otherwise, false. The code for this function is as follows: exports.createUser = (user) => { const salt = crypto.rando ...

Updating Select Options with Multiple Values using Javascript

My goal is to update the selected value of multiple select elements simultaneously using JavaScript. However, I am facing an issue where my script only updates one select element instead of all of them on the page. Unfortunately, I cannot modify the id att ...

Tips for showcasing the Phaser game screen exclusively within a React route

I am trying to make sure that my game screen only appears on the '/game' route. However, when I initialize it using the method "new Phaser.Game(config)", it ends up displaying on every route including '/home', the default route '/& ...

Distinguishing Between Two Comparable ExpressJS RoutesWhen working with ExpressJS,

I am facing an issue with two routes in my API: /api/persons/:personId and /api/persons/contact. The problem arises when I hit the route api/persons/contactS (with an extra 'S' character) as it mistakenly triggers the API code for api/persons/:pe ...

The php script fails to return any response to Ajax

Why is my code not working with jQuery alert and Firefox response? The database query returns successful records, so what am I missing? Jquery ajax. $.ajax({ type : "POST", url : "include/add_edit_del.php?model=teksten_display ...

Using the Ajax method from a separate class in TypeScript: A step-by-step guide

Recently, I started learning about typescript and ajax. One of the challenges I encountered was while creating a method in typescript for making ajax calls that can be used across classes: myFunc(value: string): JQueryPromise<any> { var dfd = $. ...

The initial value set for the innerHTML property of a div element

I have a requirement in my application where I need to confirm if the container div is empty before adding specific text elements to it. The innerHTML of this div is frequently created and removed within the app, so it's crucial to validate its emptin ...

Oops, seems like there was a problem with parsing the

I have encountered an issue when trying to decode the value of a PHP array sent as JSON format. Here is how I created the array: $ads = $atts['ads']; if (sizeof($ads) > 0) { foreach($ads as $social_item) { $sdbr = $social_ ...

Encountering a 404 error on API routes upon deploying Nuxt to Heroku

I can't seem to figure out the issue here. Everything runs smoothly in development, but once I deploy to Heroku, I keep encountering 404 errors when trying to access routes with Postman (or Axios). What could be the problem? This is my index.js: con ...

Integrating PHP code into a React.js application can provide

I am currently integrating react.js into a section of my app and exploring the possibility of embedding some PHP code into react.js. This would allow me to avoid having to completely rewrite the backend that was originally written in PHP. Here's an ex ...

Creating a redirect button using React Material UI and React Router

I've been exploring how to use Material-UI with React and I'm struggling to figure out the best way to redirect to other pages or components. After reading various articles on different methods of redirection using react-router-dom, I still have ...

What is the best way to showcase multiple selected values in a div using jQuery?

Is there a way to use jquery to populate an empty div with the values selected from a multi-select dropdown? How can I achieve this in the context of the provided code snippet? <select multiple data-style="bg-white rounded-pill px-4 py-3 shadow-sm" c ...

Working with conditional rendering in React Native allows us to easily change text based on different conditions. By utilizing

Hello fellow React Native beginners! I'm currently working on a feature where the text output on the screen changes based on the time of day. Specifically, I want the screen to display 'Morning' if it's morning, 'Afternoon' i ...

When the child component's form is marked as dirty, the parent component can access it

I have implemented a feature in my application that notifies users about pending changes on a form before they navigate away. Everything works as expected, but I have a child component with its own form that needs to be accessed by the guard to check if i ...

Converting SVG to PNG image directly in the browser (compatible with all browsers, including Internet Explorer)

I am currently working with Highcharts and I have a need to convert all the charts displayed on the webpage into images so that I can send them to my server for merging with a master export Excel file. The Excel file already contains some tables and pivot ...

What is causing the delay of my electron event to reach the render process?

I'm currently facing an issue with toggling a switch in my electron app that activates an express server. The expected behavior is for the server to send a message back to the app signaling that it's turned on. However, the problem I'm enco ...

My chart's data gets misaligned when I resize the window, causing issues with the d3

I have 5 HTML elements with the class "container" that will contain 5 SVG images. The ids of these elements are generated programmatically and consist of numbers: <div id="svg-container-total"></div> <div id="svg-container-3"></div> ...