What is the best method for sending JSON data to an ASP Server through AJAX?

I'm currently working on a website built with ASP.NET that requires data retrieval from CloudKit. Utilizing CloudKit JS, I successfully retrieve a record from CloudKit and aim to send the data to the server using C# in my JavaScript code. I can convert the JSON object of the retrieved record into a string with JSON.stringify(record);, however, I'm facing difficulties in sending it to the server through AJAX. Below is the snippet of my code attempting to send the data via AJAX:

function afterRecordLoaded(record) {
            var decodedRecord = JSON.stringify(record);
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.open("POST", "/receive?type=specific&" + "data=" + decodedRecord, true);
            xmlhttp.setRequestHeader("Content-Type", "application/json");
            xmlhttp.send();
}
afterRecordLoaded(record);

Although I can manually perform the request correctly using the Browser Dev Tools console, when AJAX executes it, an HTTP Error 400 occurs. Essentially, typing the same URL (with correct parameters) directly into the address bar works, but when AJAX tries to do the same, it fails with an HTTP Error 400.

Below is the C# code for the page tasked with handling the incoming request:

    var token = antiforgery.GetAndStoreTokens(HttpContext).RequestToken;

    var type = Request.Query["type"];
    var data = Request.Query["data"];

    if (type == "specific")
    {
        if (data != "")
        {
            PostProcessor.processPostData(data);
        }
        else
        {
            Response.StatusCode = 400;
        }
    }

Upon researching, I found that others have encountered the same issue and resolved it by implementing an anti-forgery token. However, I'm unsure how to incorporate anti-forgery tokens into my code. Any guidance on resolving the HTTP Error 400 or incorporating anti-forgery tokens to address the issue would be greatly appreciated. Apologies if this question seems scattered or basic, as I am relatively new to working with ASP.NET. Thank you.

Answer №1

Perhaps when you input data through the console, it is not empty. However, when using XHR in your code, if the data is empty, the request will trigger the else expression in asp.net with Response.StatusCode = 400;.

It is possible that there are errors in your code causing JSON.stringify(record) to return nothing.

Additionally, when making a post request, the data (payload) should not be sent as a query parameter as you are doing. It should be included in the payload as shown below.

var decodedRecord = JSON.stringify(record);
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/receive?type=specific", true);
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(decodedRecord);

Answer №2

The solution turned out to be quite straightforward. I had mistakenly used the format of a GET request instead of a POST request. To fix the issue, I simply had to update the code from

xmlhttp.open("POST", "/receive?type=specific&" + "data=" + decodedRecord, true);
to
xmlhttp.open("GET", "/receive?type=specific&" + "data=" + decodedRecord, true);
.

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

Default Redirect in IIS

Is there a way to ensure that when a default redirect is set to a relative path at the website level in IIS7, it redirects to https instead of http? For example, if the host is abc.com and the login page is abc.com/myapp/login.aspx, setting the default re ...

Load Form with Json Data from LocalStorage Key-ID to Auto-Populate Fields

After successfully setting the ID in localStorage, I now need to retrieve and display only that specific record from my JSON data. The content of my localStorage is: This information is obtained from my JSON data after a button click. The challenge is us ...

Utilizing URIs as identifiers for GUI components in react.JS

I am looking to develop a front end using React.js where I can pass URI as name/id properties to GUI components. My goal is to then map these URI keys to corresponding values. When the web page is requested, it should display the mapped value. <input t ...

Facing troubles with the file format while trying to upload a CSV file to dropbox.com

My goal is to develop a Chrome extension that allows users to upload files directly to Dropbox.com. While most aspects of the functionality are working smoothly, I am encountering some challenges with the CSV format. The code snippet below demonstrates how ...

Bringing XML data into a datagridview

I've been searching high and low for a solution to this issue, but I can't seem to find anything that does the trick. In my application, there's a datagridview where data is added using a textbox. I've managed to save the information to ...

What is the best way to run code once a callback function has completed its task?

