Sending array values from the Controller to the view using JSON after a checkbox has been selected

How can I make a checkbox in the view return data from the controller when checked and display it in input boxes?

<input  class="js-recipient-is-me" type="checkbox"/>

Javascript :

$('.js-recipient-is-me').change(function () {
    if (this.checked) {
        $('.js-input-field').addClass('disabled');
        $.ajax({
            url: '/Cart/GetUserInfo',
        });
    } else {
        $('.js-input-field').removeClass('disabled');
    }
});

Html Inputs :

<input type="text" id="mobile" class="js-input-field" name="name" />
<input type="text" id="name" class="js-input-field" name="name" />
<input type="text" id="family" class="js-input-field" name="name" />

Controller :

public async Task<JsonResult> GetUserInfo()
{
    CurrentUserId = User.FindFirstValue(ClaimTypes.NameIdentifier);

    var userinfo = await _scope.GetUserInfo(Guid.Parse(CurrentUserId));

    return Json(0);
}

userinfo is a string array with three values:

["Mobile", "name", "family"]

I want to populate the input fields with the values from userinfo...

Any suggestions on how to achieve this?

Answer №1

To properly handle the data received from the server, it is essential to add a callback function. This can be achieved by using the done() method following the ajax request.

    $.ajax({
        type: "GET",
        url: '/Cart/GetUserInfo'
    })
    .done( function(data) {
        $('#mobile').val(data[0]);
        $('#name').val(data[1]);
        $('#family').val(data[2]);
    });

Furthermore, ensure that you are passing the correct data from the Controller to the view instead of always returning 0. Return the userinfo object using return Json(userinfo);

public async Task<JsonResult> GetUserInfo()
{
    CurrentUserId = User.FindFirstValue(ClaimTypes.NameIdentifier);
    var userinfo = await _scope.GetUserInfo(Guid.Parse(CurrentUserId));

    return Json(userinfo);
}

It is advisable to assign appropriate names to your input fields to avoid potential issues with form submissions. Make sure each input has a unique name attribute, for example:

<input type="text" id="mobile" class="js-input-field" name="mobile" />

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

Having trouble locating a character's name in the Marvel API with NodeJS

I have integrated the Marvel API to fetch character data using axios. Here is a snippet of the code I am using: const axios = require('axios'); const md5 = require('blueimp-md5'); const publickey = '73f5271b4d972dc0f4eba'; co ...

The ion-col with col-3 is causing a template parse error

Currently, I am facing an issue while trying to print data from a constructor. Everything is working fine until I added col-3 to ion-col. It seems like I missed including some module, but I am not sure which one. This is my home.ts file: import { Compone ...

Django and Ajax working together with GET requests

Despite having experience in working with Python, Django, and REST framework, I am facing a challenge when trying to make an Ajax request. No matter how many similar questions I come across, I just can't seem to solve the problem at hand. The situatio ...

I require the ability to generate a fresh JSON file using Node.js

I'm encountering a problem while working on creating a new JSON file. Each time I attempt to use the writeFile function, it throws an error stating that the directory does not exist. Below is the code snippet that I have experimented with: fs.writeFil ...

The issue with ng-repeat causing incorrect image width in Flexslider

My webpage features image scrolling functionality, powered by Flexslider. The images on the page are sorted by date - for example, selecting "last 7 days" will display images from the past week (data managed through AngularJS). However, when the JSON dat ...

Designing a flawless CSS pattern for the online world

Currently, I am working on creating a seamless CSS pattern for the web. Even though this may seem impractical and nonsensical, I find joy in experimenting with it. View my progress here After successfully designing my first tile, my next challenge is to ...

JavaScript only collapsible navigation bar

I have implemented a collapsible navbar using Bootstrap 4 framework according to the documentation provided at this link. The navbar and its contents collapse on small screens, including smartphones, by adding the class .collapse.navbar-collapse. You can ...

Browse through websites without refreshing a shared component specific to those pages in Angular 2

Check out this example app: This is the main component of my Angular application: import { Component } from '@angular/core'; @Component({ selector: 'root', template: ` <h1>My Dummy Angular App</h1> <router-out ...

Using API call responses to initiate a render in React

As a newcomer to React, I'm facing an issue with passing the results of my API call to another component file in order to trigger a render. Can anyone provide a straightforward explanation of what steps I need to take? In my code, I make a call to th ...

Problems with Wordpress AJAX search functionality

I am currently working on implementing a search feature using AJAX to dynamically load posts. However, I am facing an issue where the results are not being displayed. This code snippet was adapted from another source and modified based on private feedback ...

Is it possible to submit form elements within a table using an ajax request?

My scenario involves a table that is generated dynamically and contains an edit and delete button in each row. When a user modifies the content of inputs, checkboxes, or textareas within a specific row and clicks on the edit button, I need to send this d ...

What is the process for printing with JQuery?

I have nested divs with dynamically generated images in my HTML code. My problem is that when I click the print button, I want the corresponding image to be printed. <div id="outputTemp" style="display:none"> <div id="rightoutputimgae"> <di ...

Initializing function handler for Java Script modules

As I was diving into the socket.io's get-started guide, I stumbled upon a module requirement that left me puzzled: var app = require('express')(); var http = require('http').Server(app); The explanation provided by the author is ...

SignalR 2.2 users are experiencing a lack of message reception

I have developed a unique self-hosted SignalR application that is operating within the framework of a console application. To access the hubs within this application, I have implemented a wrapper class to avoid referencing the SignalR.Core assemblies direc ...

Ways to extract dropdown selection into a .php script

I am trying to capture the selected dropdown value in my .php file, which is used for sending emails. When a user selects one of the 6 options from the dropdown menu, I want that selected option to be included as the email subject. Below is the HTML code ...

What is the best way to create a MySQL query using the JSON data provided?

Here is the example data that is being sent to the PHP script: [{"id":1,"due_date":"2011-09-03","due_amount":"48279.00","wo_interest":"45980.00"}, {"id":2,"due_date":"2011-10-03","due_amount":"48279.00","wo_interest":"45980.00"}] The table fields are in ...

What is the best approach for converting a string containing data into a format suitable for displaying in a series on React

Here's a question that may seem simple, but is a bit of a challenge to explain if you're not familiar with highcharts. Imagine you have a simple block of code like this: ` [{"name":"Name1","data":[{"x":1477621800,"y":114,"name":"Name2"}]` and y ...

I am struggling with clicking on Bootstrap's pagination using AngularJS

I'm still getting the hang of Angularjs. I managed to set up a pagination system, but for some reason, I can't seem to interact with it when I run my project. Take a look at this screenshot that illustrates my issue: https://drive.google.com/fil ...

What could be causing my $q resolution and promise to not function as expected?

I'm constantly facing issues with $q Here is an instance where the .then is triggered immediately function performAction() { var deferred = $q.defer(); var modalInstance = $modal.open({ template: '&l ...

After changing the page, the Facebook JS SDK fails to function properly when using JQueryMobile

I'm facing an issue with my webapp that utilizes jQuery Mobile for full ajax navigation. I have initialized the Facebook SDK at the pageinit event in jQueryMobile (called on each page). jQuery(document).on('pageinit', function (event) { ...