Struggling to get the AJAX code functioning correctly

Embarking on my journey with AJAX, I decided to test a simple example from the Microsoft 70515 book. Surprisingly, the code doesn't seem to be functioning as expected and I'm at a loss trying to figure out why - everything appears to be in order.

  • Edit: It seems like a portion of my code didn't get posted for some reason (even as I type this now, the formatting looks odd, almost as if I can't post all of my code?) I have rectified that issue now - but could someone please explain the reason behind the down vote? I fail to see what's wrong with my question. Your input is much appreciated.

I'm hopeful that someone will be able to identify the problem and offer assistance here :)

Markup .aspx:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="AjasxTest._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

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


<br /><br />

<script type="text/javascript">
    function ClientCallbackFunction(args) {
        window.LabelMessage.innerText = args;
    }
</script>

</asp:Content>
<asp:Content ID="Content1" runat="server" ContentPlaceHolderID="FooterContent">
<asp:DropDownList ID="DropDownListChoice" runat="server" OnChange="MyServerCall(DropDownListChoice.value)">
<asp:ListItem>Choice 1</asp:ListItem>
<asp:ListItem>Choice 2</asp:ListItem>
<asp:ListItem>Choice 3</asp:ListItem>
</asp:DropDownList>
<asp:Label ID="LabelMessage" runat="server"></asp:Label>
</asp:Content>

Code-behind:

namespace AjasxTest
{
    public partial class _Default : System.Web.UI.Page, System.Web.UI.ICallbackEventHandler
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string callbackRef = Page.ClientScript.GetCallbackEventReference(this, "args", "ClientCallbackFunction", "");

            string callbackScript = String.Format("function MyServerCall(args) {{{0};}}", callbackRef);

            Page.ClientScript.RegisterClientScriptBlock(this.GetType(),"MyServerCall", callbackScript, true);
        }

        public string GetCallbackResult()
        {
            return _callbackArgs;
        }

        string _callbackArgs;

        public void RaiseCallbackEvent(string eventArgument)
        {
            _callbackArgs = eventArgument;
        }
    }
}

Answer №1

Make sure to use the correct function name in your JavaScript code. Your function is named ClientCallbackFunction, but you are trying to call it using the name MyServerCall in the DropDownList OnChange event.

<script type="text/javascript>
    function ClientCallbackFunction(args) {
        window.LabelMessage.innerText = args;
    }
</script>

...

<!-- Make sure to call the correct JS function in the OnChange event -->
<asp:DropDownList ID="DropDownListChoice" runat="server" OnChange="ClientCallbackFunction(DropDownListChoice.value)"> 

...

Answer №2

Your code is almost there, but the issue lies in attempting to access ServerSide objects (like Label and DropDownList) from the client side.

For instance, an asp:Label control, when displayed in a web browser on the client side, is essentially an HTML div. The ID of the label may be "LabelMessage" in Visual Studio, but the actual ID on the client side (visible to users who view the page source in FireFox or IE) could be something like "FooterContent_LabelMessage1", depending on your page's structure and controls.

ASP.net controls come with a property that allows you to access the dynamically generated ID in JavaScript, which can be retrieved using YourControl.ClientID.

I've made the necessary adjustments to your code to make it functional. Additionally, I included some null reference checks in the JavaScript to ensure the objects we are trying to access exist. This code has been tested in a new ASP.net forms application.

Below is the updated code for the Default page (front end):

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="TheAnswer._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <br />
    <br />
    <script type="text/javascript">
        function ClientCallbackFunction(args) {
            var labelMessage = $get("<%= LabelMessage.ClientID %>");
            if (labelMessage) {
                labelMessage.innerText = args;
            }
        }
        function MyServerCallWrapper() {
            var dropDown = $get("<%= DropDownListChoice.ClientID %>");
            if (dropDown) {
                MyServerCall(dropDown.value);
            }
        }
    </script>
</asp:Content>
<asp:Content ID="Content1" runat="server" ContentPlaceHolderID="FooterContent">
    <asp:DropDownList ID="DropDownListChoice" runat="server" onchange="javascript:MyServerCallWrapper();">
        <asp:ListItem>Choice 1</asp:ListItem>
        <asp:ListItem>Choice 2</asp:ListItem>
        <asp:ListItem>Choice 3</asp:ListItem>
    </asp:DropDownList>
    <asp:Label ID="LabelMessage" runat="server"></asp:Label>
</asp:Content>

It's important to note that the $get() function is a built-in ASP.net (not JQuery) function that serves as shorthand for document.getElementById(). Both methods achieve the same result and require passing the ClientID in quotes to access the desired object in JavaScript.

As a fun addition, I tweaked one of the backend functions so you can see that the callback was successfully processed on the server:

public string GetCallbackResult()
{
    return _callbackArgs + " from the server!";
}

This should work smoothly, as it did for me. Hopefully, this resolves the issue and clarifies where the problem stemmed from - most of your original setup was spot-on.

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 retrieving the address of the connected wallet using web3modal?

