Ways to retrieve information from an ajax request within an MVC controller

Within my MVC controller, I have implemented a method to query a database and return a JSON object. To achieve this, an ajax call is necessary to provide a date for the database query. However, I am encountering an issue where null is being passed to the controller within my current configuration.

Here is an excerpt from my ajax request:

$(document).ready(function () {
        setInterval(function () {
            $.ajax({
                type: "POST",
                url: '@Url.Action("GetChartData", "Plot")',
                dataType:'json',
                data: '04-15-2019 15:49:00',
                success: function (result) {
                    console.log(JSON.parse(result));
                }
            });
        }, 10000);
    });

The corresponding controller code looks like this:

[HttpPost]
public JsonResult GetChartData(string timeStamp)
{
    string output = queryDatabase(timeStamp);
    string jsonOutput = new JavaScriptSerializer().Serialize(output);
    return Json(output, JsonRequestBehavior.AllowGet);
}

When analyzing the code flow after calling queryDatabase, the timeStamp variable consistently appears as null. What could be the underlying cause of this issue?

Any insights or suggestions would be greatly appreciated!

Answer №1

Here is a suggestion for your code:

$(document).ready(function () {
    setInterval(function () {
        $.ajax({
            type: "POST",
            url: '@Url.Action("GetChartData", "Plot")',
            dataType: 'json',
            data: {timeStamp: '04-15-2019 15:49:00'},
            success: function (result) {
                console.log(JSON.parse(result)
            }
        });
    }, 10000)
});

You can implement the following in the controller:

[HttpPost]
public JsonResult GetChartData()
{
    var timeStamp = Request["timeStamp"];
    var output = queryDatabase(timeStamp);
    var test = new JavaScriptSerializer().Serialize(output);
    return Json(output, JsonRequestBehavior.AllowGet);
}

Answer №2

To ensure the controller reads a simple type from the request body, add the [FromBody] attribute:

 using System.Web.Http;
 [HttpPost]
 public JsonResult GetChartData([FromBody]string timeStamp)
 {
        string output = queryDatabase(timeStamp);
        string test = new JavaScriptSerializer().Serialize(output);
        return Json(output, JsonRequestBehavior.AllowGet);
 }

Answer №3

When making an Ajax call using the Post type and setting the dataType to JSON, ensure that you pass the data in the format of {title:data}. In your specific case, it should look like this:

$(document).ready(function () {
    setInterval(function () {
        $.ajax({
            type: "POST",
            url: '@Url.Action("GetChartData", "Plot")',
            dataType: 'json',
            data: {timeStamp: '04-15-2019 15:49:00'},
            success: function (result) {
                console.log(JSON.parse(result))
            }
        });
    }, 10000)

In your controller, the data will automatically be captured as an argument. Make sure to double-check the URL in your Ajax call for accuracy.

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

Dealing with multiple parameters within the app.param() function

Currently, I am developing an API using Express.js and facing a challenge in implementing an app.param() function for handling the id parameter in a GET request: app.param('id', (req, res, next, id) => { const envelopeIndex = Number(id); ...

What is the process for establishing a key on the request header to authenticate in Node.js?

I am a novice in the world of nodejs. My current project involves creating a basic server that writes JSON data to a CSV file. However, I have encountered a stumbling block: For authentication purposes, the request header must include an “appKey” para ...

Angular: displaying dates in a specific format while disregarding time zones

Is there a way to format date-time in Angular using DatePipe.format() without converting timezones, regardless of location? For instance, for various examples worldwide (ignoring time differences) I would like to obtain 07/06/2022: console.log('2022-0 ...

A Vue component nested within another Vue component

Hey there! Check out this snippet of HTML code: // index.html <div data-init="component-one"> <...> <div data-init="component-two"> <button @click="doSomething($event)"> </div> </div> This part basically invol ...

Issues encountered with the functionality of face-api and tensorflow.js within the browser

I've been trying to execute this example in the browser Check out the example here Specifically looking at this code snippet <!DOCTYPE html> <html> ... (Contents of the code snippet) ... </body> </html> Unfortunately, I&apos ...

I'm encountering a type error every time I attempt to render an EJS page. Could someone please take a look and help me troubleshoot?

Below is the index.js code: CODE HERE const express = require('express'); const app = express(); const path = require('path'); app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded app.use(ex ...

Having trouble displaying images when uploading to a remote server

I recently uploaded my website to a remote server, but I am encountering an issue with viewing the images that I have referenced in the following code block: <a href="ProductDetails.aspx?productID=<%#:Item.ProductID%>"> <img src="/C ...

Initiate the function once the condition is satisfied (contains the class "in-view")

Here is the code for an animation: var setInter = null; function startAnimation() { var frames = document.getElementById("animation").children; var frameCount = frames.length; var i = 0; setInter = setInterval(function () { fr ...

Issue with Navigation bar: Bootstrap menu fails to open upon clicking

My Bootstrap menu is experiencing an issue where it fails to open when I click on it. This means that I can't see any items in the menu. However, when I press the "Down key" on my keyboard, it opens immediately. This issue seems to occur specifically ...

The userscript will keep the window open as long as it remains inactive

Hello everyone, I'm excited to join the StackOverflow community and dive into userscripts for the first time! Putting aside any unnecessary details, I'm encountering a small issue with a script I recently created. (function () { $("#enbut"). ...

When comparing `xhr.onload = () => {resolve();}` and `xhr.onload = resolve();`, it is important to note the distinction in syntax

function bar(){ return new Promise((resolve,reject)=>{ const xhr = new XMLHttpRequest(); xhr.open(method,url); xhr.onload = ()=>{ resolve(xhr); }; xhr.send(); }) } The code snippet shown above performs as expected Howe ...

Implementing conditional reduction in JavaScript arrays

I've encountered an issue with the filter and reduce methods. I am attempting to calculate the sum of "smc" values only when "A" equals 2020 from the given array below: arr = [{A:2020, smc:1},{A:2020, smc:2}, {A:2021, smc:3}] My attempted solution so ...

Utilizing the Facebook Like Button with ASP.NET MVC in C#

I have recently developed a website showcasing various products, with the intention of displaying product details when users click on each item. I am looking to integrate the Facebook Like Button into these product pages. After consulting http://developer ...

Understanding @@iterator in JavaScript: An in-depth look

Can someone shed some light on the mysterious @@iterator? It keeps popping up in tutorials but no one seems to provide a clear explanation of what it actually is. Is it a symbol literal or something else entirely? ...

What could be causing my Link to malfunction in my about.js file?

I've encountered an issue where clicking the link in my app doesn't produce any result, and I'm unsure of the cause. Below is the content of my app.js file: import './App.css'; import {BrowserRouter as Router, Routes, Route} from ...

React has reached the maximum update depth limit

In my current project, I am developing a react application that involves a user inputting a search term and receiving an array of JSON data from the backend. On the results page, I have been working on implementing faceted search, which includes several fi ...

Resize the Excel DNA array to return vertically

I am experimenting with creating dynamic arrays using the Excel-DNA API. While I have managed to generate the desired output, I am looking to format it vertically. Below is the C# code for my User Defined Function (UDF). I referred to this link as a guide ...

Animations are failing to run within a Bootstrap card when using Vue rendering

I have utilized Bootstrap cards to display pricing information in my project. I implemented a collapse feature for half of the card when the screen size is equal to mobile width. While using vanilla Bootstrap, the animation worked seamlessly with the col ...

Most effective method for exporting data to a JSON file

I possess an array of weather data for various "stations," with most being situated at airports. This data has been gathered from web APIs and is currently presented as unordered arrays. As an example: Station: Chicago (O'Hare Airport) Temperature: ...

Modifying the input value within the "input" event handler stops the firing of the "change" event in Chrome and IE, although this does not occur in Firefox

Within this code snippet, I have an "input" event handler that updates the input value as the user types. Additionally, there is a "change" event handler to monitor any modifications made to this field. However, there seems to be an issue where the "change ...