Leveraging JavaScript functions for invoking Ajax requests, accompanied by ASP.NET controls

Having a background in PHP, I am accustomed to using a PHP file to handle all of my ajax calls.

Recently, I have been introduced to ASP.NET controls and the overall environment.

I am curious about the correct method for handling ajax requests when they need to be called from a JavaScript file.

If you have an alternative option to AJAX with ASP.NET, I would appreciate seeing a brief implementation from you, if possible.

Thank you! - Guy

Answer №1

After exploring various ajax implementations for ASP.NET, I have come to the conclusion that my own implementation is the best of them all... :D

To implement this, simply create a JavaScript function like the one below:

<script type="text/javascript">
    function callasync(url, container_id) {
        var ajax = false;

        if (window.XMLHttpRequest) {
            //Modern browsers 
            ajax = new XMLHttpRequest();
        }
        else if (window.ActiveXObject) {
            //Internet Explorer       
            try {
                ajax = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e) {
                //Older version    
                try {
                    ajax = new ActiveXObject("Microsoft.XMLHTTP");
                }
                catch (e) {
                }
            }
        }
        else
            return false;

        if (container_id != '') {
            document.getElementById(container_id).innerHTML = "<table width='100%' height='100%'><tr><td style='text-align: center; vertical-align: center;'><a class='LabelInfo'>Wait...</a><br /><img src='Images/Loader.gif' /></td></tr></table>";
        }

        ajax.onreadystatechange = function () {
            handleResponse(ajax, container_id);
        }

        ajax.open('GET', url, true);
        ajax.send(null);
    }

    function handleResponse(ajax, container_id) {
        if (ajax.readyState == 4 && (ajax.status == 200 || window.location.href.indexOf("http") == -1))
            if (container_id != '') {
                document.getElementById(container_id).innerHTML = ajax.responseText;
                adjustLayout();
            }
    }
</script>

Then, simply call the function "callasync" with a URL and the ID of the containing div element:

callasync('mypage.aspx?QS_KEY=123', 'divId');

In the ASP.NET code-behind, override the Render method as shown below:

protected override void Render(HtmlTextWriter writer)
{
    if (Request.QueryString["QS_KEY"] != null)
    {
        //render your desired content here
    }
    else
    {
        base.Render(writer);
    }
}

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 best way to manage a brief webhook timeout in a Node.js environment?

The eSignatures API has been successfully integrated into our app, ensuring smooth functionality up to this point. However, an issue has arisen with the webhook function. When a client signs a document, it triggers our webhook cloud function to update our ...

Dealing with AngularJS memory leaks caused by jQuery

How can I showcase a custom HTML on an AngularJS page using the given service? app.service('automaticFunctions', function ($timeout) { this.init = function initAutomaticFunctions(scope, $elem, attrs) { switch (scope.content.type) { ...

Sending data through ajax to PHP on separate pages is a common practice

Here is where I choose my preferred option Company Name<br /> <select id="company" name="selected"> <option value="">Option A</option> <option value="">Option B</option> </select> When I click this, a mo ...

Attempting to abbreviate repetitive Javascript instructions

I have this functional javascript code, but I feel like there might be a more efficient way to write it. Any suggestions on simplifying this? let searchTerm = 'Some search text'; const isMatch = entry.title.toLowerCase().includes(searchTer ...

Verify whether an object possesses all the attributes of a class in TypeScript

Within my typescript code, I have a class called abc: export class ABC{ public a : any; public b : any; public c? : any; public d? : any; } In one of my functions, I receive an input which is represented as data:any. My goal is to verify i ...

What is the best way to clear radio button selections in a form using reactjs?

I designed a survey form with 4 radio buttons for a single question. I also included buttons to submit the form and clear input fields. However, when I click on "Clear Input," the checked radio buttons do not get cleared. How can I achieve this using the r ...

Ensuring all fetch requests are completed successfully before dispatching an action in React-Redux

I'm currently developing a React application and utilizing Redux to manage the state. Here is a snippet of the code: category-arrows.component.jsx: import React, { Component } from 'react'; import { connect } from 'react-redux'; i ...

Use Enums instead of conditions in Typescript

Consider the code snippet below, which is a function that generates a CSS class based on the value of toCheck: const computeSomething = (toCheck: string) => { return clsx('flex', { 'flex-start': toCheck === 'FIRST', ...

How to implement a pop-up dialog box with multiple input boxes using AngularJS?

If you click on the link below: https://material.angularjs.org/latest/demo/dialog You'll notice that the prompt dialog box features only one input field. I'm curious to know if it's possible to customize this using mdDialog to include mult ...

Determine the status of a script in PHP by incorporating AJAX

I am having trouble with my file upload page in the application. I want to display "Uploading" while the file is uploading and then show "Processing" while the file is being processed. Eventually, after the script completes, my page should redirect to a sp ...

Loading times for the Polymer Project are sluggish

The website design is very appealing. However, it seems to be loading quite slowly even on Google's servers. Is there a way to speed up the initial load time of the Polymer site? Additionally, there are numerous HTTP requests being made; is there a wa ...

Which language is better for refreshing web pages: PHP or Javascript?

May I seek your opinion on this matter? I have the ability to refresh my page using two different methods, but I am uncertain of any potential drawbacks. Can you advise me on which one I should utilize? Edit: Specifically, I am referring to the use of he ...

Issue - Following error occurred in the file connection.js located in node_modules/mysql2 library: Module not found: Unable to locate 'tls' module

I've encountered an error in our Next JS applications where tls is not found. I have tried several troubleshooting steps including: 1. Updating Node modules 2. Using both mysql and mysql2 3. Running npm cache clean --force 4. Removing node_modules di ...

Objects for requesting and responding

When utilizing express.js, middlewares have the ability to modify both the request object and the response object. This raises the question: what exactly do these request and response objects represent, and what information do they hold? ...

The absence of a base path in NestJs swagger configuration

Everything was running smoothly on my local machine. However, I encountered a problem after deploying the application. After deployment, /querybuilder gets added to the base URL. Therefore, http://localhost:80/helloworld turns into http://52.xxx.xxx.139/q ...

Synchronize React Hooks OnchangeORSync React Hooks On

Currently, I am in the process of transitioning my app from using a class model to utilizing hooks. In my code, there is a dropdown list where the onChange method performs the following function: filter(event) { this.setState({ selectedFilter: ...

Ensure the smooth scrolling feature is activated by adding an active class when either clicking or manually scrolling the

I have a script that enables smooth page scrolling, but I want it to automatically add an "active" class to the link corresponding to the section currently in view. While there are similar solutions out there, most of them only apply the class when the lin ...

Creating a dynamic nested form in AngularJS by binding data to a model

Creating a nested form from a JSON object called formObject, I bind the values within the object itself. By recursively parsing the values, I extract the actual data, referred to as dataObject, upon submission. To view the dataObject in a linear format, r ...

Exploring the realms of Django Administrator with external JavaScript integration

Currently, I am working with django 2.0 that includes jquery 2.2.3. My goal is to implement the ImageViewer Javascript app (https://github.com/s-yadav/ImageViewer) on one of my admin pages. I have added the necessary js and css files to the Media class wit ...

Iframe overlay feature functioning on Chrome but not on IE11

I have a Document viewer with a .less file containing the following styling: div.document-previewer-container { //height: 400px; //width: 300px; position: absolute; top: 0; bottom: 0; left: 0; right: 0; //padding: 5px 2px; > div.document-preview { h ...