I am looking for a way to execute line(s) of code after every callback function has finished processing. Currently, I am utilizing the rcon package to send a rcon command to a Half-Life Dedicated Server (HLDS) hosting Counter Strike 1.6 server and receive ...

transferring information from browser storage to the server

On my web app, there is a feature that saves data to local storage and converts it to a JSON object. I'm interested in passing this local storage data to my server using AJAX, so that other clients of the web app can access it. Is there a way to accom ...

Leveraging keyboard input for authentication in Angular

Would it be possible to modify a button so that instead of just clicking on it, users could also enter a secret passphrase on the keyboard to navigate to the next page in Angular? For example, typing "nextpage" would take them to the next page. If you&apo ...

Trigger Ajax.ActionLink with Razor syntax when a value is updated

In my View, there are multiple criteria elements such as a Supplier TextBox, a LastMonth dropdown, and a Months Textbox. @using JouleBrokerDB.ViewModels; @model AssignPayReportToDepositViewModel @{ ViewBag.Title = "View"; } <lin ...

Checking connectivity in an Ionic application

Within my Ionic application, I am faced with the task of executing specific actions depending on whether the user is currently connected to the internet or not. I plan on utilizing the $cordovaNetwork plugin to determine the connectivity status within the ...

Encountering difficulty selecting a dropdown sub-menu using Selenium WebDriver

I'm currently working on automating a website with selenium webdriver. The issue I'm encountering is that when I try to click on a menu item, the submenu pops up (actually a misplaced dropdown, UI issue), and although I can locate the element of ...

Save the output of a function in node.js

I have created a function that utilizes the nodejs module recursive-readdir to read all files within a folder recursively. The function is functioning correctly, but I am facing an issue with exporting the 'routes' array using 'module.export ...

Locate Checkbox by its Attribute Name and Value

On my webpage, there are multiple groups of checkboxes. In one particular group, I have added a custom "documentcategory" attribute to each checkbox. My goal is to identify all the checkboxes on the page that have the "documentcategory" attribute with a va ...

Having difficulty with delaying the loading of a div layer and javascript after the page has initially loaded

I've been struggling to make this script wait a few seconds after the page has loaded, but I haven't been successful so far. Despite trying some solutions from similar questions here, nothing seems to be working. Any help you can provide would b ...

Step-by-step guide on transferring an HTML5 sqlite result set to a server using AJAX

Imagine I have a scenario where I receive a result set as shown below: db.transaction( function(transaction) { transaction.executeSql( 'SELECT col1, col2, col3 FROM table;', [],function(transaction, result){ //need to find a ...

MVC 3 with MVCScaffolding now utilizes SQLCe instead of Express, resulting in no database file being generated

I recently switched to using the new MVCScaffolding for my upcoming CMS project and it has been incredibly useful. However, I encountered an issue when attempting to change the default database from SQLExpress to a local SQLCe database. According to this ...

Tips for overlaying text onto a canvas background image

I'm curious about how to overlay text on top of an image that is within a canvas element. The image is a crucial part of my game (Breakout), so it must remain in the canvas. I've tried adding text, but it always ends up behind the image, which is ...

Creating an array from objects without manual effort

Greetings everyone, currently I am structuring my array in the following manner: var piece1 = new DialoguePiece(null, questions[0], 0, 0, 4, 1); var piece2 = new DialoguePiece(null, questions[1], 1, 0, 2, 3); var piece3 = new DialoguePiece(scripts[1], nul ...

Using AngularJs, you can access the document.body.onfocus event within the controller of

I am attempting to detect when the user closes or cancels the File Upload Window <input type="file"> Since there isn't a built-in listener for the close event of the file upload, I am trying to capture it using the document.body.focus event, s ...

What are the steps to validate an Ajax form using Dojo JavaScript?

Currently, I am in the process of validating a form that has been written in Javascript/Dojo before sending it via Ajax. Here is the code snippet: <script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojo/dojo.xd.js" type="text/javascript" djConf ...