Unable to invoke function from code-behind using PageMethods - error undefined

I am in the process of creating a website where users can customize their own cakes. Each cake comes with a base price and various options that may incur additional charges. These additional prices are stored in the database and can be retrieved using the feature id.

My goal is to develop a function that dynamically updates the total price as users select different options. The options are presented in dropdown menus and checkbox lists, displaying the option text while storing the feature id as the value. I have implemented a JavaScript function to retrieve the selected item values.

My approach involves invoking the "additionalPrice" method whenever a dropdown menu or checkbox list is changed. This method queries the database for the corresponding feature ids and calculates the extra cost. However, I am encountering an issue where PageMethods appears undefined. It does not auto-populate in VS2012 and is displayed in black instead of light blue. Despite following similar cases, I cannot seem to identify any errors in my code...

<asp:ScriptManager ID="ScriptManager1" 
EnablePageMethods="true" 
EnablePartialRendering="true"  runat="server" />

<script>
$('.featureDropDown').change(function (a) {
            //var price = $.ajax({ url: 'ajax/totalproductprice.ashx', async: false }).responseText;
            var price = PageMethods.additionalPrice();
            alert(price);
</script>

Codebehind...

 [WebMethod] public static int additionalPrice()
    {
        return 77; 
    }

The "additionalPrice" function will incorporate more logic once this initial hurdle is cleared. As it stands, changing a dropdown list triggers an alert displaying 'undefined'.

UPDATE: Following the resolution of the first issue, I have encountered another challenge. I am attempting to update a label with the final price returned from the "additionalPrice" method within the onSuccess function of PageMethods. The label is located at the top of the page -

<asp:Label ID="lblPrice" runat="server" />

Below are the attempts I have made within the onSuccess function to update the label, none of which seem to affect the display.

function onSuccess(result) {
            alert(result + "worked");
            $('.lblPrice').attr("text", result);
            $('.lblPrice').attr('text', function () {
                $(this).attr('text', result);
            })
            $('.lblPrice').text(result);
            document.getElementById('lblPrice').value= result;
            document.all('lblPrice').innerHTML = result;
        }

Answer №1

When working with ASP.NET AJAX, you can utilize the PageMethods feature to include success and failure callback functions. By passing these parameters in your call, you can easily handle the response.

$(function () {
    $('.featureDropDown').change(function (a) {
        //var price = $.ajax({ url: 'ajax/totalproductprice.ashx', async: false }).responseText;
        PageMethods.additionalPrice(onSuccess, onFailure);
    });

    function onSuccess(result) {
        alert(result);
    }

    function onFailure(error) {
        alert(error);
    }
});

Answer №2

When calling web methods from JavaScript, be sure to utilize the

<System.Web.Script.Services.ScriptService()>
class where your web method is located. If you choose to organize your web methods in a separate file for scalability, you will need to reference them in your script manager.

<asp:ScriptManager ID="scriptManager" runat="server">
    <Services>
        <asp:ServiceReference Path="~/WebServices/SomeWebServices.asmx" />
    </Services>
</asp:ScriptManager> 

In addition, be sure to follow the steps mentioned earlier. If you encounter any issues, feel free to reach out for assistance.

$(function () {
    $('.featureDropDown').change(function (a) {
        //var price = $.ajax({ url: 'ajax/totalproductprice.ashx', async: false }).responseText;
        PageMethods.additionalPrice(onSuccess, onFailure);
    });

    function onSuccess(result) {
        alert(result);
    }

    function onFailure(error) {
        alert(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

What is the process for transitioning from Ajax to Fetch API in JavaScript?

Currently, I am utilizing the JavaScript version of RiveScript which relies on ajax, and I have decided to move away from using jQuery. There is a single line of ajax code that I need to update to integrate the new Fetch API. **Note: The ajax code can be ...

AJAX request function is only successful on the first attempt

Currently, I am implementing AJAX functionality to verify whether a user-input ID exists in the database. If the ID is found, a check mark is displayed; if not, a cross mark is displayed. The issue arises when I input an ID for the first time, which is pr ...

What are the steps to start a ExpressJS server for webpages that are not index.html?

I am exploring how to browse/run/view web pages other than just the index.html file in my public folder, which contains multiple HTML files. I am using ExpressJS and NodeJS for this purpose, but every time I start my server, I can only access the index.htm ...

Utilizing jQuery to send an Ajax GET request for a JSON file

Recently I have begun delving into the world of jQuery and Ajax, attempting to utilize both technologies to retrieve a JSON FILE. Below is the structure of the file: [ { "userId": 1, "id": 1, "title": "delectus aut autem", "completed": f ...

The Node application seems to be encountering an issue when attempting to handle

Whenever I click a button on my page in Node using Express, my JavaScript file sends the following request: toggleCartItem = index => { http = new XMLHttpRequest(); http.open("POST", `/cart_item/${index}`, true); http.send(); } Th ...

Enabling Cross-Origin Resource Sharing in Finatra

While attempting to access my REST API created with Finatra through AJAX calls, I encounter an error: The preflight request response fails the access control check: The requested resource does not have the 'Access-Control-Allow-Origin' header. ...

Which HTML tags can be activated with JavaScript to be interactive?

I'm currently diving into the world of JavaScript and one of the initial code snippets I've encountered is onclick. So far, I've seen it utilized in form buttons like this: <input type="button" onclick="checkName()" value="Check name" / ...

The combination of Jquery and Ajax does not seem to be able to retrieve the value of an

Below is the jQuery function that I have: function displayNewWindow(){ $('#result').slideDown('slow'); $("#result").html('<div id=resim><center><img src="loading.gif"></center></div>'); ...

Simulated 'paths' configuration in non-TypeScript Node.js environment

In my TypeScript project, I've utilized a helpful configuration option in tsconfig.json that enables me to set up aliases for folders. { "compilerOptions": { "paths": { "@src/*": ["src/*"], "@imag ...

What steps can I take to display lines in a textarea so that it closely resembles the appearance of a notepad document

Is there a way to display lines in a text-area to give it the appearance of a notepad? I only have one text-area available. See the example notepad below for reference. ...

What is the best way to target a specific item in a list using JavaScript in order to modify its appearance?

How can I modify the appearance of a specific li element when it is clicked? ...

Using Javascript in the Model-View-Controller (MVC) pattern to load images stored as byte

Despite the numerous solutions available on Stack Overflow, I am still unable to get any of them to work... I am faced with the challenge of setting the "src" attribute of an image tag using a byte array obtained from an ajax call to my controller in Java ...

Display the keys of a nested array in Vue.js when the structure is unknown

Here is a representation of a dynamic array I have: nodes: [ { n1: "Foods", }, { n4: "Drinks", b7: [ { a2: "Beers", a4: [ ...

Activate the angular function

In the controller below, there is a function that should be triggered when the link is clicked: <a id="1" href="" name="xxx" ng-click="searchall(id)">sample link</a> ng.controller('SearchResultController', ['$scope', &apos ...

What is the best way to assign a value to a property in a Controller or Global Variable using jQuery?

On my ASP MVC 5 site, I have a checkbox within the NavBar element. This checkbox's state dictates whether or not the Grid will display Inactive records alongside active ones on each page. In an attempt to have all controllers access the same property ...

Refreshing data attribute following an ajax request

I have this page with a list of various job listings. Each job listing has a button labeled "Paid" that includes a data-paid attribute indicating whether the job is paid or not. Whenever the "Paid" button is clicked, it sends a request to my route which u ...

Integrating a parameter into a plugin allows for displaying a specified number of elements in the output

A unique plugin is being used to create a vertical slideshow effect. This plugin scrolls the top-most div in a series of divs with the same class upwards, removes it from the container, and appends it to the bottom of the series within the container. The e ...

What are the steps for configuring a dynamic variable?

One issue I encountered was setting up a variable in vue that updates when the screen orientation changes. Despite adding this variable to the data object, it did not become reactive as expected. This is my initial data function for the component: data() ...

Transferring a JSON array from Google App Engine to Cloud Storage using GO

I am attempting to upload a JSON array to Google Cloud Storage, which is posted by an App Engine application using the code below: saveData : function saveData() { var _this = this, save = this.shadowRoot.querySelector('#save-data'), ...

Node.js and MongoDB integration for implementing like and dislike buttons

I have been struggling to create a system for liking and disliking posts in my project. The issue I am facing is with the communication between the server and client side. Here is the form I am using: https://i.sstatic.net/IBRAL.png When I click on the li ...