Utilizing ajax to transfer local storage data to a controller

I am looking to access the information stored in localstorage on the server side, but that's a story for another time.

Within my view, I have this button:

<div style="float:right;">
    <input id="btnTest" type="button" name="test Json Button" value="test Json Button" onclick="sendLocalStorage();" class="btn btn-default" />
</div>

This JavaScript function is triggered by the button:

function sendLocalStorage() {

    var JsonLocalStorageObj = JSON.stringify(localStorage);
    
    $.ajax({
        url: "/MyControllersName/Test",
        type: "POST",
        dataType: 'json',
        data: JsonLocalStorageObj,
        contentType: "application/json; charset=utf-8",
        beforeSend: function () { alert('sending') },
        success: function (result) {
            alert(result.Result);
            localStorage.clear();
        }
    });
};

This test controller method is expecting the data from the localstorage:

    [HttpPost]
    [WebMethod]
    public ActionResult Test(string JsonLocalStorageObj)
    {
        string x = JsonLocalStorageObj;
        //deserialize here
        return RedirectToAction("Index");
    }

Upon inspection using JSON.stringify(localStorage); in chrome dev tools reveals the data as expected. However, when debugging the controller, JsonLocalStorageObj appears to be always null. When testing with an array of strings, it was successfully passed through. What could be causing the issue with passing JSON.stringify(localStorage);?

Answer №1

The parameter name for your action (JsonLocalStorageObj) was not specified correctly and the content as well as the dataType were incorrect. To fix this, modify your javascript code to:

function sendLocalStorage() {

    var JsonLocalStorageObj = JSON.stringify(localStorage);
    
    $.ajax({
        url: "/MyControllersName/Test",
        type: "POST",
        data: { JsonLocalStorageObj: JsonLocalStorageObj },
        success: function (result) {
            alert(result);
        }
    });
}

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

Determining if the device is connected to the internet

Is there a way to create a unique code using HTML, JavaScript, or jQuery that executes a random action when the website detects that the device is offline? ...

The ThreeJS scene may run smoothly at 60 frames per second, but it maxes out my fans and crashes after

Recently, I delved into the world of threeJS and decided to test my skills by using this example: After exporting some terrain from blender and replacing the platform.json file, my scene was running smoothly at 55-60fps. However, as time went on, my compu ...

Preventing grid-collection from iterating within a for loop in Liquid on Shopify

I am trying to find a solution to prevent the grid-collection div from iteratig inside a for loop. Below is a snippet of my code in liquid: {% for block in section.blocks %} {% if block.settings.download_title %} <div class="title& ...

Will cancelling a fetch request on the frontend also cancel the corresponding function on the backend?

In my application, I have integrated Google Maps which triggers a call to the backend every time there is a zoom change or a change in map boundaries. With a database of 3 million records, querying them with filters and clustering on the NodeJS backend con ...

Optimal method for utilizing Babel to generate a unified JavaScript bundle

I have multiple JS files and I need to combine them into a single JS bundle using Babel. Someone pointed me towards this first resource, but I am having trouble grasping the instructions: https://babeljs.io/docs/usage/cli/ While searching online, I came ...

Failure of AngularJS $http GET request

function ContactDetails($scope, $http) { $http({ method: 'GET', url: 'myurl/?', params: { 'company': '1571', 'secret': 'complex15', 'mode': 'contactdetai ...

Inspecting the options within a dropdown menu to adjust a styling attribute

I am in the process of developing a website that features multiple select options for creating sentences. My goal is to detect when users are changing these options to form specific sentences, such as changing "I", "Am", "Blue" to reflect the color blue. T ...

Exploring the challenges of implementing the Lob Node API wrapper within a MeteorJs project due to conflicts with the 'fs' module

I recently updated to the latest version of Meteor (1.13) which now supports NPM. I decided to add the Lob.com NPM to my project and started working on a letter function. However, I encountered the following error: Uncaught TypeError: fs.readdirSync is ...

styling multiple elements using javascript

Recently, I created a jQuery library for managing spacing (margin and padding). Now, I am looking to convert this library to pure JavaScript with your assistance :) Below is the JavaScript code snippet: // Useful Variables let dataAttr = "[data-m], [d ...

Vue struggles to handle data coming from a composable function

For my specific case, I need to verify whether the user has subscribed to my product through both Stripe and Firebase. To accomplish this, I created a composable function that checks for the current subscription in the Firebase collection. If the user cur ...

Changing the color of a progress bar in Bootstrap based on a specific percentage level

var elem = document.getElementById("progress-bar"); var progress = 75; elem.style.width = 80 + '%'; if (progress > 80) { elem.style.background = "red"; } #myProgress { height: 5px; } #progress-bar { w ...

Using Vue.js to link and update dynamic form fields

I have developed a dynamic set of form inputs utilizing vue.js, where the form inputs are generated from an external list of inputs. My challenge lies in figuring out how to bind the input values back to the vue model, enabling the vue instance to access ...

A dialog box resembling a tooltip

Are there any jQuery plugins available that mimic the functionality of the tooltip dialog in the Flow App? (See screenshot here: ). I am currently working on a web app that requires a lot of tooltip dialogs. If there isn't a plugin available, could s ...

How can I adjust the number of columns displayed per page on a Bootstrap Studio website?

Currently, I am utilizing Bootstrap studio to design a website featuring multiple cards on each page. Initially, I incorporated cards from the sb-admin-2 template and everything was proceeding smoothly. In my bootstrap studio interface, the three-column ca ...

Guide to making a Java Servlet for a specific jQuery.ajax () request?

In one of my files named wfd.proxy.js, I have the following code snippet: if (!WFD) { var WFD = {}; }; if (!WFD.Proxy) { WFD.Proxy = {}; }; WFD.Proxy = { SERVICE_URL : "/delegate/WFD/WFService?", PDF_SERVICE_URL : "/delegate/pdf-exporter?", ...

Inability to assign a value to an @input within an Angular project

I recently started using Angular and I'm currently trying to declare an input. Specifically, I need the input to be a number rather than a string in an object within an array. However, I'm encountering difficulties and I can't figure out wha ...

Tips for passing a function and an object to a functional component in React

I am struggling with TypeScript and React, so please provide clear instructions. Thank you in advance for your help! My current challenge involves passing both a function and an object to a component. Let's take a look at my component called WordIte ...

Troubleshooting: Issues with Jquery's has, find, contains functions

As I check whether an element contains another element, I've previously utilized the jquery element.has(secondElement) function. In my angularjs project, I make use of jquery within a directive where I transclude elements through markup using ng-tran ...

Accessing information through API in Javascript

I am looking to retrieve data from an API by connecting to it through the Hubspot CMS. The API link can be found here: Despite trying a Codepen example, I am facing difficulties as the data is not displaying even though there are no errors in the console: ...

When working with ASP.NET MVC, I encountered an unexpected issue where a JSON response was sending me a file instead of

After receiving JSON data, I observed that instead of updating the jQuery accordion, it prompts to save or open a file. Below is my code and controller setup. I have integrated a jQuery modal dialog for editing employee details using a partial view. When c ...