A guide on fetching JSON data from an ASP.NET web service using JavaScript

Long ago, there existed a project that held the attention of an individual. This particular project featured both a master page and a content page, where the latter boasted a drop-down list along with two text boxes. However, when an item name was selected from the drop-down list, to everyone's surprise, the values of totalQuantity and pricePerItem failed to show up in the text boxes! The person diligently worked on crafting web service and JavaScript code for this venture, but alas, it did not behave as intended. Thus, comes the humble request for your assistance.

 public class QuantityAndPrice
{
    public string totalQuantity { get; set; }
    public string pricePerItem { get; set; }
}

webservice code

  public class QuantityAndPriceService : System.Web.Services.WebService
{

    [WebMethod]
    public void GetQuantityAndPrice(string productName)
    {
        QuantityAndPrice quantityAndpriceObject = new QuantityAndPrice();

        string connect_string = "datasource=localhost;port=3306;username=root;password=root;";
        MySqlConnection connection = new MySqlConnection(connect_string);
        string query = "select totalQuantity,pricePerItem from smart_shop.inventory where name='" + productName + "';";
        MySqlCommand  cmd = new MySqlCommand(query, connection);
        connection.Open();
        MySqlDataReader   reader = cmd.ExecuteReader();

        while (reader.Read())
        {
            quantityAndpriceObject.totalQuantity = reader.GetString("totalQuantity");
            quantityAndpriceObject.pricePerItem = reader.GetString("pricePerItem");
        }

        JavaScriptSerializer js = new JavaScriptSerializer(); 
       Context.Response.Write(js.Serialize(quantityAndpriceObject));
    }
}

javascript

 <script type="text/javascript">

        $(document).ready(function () {
            $('#productNameDDL').change(function () {

                var pName = $('#productNameDDL').val();

                $.ajax({

                    url: 'QuantityAndPriceService.asmx/GetQuantityAndPrice',
                    data: { productName: pName },
                    method: 'post',
                    dataType: 'json',
                    success: function (data) {

                        $('#tbxAvailableQuantity').val(data.totalQuantity);
                        $('#tbxPricePerItem').val(data.pricePerItem);
                    },
                    error: function (err) {
                        alert(err);
                    }
                });
            });
        });
    </script>

and here aspx code

<div class="panel-body">
                <div class="row">
                    <div class="col-md-6"> 
                         <h6>&nbsp;&nbsp;Available Qty</h6>
                         <asp:TextBox ID="tbxAvailableQuantity" CssClass="form-control" ReadOnly="true" runat="server"></asp:TextBox>
                    </div>

                    <div class="col-md-6">
                         <h6>&nbsp;&nbsp;Price/Item</h6>
                          <asp:TextBox ID="tbxPricePerItem" CssClass="form-control" ReadOnly="true" runat="server"></asp:TextBox>
                    </div>

                </div> 
                <div class="row">
                    <div class="col-lg-6">
                         <h6>&nbsp;&nbsp;Sales Qty</h6>
                         <asp:TextBox ID="tbxSalesQtuantity" CssClass="form-control" runat="server"></asp:TextBox>
                    </div>
                    <div class="col-lg-6">
                         <h6>&nbsp;&nbsp;Total Price</h6>
                         <asp:TextBox ID="tbxTotalPrice" CssClass="form-control" runat="server"></asp:TextBox>
                    </div>
                </div>                 
            </div>

  <asp:DropDownList ID="productNameDDL" CssClass="form-control" runat="server"></asp:DropDownList>

Answer №1

  1. It is crucial for a web service class to include the ScriptService attribute.
  2. The web service method must also have the ScriptMethod attribute in order to declare
    ResponseFormat = ResponseFormat.Json
    .
  3. When writing JavaScript, make sure to specify
    contentType: "application/json; charset=utf-8"
    and dataType: 'json'.
  4. Any data retrieved in the success section of an ajax call will be stored in d, such as data.d.totalQuantity.
  5. To properly handle data in an ajax call, remember to stringify it like this:
    data: JSON.stringify({ productName: pName })

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class QuantityAndPriceService : WebService
{
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public QuantityAndPrice GetQuantityAndPrice(string productName)
    {
        QuantityAndPrice quantityAndpriceObject = new QuantityAndPrice
        {
            totalQuantity = "totalQuantityValue",
            pricePerItem = "pricePerItemValue"
        };
        return quantityAndpriceObject;
    }
}

$.ajax({
    url: 'QuantityAndPriceService.asmx/GetQuantityAndPrice',
    data: JSON.stringify({ productName: pName }),
    method: 'post',
    contentType: "application/json; charset=utf-8",
    dataType: 'json',
    success: function (data) {
        $('#tbxAvailableQuantity').val(data.d.totalQuantity);
        $('#tbxPricePerItem').val(data.d.pricePerItem);
    },
    error: function (err) {
        alert(err.responseText);
    }
});

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

The issue arises when the .scroll event listener fails to accurately return true or false in

This code snippet determines whether an element is within the visible screen area. However, it seems to be returning an undefined value instead of true or false as intended. The function needs to output true or false for later use in higher-order operation ...

