Fill in the text boxes using an AJAX request

I am currently working on an MVC project that involves filling out forms with user information. Each recorded entry is given a unique Id that is associated with all the details submitted in the form.

My next task is to create a page for editing these forms, which requires passing the id through the URL and assigning it to Viewbag.Id. I want to use this Id in an ajax call to retrieve the remaining information from the web API and populate the fields with the existing data. However, as I am still learning about ajax, I am unsure of how to accomplish this effectively. Below is the relevant code snippet:

Controller Code:

@Route("EditUser/{id}")]
@CustomAuthorize(Roles = UserRole.Any)
public ActionResult EditUserDetails(int id)
{
    var userDetails = _slg_Entity.NewUser.FirstOrDefault(z => z.Id == id);

    ViewBag.Id = userDetails.Id;         

    return View("~/Views/Request/EditUser.cshtml");
}

This is the jquery/ajax call I am attempting to implement:

$.ajax({
     type: "GET",
     url: "@Url.Action("UserDetails", "Api/Request")",
     data: {
         Id: "@ViewBag.Id" // ID passed to the API controller
     }
 }).done(function (data) {
     $(".firstname").val(variable); // Assigning data from API to field value
 }).fail(function (error) {
     displayError(error);
 });

API Controller Code:

@Route("UserDetails")]
@HttpGet
@CustomApiAuthorize(Roles = UserRole.HR)
public async Task<IHttpActionResult> GetUserDetails([FromUri] NewUserDetails existingUser)
{
    var details = await _slg_Entity.NewUser.FirstOrDefaultAsync(z => z.Id == existingUser.Id);

    existingUser.FirstName = details.FirstName;

    return Ok(details);
}

I'm not sure if I'm on the right track, so any tips or feedback would be greatly appreciated! Thank you.

Answer №1

After some investigation, I realized that the data was actually being passed correctly. The issue turned out to be a mistake in how I was calling it.

Instead of simply passing the variable created in my controller, it slipped my mind to include the proper data prefix.

$.ajax({
    type: "GET",
    url: "@Url.Action("UserDetails", "Api/Request")",
    data: {
       Id: "@ViewBag.Id"
    }
}).done(function (data) {
   $(".firstname").val(data.variable); 
}).fail(function (error) {
   displayError(error);
});

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

Error in Charts API - [draw function failed to render for one or more participants]

Currently encountering an error on the client side where one or more participants failed to draw. I am able to successfully output data in the drawVisualization call, indicating that the issue lies within the JavaScript code. Despite following examples, I ...

Different ways to send data from JavaScript to Python using the 'POST' method

I have this specific section of code from my GAE application that utilizes webapp2 framework to receive data from a form through the post method. class RenderMarksheet(webapp2.RequestHandler): def post(self): regno = self.request.get('content ...

Counting results in mySQL using C#

I wrote this code snippet to connect to a database and display the content of a table called 'cars'. I need help figuring out how to count the number of rows returned by the query: public void establishDBConnection() { DB ...

How can I assign a variable from a function that may include an ajax request?

I have created my custom script for loading content via AJAX if it hasn't already been loaded. Check it out below: /* * Custom Content Loader */ var loaded_urls = {}; function fetch_content_from_url(url) { if (loaded_urls[url] === undefin ...

Identification of inappropriate language in usernames

One of the challenges I'm facing is detecting inappropriate language in usernames. Currently, I am using regex to validate the username based on a specific pattern: "/^[A-Za-z0-9]*(\d*\.\d*)*[A-Za-z0-9]+$/" This regex pattern allows u ...

Jquery and Ajax failing to function properly with multiple dropdown selections

I've been working on creating a functionality to have multiple dropdown menus using Bootstrap, JQuery, and AJAX. The goal is to select multiple countries from these dropdowns and store the selected values in CSV format in my database. Initially, I had ...

Tips for sending arguments to NUnit test cases using the UI

Does anyone know of a third-party UI tool that can handle passing parameters to NUnit Test Cases? I am really in need of one. Any comments or suggestions would be greatly appreciated!! ...

Extracting data types from strings in JavaScript

I have been developing a project using HTML and JavaScript where I need to extract two strings from the HTML script, pass them to JavaScript, and convert them into their respective variable types similar to using typeof. For instance, "true" shou ...

Steps to extract date selection from a datepicker using jQuery

I recently implemented this code snippet to utilize datepicker for displaying dates: $(document).ready(function(){ $("#txtFrom").datepicker({ numberOfMonths: 1, onSelect: function (selected) { var dt = new Date(selected); ...

User creation causing redirection malfunction

Recently, while working on a website, I encountered an issue with the registration process for users. It was functioning properly when I tested it a few days ago. After making some updates to other aspects of the website such as the login and profile sect ...

Ways to avoid form submission using jQuery

A unique shortcode has been developed to create a custom input: function generateCustomInput() { $output = " <div data-role='controlgroup' data-type='horizontal' data-mini='true'> <button ...

Struggling with updating a user in MongoDB using findOneAndUpdate and encountering a frustrating internal server error 500?

Presently, I am in the process of developing an API that is designed to update the current user in mongoDB based on the data provided in the request. However, whenever I execute findOneAndUpdate(), I encounter a 500 internal server error. (I will outline ...

Uh oh! There seems to be an issue with the ClerkJS frontendAPI option. Visit the homepage at https://dashboard.clerk.dev to retrieve your unique Frontend API value

Despite inputting the correct Clerk API keys, I'm encountering issues with the functionality of the ClerkJS API. I anticipate that the application should enable me to utilize the ClerkJS API for user authentication without any problems. ...

What happens in mongoose if one of several consecutive queries fails?

Currently, as I work on my API, I am utilizing two Models: SongModel and UserModel. Whenever a new song is saved, I also execute a query to link the song._id to the user who created it. Unfortunately, a mistake in my code caused the second query to throw a ...

The jQuery navigation consistently unveils the initial option every time

My navigation element looks like this: <ul> <li name='first_item'> <ul> <li>item 1</li> <ul> <li>item 1.1</li> <li ...

Can you pinpoint the weak wiring in this AngularJS function?

I am currently studying AngularJS and I suspect there may be a glitch in my page. On the page, there is a TEXTAREA where I have typed 'aaa'. The TEXTAREA is linked to an ng-model named input. The following AngularJS code aims to monitor external ...

Tips for testing a service in Angular using unit testing techniques

Within my service, I have a function that looks like this: exportPayGapDetails(filterObject: PayGapDetailFilter): void { const url = `${this.payGapDetailExportUrls[filterObject.type]}`; this.http .post<PollInitResponse>( `/adpi/rest/v2/s ...

What is the best way to verify that a check should have various attributes using chai-things?

Searching for a way to verify if an array in my mocha tests consists of an Object in my Node.js application, I discovered that with Chai-Things, I can use: [{ pet: 'cat' }, { pet: 'dog' }].should.include({ pet: 'cat' }) or ...

Alternative method for displaying text in Discord

At the moment, my discord bot is set up to read from a file and post the new data in that file to a specific channel. I am interested in modifying the output so that any characters enclosed in ~~ are displayed as strikethrough text. const Bot = require( ...

The parameter in a JavaScript for loop

I'm struggling with my Javascript skills. Here is the code snippet I am currently working with: var information = [ {"Column":"","keyw":"","Column_3":"day of march 2011 to someother numeric" ...