Transmitting JSON object and JavaScript variable via AJAX communications

I am attempting to send a JSON object and two JavaScript arrays in the same AJAX call.

However, I keep encountering the following error:

    System.ArgumentException: Invalid JSON primitive: object

I suspect that this error is related to the different variable types being passed.

Can you spot any obvious errors?

Thank you

    var requestData = {
    "deptCode": userVar,
    "roundID": parseInt(roundIDVar),
    "moduleCode": moduleCodeVar,
    "priority": parseInt(priorityVar),
    "day": parseInt(dayVar),
    "start": parseInt(timeVar) - 8,
    "length": parseInt(lengthVar),
    "weeks": weeksNum,
    "capacity": parseInt(studentsVar),
    "type": roomTypeVar,
    "otherReqs": otherReqs
};
var obj = JSON.stringify(requestData);

$.ajax({
    type: 'POST',
    url: '/create/Submit',
    error: function (xhr, ajaxOptions, thrownError) {
        alert("Submission Failed. Please Reload and Try Again.");
    },
    data: { JSONdata: obj, weeks: weeksVar, facilities: facilitiesValue },
    datatype: 'html',
    contentType: 'application/json',
    processData: false,
    async: false,
    success: function (data) {
        alert(data);
    }
});

Controller

     public ActionResult Submit(request JSONdata, String[] Weeks, String[] facilities) {
        ViewBag.module = JSONdata.weeks;
        if(JSONdata.otherReqs == null){
            JSONdata.otherReqs = "None";
        }
        JSONdata.sent = 1;
        JSONdata.status = 0;
        JSONdata.viewed = 0;
        JSONdata.booked = 0;
        db.requests.Add(JSONdata);

        try
        {
            db.SaveChanges();
        }
        catch (DbEntityValidationException e)
        {
            foreach (var eve in e.EntityValidationErrors)
            {
                Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                    eve.Entry.Entity.GetType().Name, eve.Entry.State);
                foreach (var ve in eve.ValidationErrors)
                {
                    Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                        ve.PropertyName, ve.ErrorMessage);
                }
            }
            throw;
        }

        if(Convert.ToInt16(JSONdata.weeks) == 1){
            for (var i = 0; i < Weeks.Length; i++) {
                Weeks_request newWeek = new Weeks_request();
                newWeek.week = Convert.ToInt16(Weeks[i]);
                newWeek.requestID = JSONdata.requestID;
                db.weeks_request.Add(newWeek);
                db.SaveChanges();
            }
        }
        return View();
    }

Answer №1

Opt for the conventional approach by setting traditional: true in your ajax request.

$.ajax({
type: 'POST',
url: '/create/Submit',
error: function (xhr, ajaxOptions, thrownError) {
    alert("Submission Failed. Please Refresh and Try Again.");
},
data: {JSONdata:obj,weeks:weeksVar,facilities:facilitiesValue },
datatype: 'html',
contentType: 'application/json',
processData: false,
async:false,
traditional: true,
success: function (data) {
    alert(data);
}

});

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

I'm having trouble pinpointing the issue in my code

For some reason, the first button in the div in this code is not working on HTML files. I have tried multiple JavaScript and HTML validators but none of them seem to work. Surprisingly, it works fine on codecademy.com and w3schools.com, but the issue persi ...

Error 403 occurs after submitting the form

Recently, I encountered a 403 error when attempting to submit the form on this page. Interestingly, when I directly accessed the new page by typing the URL into my browser, it loaded without any issues. The PHP code in the initial page looks like this: & ...

Encountered an issue when attempting to utilize `npm start` within a React JS project following

https://i.stack.imgur.com/yII3C.png Whenever I attempt to run npm start in the vsCode terminal, an error pops up as shown in the image above. In the picture provided, you can see that my package.json only contains a start script. Can anyone offer assistan ...

Leverage JavaScript to run a snippet of PHP code directly (without utilizing a separate PHP file)

I am looking for a way to integrate PHP into my web page using JavaScript and AJAX. I want the PHP file to be included and executed as if it is part of the native page, allowing me to utilize features like GET requests. <div id="firstAjaxDiv">Defaul ...