What should be used for data fetching in Next.js: SWR or traditional fetch/axios along with useEffect?

I'm currently diving into the world of Next.js and I'm eager to showcase data based on user input queries. However, I'm uncertain if leveraging useSWR is the most suitable approach to tackle this challenge because I haven't come across ...

Retrieving the JSON value from a data attribute and then locating the corresponding JSON key in a designated element within the DOM

I have an HTML element that contains a data attribute: <a href="#" data-trigger="{ "rem": "albatros", "ap":1 }'">Remove</a> <div data-container> <p>lorem ipsum<p> <p data-rem></p> </div> 1. So ...

Loading images onto tinyMCE

I’m currently creating a website using AngularJS, NodeJS, mongoose, mongoDB, and other technologies. On this site, I have integrated a tinyMCE text editor. However, I am now looking for a way to include images in the editor. I have explored solutions lik ...

Managing different authentication methods for a single user on Firebase: Tips and Strategies

Currently, I am in the process of developing an authentication system utilizing Firebase. My aim is to incorporate email/password, Google, and Facebook as sign-up and sign-in methods. Initially, everything runs smoothly when a user signs up using each met ...

Under specific circumstances, two combo boxes will function with the jQuery select plugin

I am working on an ASP.NET MVC Razor view that contains two dropdowns. <select id="country_id" ... /> and <select id="city_id" ... /> When an option is selected in the country dropdown (country_id), the second dropdown (city_id) is populate ...

Enhanced functionality for Thingworx using ThreeJS

I'm currently facing an issue while developing a 3 JS extension for Thingworx, specifically with the renderHtml function when working with a 3 JS canvas (Check out the code). //runtime.ts file renderHtml(): string { let htmlString = '<div ...

A guide on extracting data from a Bootstrap table and removing a specific row

In my ejs file, I have a Bootstrap table set up as shown below. I am trying to implement a feature where clicking a button will trigger my del() function to delete the selected row. However, I am facing an issue where my function does not receive the &apos ...

The outcome of retrieving data through a combination of ajax, jquery, and json

Hey there, I'm new to programming and could really use some help with this. If my question seems silly, please bear with me. Thanks! I've got an index.php page with a login form (username, password) and a login.php file with the following snippe ...

Using JSON input to add color to a d3 bullet chart

I am currently working with a D3 bullet chart example and trying to enhance it by incorporating different colors for the ranges directly into the JSON file. The link to the original example can be found here: . I need this customization because I require d ...

Is there a way to dynamically insert page breaks in jspdf to ensure that tables do not split across multiple pages?

I am currently working on developing a website that can generate PDFs from database information, using PHP and MySQL to create tables with variable lengths. Sometimes, these tables may even span across multiple pages. If the first table takes up too much ...

How come running `npm install <folder>` results in installing different dependencies compared to `npm install lib`?

My current project, project1, relies on <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5221262b3e37367f313d3f223d3c373c262112667c6">[email protected]</a>. When attempting to integrate project2 into project1 as a ...

Analyze the elements within arrays and determine the occurrence rate of each element

Issue at hand: var rawData = [[two],[three],[four],[one],[two],[two],[two],[three],[four],[five],[three],[four],[five]]; Given an array of arrays, the goal is to identify the unique elements within one of the arrays and provide a count of each unique ele ...

Utilizing SwiftyJSON for converting JSON strings to Swift objects

What is the best approach to map a JSON string to a Swift object? struct User { var name: String var age: Int } Is there a simple method for converting a User object to a JSON string and vice versa, for mapping a JSON string to a User object? ...

In TypeScript, maximize the capabilities of JavaScript modules by utilizing the import extension

Incorporating the dynamo-cache package from NPM into my TypeScript project has been a bit of a challenge. Essentially, this module introduces a new method to the AWS.DynamoDB.DocumentClient: AWS.DynamoDB.DocumentClient.prototype.configCache = function(con ...

Is there a way for me to identify what deletes CSS classes from an element during the first page load?

On a page where an element (specifically, a TextBox) initially has two CSS classes assigned when it loads, something strange is happening. After the page renders and JavaScript runs, the class attribute of the input element mysteriously becomes empty. I c ...

Timed up 10-second countdown with vue.js

<html> <head> <meta charset="utf-8" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" ></script> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> < ...

Difficulty transferring information between two components by using services

I am trying to pass the values of an array from the Search component to the History component in order to display the search history. My current code structure looks like this: search-page.component.ts export class SearchPageComponent implements OnInit ...

The jQuery .val() function does not function properly when using 'this'

This is an example with a textarea: <textarea id='ta' onkeydown='down(this)'></textarea> and here is the accompanying JavaScript code: <script> function down(input) { alert(input.val()); // not functioning ...

Using Vue JS to handle image upload with "PROP MUTATING"

Apologies for any language barriers or inaccuracies in my English. I have a single component designed specifically for image uploads. It is currently being utilized in two forms: an add form and an edit form. In the edit modal, the Image URL is passed as ...