Encountering the "Invalid JSON primitive" issue when making an AJAX request in MVC

Despite my efforts to resolve the "Invalid JSON primitive" issue by reading various references, I have not been able to find a solution. As a last resort, I am sharing my code in its simplest form and still encountering the error. See below for the minimal code snippet:

var dataObject = {
    'FirstName': $('#FirstName').val(),
    'LastName': $('#LastName').val()
};

$.ajax({
    type: 'POST',
    url: '@Url.Action("Submit", "Home")',
    contentType: 'application/json;',
    dataType: 'json',
    data: dataObject,
    success: function (result) {
        debugger;
        alert('Success');
    },
    error: function (response) {
        debugger;
        alert('Error');
    }
});

I have also attempted using the following dataObject replacement:

var dataObject = {
    'FirstName': 'ES',
    'LastName': 'Dictor'
};

Unfortunately, this did not change the results of the error message.

Regardless of my attempts, the Chrome console consistently shows:

response:
Object {readyState: 4, responseText: "<!DOCTYPE html>
↵<html>
↵    <head>
↵        <titl…nStep step, Boolean& completedSynchronously)
↵-->", status: 500, statusText: "Internal Server Error"}

Inspecting the response.responseText reveals:

<!DOCTYPE html>
<html>
    <head>
        <title>Invalid JSON primitive: FirstName.</title>

At this point, after exhausting all possible solutions, it seems like there may be a simple fix that I am overlooking. Hopefully, someone can identify what I am missing.

Answer №1

When sending an object instead of json data, you should remove the

contentType: 'application/json;',
line in your ajax options. This way, it will default to using
'application/x-www-form-urlencoded; charset=UTF-8'
. Alternatively, you can use JSON.stringify() to convert the object into a JSON string.

Just a side note: Quoting property names is not necessary. For example,

var dataObject = {
    FirstName: $('#FirstName').val(),
    ....

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

Using Javascript's regular expressions to add double quotes around JSON values that are not already enclosed in quotes

Dealing with improperly formatted JSON values can be a challenge. The response I am working with is from a Java Servlet, specifically a hashmap, over which I have no control. Initially, it looked like this: { response={ type=000, products=[{id=1,name=prod ...

Is there a method to receive a clean JSON response using AFNetworking in Objective-C?

My current iOS app, written in Objective-C, uses AFNetworking for networking and returns responses as Dictionaries. I'm interested in experimenting with Codable in Swift 4 and want to switch to a pure JSON response. Is this possible? What are my optio ...

Leverage the power of Laravel8 to simultaneously update two tables in one go

In my database, I currently have two tables: https://i.stack.imgur.com/TObcy.jpg https://i.stack.imgur.com/U6IhT.jpg The form that I am working with is shown below: <form id="contratform" method="post" action="contrats" ...

Clicking on a link with an onclick method renders selenium ineffective in producing any action

The specified element is: <a href="#" onclick="submitViaAjax(null, url);return false;">Add</a> After using element.click() to try clicking the link, the onclick method fails to execute. Is there a way to ensure the method is executed success ...

Using JavaScript and Codigniter to populate a drop down box with an array

One of the key elements in my Codeigniter project is the $location variable, which is set using sessions and can represent cities like 'Austin', 'Houston', and so on. Each location has its own unique tours to offer. Instead of manually ...

With Vite, Vue.js can generate 400 requests from a single function invocation

Is it possible that there is a bug with Vite.js or is this behavior normal? I noticed that when using date-fns in Vite.js, it's making 400 requests. It seems like just one function call is resulting in 400 ajax requests being triggered by date-fns. A ...

What is the best way to include an API key in the response to an Angular client application?

I'm working on transferring my API key from NodeJS to an Angular client application using $http, but I am unclear on the approach. Below is a snippet from my NodeJS file: // http://api.openweathermap.org/data/2.5/weather var express = require(' ...

Access + authentication code

After successfully using my login script in Postman, I ran into issues when attempting to integrate it with React.js for posting to the server. The problem lies in the fact that when the script checks for the user, it fails to return the return result. It ...

The efficient method of storing application activity logs using one schema and minimal details in MongoDB within a Node.js environment

Looking for a way to efficiently log application actions in a Node.js project with MongoDB database. We aim to include limited information such as success, action name, user id, time, etc. Any suggestions or best practices for achieving this in Node.js w ...

Setting a default value for an empty array in Joi

Struggling with the syntax to set a default value for an empty or missing array key. Joi.object({ items: Joi.array().empty([]).items(Joi.number()).default([42]), }) { items: [] } or { } In both scenarios, I want the default value of [42] to fill ...

What could be the reason for the absence of the HTTP response in the network tab of the Chrome debugger?

After utilizing Postman to test my web service, I was able to find the WS's response in the http response body. However, when I made a call using ajax in my web application, I encountered an issue where I could no longer locate the response. The tab ...

Selection of Dropdown results in PDF not loading

I am facing an issue with my function that selects a PDF from a dropdown list. Instead of loading and displaying the PDF, it only shows a blank modal. Any suggestions on how to fix this? <li> <a href="">Case Studies</a> <ul clas ...

Using MATLAB's jsonLab for parsing a JSON data structure

I am facing an issue while trying to parse a JSON object into a cell array in MATLAB. The error I encounter when parsing the filename is... `Error using loadjson>error_pos (line 431) JSONparser:invalidFormat: String starting with " expected at position ...

What are the best techniques for achieving flawless ring geometry in three.js?

I'm struggling to achieve perfect ring geometry in three.js, similar to the image here: https://i.sstatic.net/ArxKa.png After spending over a day troubleshooting, my code currently looks like this: var scene = new THREE.Scene(); var camera = new TH ...

Instructions for applying a specific style to TextFields using a theme provider

Custom transitions and colors have been added to the textfields using the makeStyles hook in the component. The issue lies in needing to define these customs every time they are used in a component. There is a desire to establish them in the theme provid ...

Would it be acceptable to save a digital signature and the public key of the signer within a JSON document?

For my current project, the process involves signing a string with a private key. I am considering storing both the public key and signature in a JSON file for future verification. Is this method secure enough, or would using PKCS#7 be more advisable? Wh ...

JSON failing to show all values sent as a string

In a div element there is a table with 3 rows, a textarea, and a button. The JSON data populates the first 3 rows correctly but the textarea remains blank. My goal is to display the previous record from the database in the textarea. function ChangeLoadin ...

Bring in the Stencil JS library from a separate Stencil JS library

Within my collection of Stencil JS web components, I have two distinct libraries - library-a and library-b. These are not complete applications, but rather separate npm packages containing various components. I am interested in incorporating certain compo ...

Sequencing when employing v-for

When utilizing the v-for to loop through an array as shown below: <ul id="example-1"> <li v-for="item in items"> {{ item.message }} </li> </ul> The items are displayed vertically as follows: Item 1 Item 2 Item ... Item ...

Combining various JSON files into a singular dataframe

I've been facing challenges in merging multiple JSON files into a single database despite trying various solutions from online resources. These files contain sensor data, and so far I have completed the following steps: 1. Unzipped the files - resul ...