I've been working on an application using next.js and web3. In order to link the user's wallet to the front-end, I opted for web3modal with the following code: const Home: NextPage = () => { const [signer, setSigner] = useState<JsonRpcSig ...

Guide to showcasing console output on a Web Server

Apologies if this question is not the most suitable for this platform. I recently set up Pure-FTPd service on a CentOS server. To check current connections, I use the command pure-ftpwho, which gives me the following output: +------+---------+-------+---- ...

Enhance your existing look by incorporating element.style into your designs

Is there a way to add styles onto an html element without overwriting existing css? element.style { "existing css;" } I'm trying to achieve the following result: element.style { existing css; opacity: 0; pointer-events: none; } But current ...

Attempting to crack the code within body-parser and Node.js

I am just getting started with Node.js & Express and trying to follow a tutorial at https://github.com/jw84/messenger-bot-tutorial. I have a good understanding of most parts, but I'm confused about the use of "entry" and "messaging" in this code snipp ...

Rendering in React by cycling through an array and displaying the content

I have been working on displaying two arrays. Whenever the button is clicked, a new user is generated and added to the array. My goal is to render the entire array instead of just the newest entries. I've attempted various methods but haven't had ...

Transferring an MSAL token to the backend with the help of Axios

I encountered an issue while attempting to send the user ID, which was previously decoded from a JWT token along with user input data. The problem arises when I try to send the data and receive an exception in the backend indicating that the request array ...

Is it possible to include array elements in a dropdown menu using React?

Imagine you have an array called const places = [" a1", "a2", "a3"]; and <FormControl variant="outlined" className={classes.formControl}> <InputLabel id="dropdown_label">Testing</InputL ...

How to specify a single kind of JavaScript object using Typescript

Let's say we have an object structured as follows: const obj = [ { createdAt: "2022-10-25T08:06:29.392Z", updatedAt: "2022-10-25T08:06:29.392Z"}, { createdAt: "2022-10-25T08:06:29.392Z", animal: "cat"} ] We ...

React ES6 SystemJS encountered an unforeseen token error that couldn't be caught

Even though I have imported react and react-dom using the System.config setup below, I am still encountering the error mentioned here: Uncaught (in promise) Error: Unexpected token <(…) Here is the HTML structure: <!DOCTYPE html> <html l ...

Tips for sending an email to an address from a user input field in React.js/Express.js

I am currently developing an email application that allows users to send emails to any recipient of their choice. The challenge I'm facing is that I need a way to send emails to user-specified email addresses without requiring passwords or user.id det ...

Exploring vuelidate: demonstrating personalized validation messages alongside pre-built validators

I'm currently utilizing the vuelidate library to validate my forms. I've been attempting to use the built-in validators along with a custom message, as shown below. However, I have encountered issues with it not functioning properly. For referenc ...

Tips for testing nested HTTP calls in unit tests

I am currently in the process of unit testing a function that looks like this: async fetchGreatHouseByName(name: string) { const [house] = await this.httpGetHouseByName(name); const currentLord = house.currentLord ? house.currentLord : '957'; ...

Imagine a scenario where your json_encode function returns API data that is already in JSON format. What would

It has been a while since I last worked with JSON/PHP/AJAX, and now I am struggling to access the returned data. The AJAX function calls a PHP script that makes an API call returning JSON in $data. The JSON is then decoded using $newJSON = json_decode($da ...

I am struggling to capture the user's input and display it on a webpage using HTML and JavaScript. Can you help me identify where I may be going wrong in this process?

Good day! I am fairly new to the programming world and have recently embarked on my first JavaScript project. I've chosen to create a simple budgeting app. However, I'm struggling with displaying user input on the page. Something seems off with ...

Swap out periods with commas in the content of Json Data

I have a JSON file containing percentage data that I am extracting and displaying on my website: <?php $resultData = file_get_contents('https://example.com/json/stats?_l=en'); $jsonData = json_decode($resultData, true); if( isset( ...

"Troubleshooting an issue with ng-model not functioning properly with radio buttons in Angular

I'm a newcomer to Angular and I'm attempting to retrieve the value of the radio button selected by the user using ng-model. However, I'm not seeing any output in "selected contact". Check out My HTML below: <!doctype html> <html n ...

The Jquery calculation is giving unexpected results by returning NaN instead of an integer

Hello, I'm attempting to create a calculation that will add up the values from multiple text inputs and then display the total in another text input field. Below is the code that I have put together for this purpose. However, when I test it out, I see ...

Exploring the images in a continuous loop

Looking to create a unique image looping effect using HTML, CSS, and Jquery/Javascript. The concept is to display several images on one page that do not move, but loop through them one at a time while displaying text above the current image. For example, ...

leveraging the localStorage feature in a for-in iteration

I am new to stackOverflow, although I have browsed the forums for help in the past. However, this time I couldn't find a solution to my current issue, so I decided to create an account and seek assistance. The problem at hand is related to a workout ...

Having trouble updating an array in a mongoose document?

Need help with updating an array in a document by adding or replacing objects based on certain conditions? It seems like only the $set parameter is working for you. Here's a look at my mongoose schema: var cartSchema = mongoose.Schema({ mail: Stri ...