Combining duplicate nodes in JSON with JSON4S Merging

Before flagging this as duplicate, I want to clarify that I have already reviewed the following question: Remove duplicates and merge JSON objects. (I borrowed an example from there) I am currently working on a scenario that requires merging JSON data sim ...

What are the reasons behind the inability to import an image file in Next.js?

Having an issue with importing image file in Next.js I'm not sure why I can't import the image file... The image file is located at 'image/images.jpg' In Chrome browser, there are no error messages related to the image, However, in ...

Utilizing Observable Data in Angular 4 TypeScript Components

Looking to extract and assign a JSON value obtained from an API into a variable. Here is an example: TS this.graphicService.getDatas().subscribe(datas => { this.datas = datas; console.log(datas); }); test = this.datas[0].subdimensions[0].entr ...

Are multiple instances of ajax being executed within the modal?

Currently, I am working on a feature that requires an Ajax request. To begin with, the process involves opening a modal by clicking a button with the class '.open-email-modal'. Within this modal, there are two input fields to enter registration d ...

What is the method for invoking an imported function in a template?

Let's analyze the code snippet below, which utilizes a method and an imported function: <template> <div> {{sayHello()}} {{sayDate()}} {{DateTime.now()}} <div> </template> <script> import {DateTime} from & ...

Utilizing Axios for Vue Multiselect on select/enter Event

I have successfully implemented a Vue Multiselect feature that retrieves options from my database using an axios call. This functionality works great as it allows users to select existing options or add new ones to create tags. While this setup is working ...

Can a CSS hover effect transition modify the color scheme?

I have multiple buttons on a single page, and I want the hover effect to be applied to all of them with just one code using jQuery. Please review my code below. $(document).ready(function(){ $('.button').hover(function(){ var bc=$(this ...

Toggle the visibility of items based on the user's login status

Below is the code snippet for when the user is logged out: <div class="fusion-secondary-main-menu"> <div class="fusion-row"> <?php avada_main_menu(); ?> <?php avada_mobile_menu_search( ...

Using the ESNEXT, Gutenberg provides a way to incorporate repeater blocks that

If you're like me, trying to create your own custom Gutenberg repeater block with a text and link input field can be quite challenging. I've spent hours looking at ES5 examples like this and this, but still feel stuck. I'm reaching out for ...

It is not possible to transfer information to a JSON document using node.js filesystem and browserify

In an attempt to convert incoming input data from a form into JSON format for storage without a backend, I am exploring the use of Node.JS module "fs" or "file-system". To make this work in a browser environment, I am using Browserify for bundling as it r ...

A method for determining the quantity of <li> elements within a <ul> container while applying specific conditions

I am currently using document.querySelectorAll('ul > li').length to count the total number of items in my list. However, I am wondering if there is a way to count only those items that meet a specific condition. For example: <ul> < ...

Incorporate a fresh key-value pair into the Redux Toolkit's state

I am currently working on an application that enables users to create and modify recipes. To manage the state, I have chosen to utilize React Toolkit and Redux. Here is an example of the state structure: const ingredients = [ { ingredientName: &apos ...

The ui.bootstrap.carousel component seems to be missing from the display

My Carousel is not displaying for some unknown reason. I have customized the implementation based on my project requirements which differ slightly from the standard guidelines. Despite this, it should function correctly as detailed below. By clicking on m ...

Incorporating video.js into an Angular website application

I've encountered a strange issue while attempting to integrate video.js into my angular app. <video id="example_video_1" class="video-js vjs-default-skin" controls preload="none" width="300" height="264" poster="http://video-js.zenco ...

What content appears post-iframe?

After researching for a while, I've only come across information about text displayed after a broken iframe on this topic. However, what I actually want to do is display text below an iframe set at 90% height, like so: https://i.sstatic.net/KHXI3.png ...

I am attempting to implement multiple ng-repeats in order to access and display data from a third level array in my JSON within a table, but I am encountering difficulties in getting it to function correctly

I'm attempting to nest an ng-repeat but it seems like my approach is incorrect. I want to display all the line items in the JSON. Since the JSON value I'm trying to display is a 3rd level array, I attempted nested ng-repeat but it doesn't s ...