Verify if an Ajax request has been made

I've been trying to figure out how to determine if a request is made via AJAX in C#, but I'm having trouble getting it to work. Below is the code I'm using. I am using a method to make an AJAX call on the client side (I'm using the ActiveXObject in my case). The page being AJAXed is checking for AJAX properties on the server-side, but neither of the X-Requested-With properties are returning anything (they are blank when printed out). Any suggestions?

Ajax Method (Javascript)

/*
* Ajax page loads with url
* @param url : URL to call for ajax page load
* @param element : Element ID to be updated
*/
function ajax(url, element) {
    UtilLogger.log(HtmlLogger.INFO, "-AJAX Call for " + url + " in " + element + "-");
    var ajx;
    if (window.HXMLHttpRequest) {
        UtilLogger.log(HtmlLogger.FINE, "Using XMLHttpRequest");
        ajx = new XMLHttpRequest();
    }
    else {
        UtilLogger.log(HtmlLogger.FINE, "Using ActiveXObject");
        ajx = new ActiveXObject("Microsoft.XMLHTTP");
    }
    ajx.open("GET", url, true);
    ajx.send();
    ajx.onreadystatechange = function () {
        if (ajx.readyState == 4 && ajx.status == 200) {
            document.getElementById(element).innerHTML = ajx.responseText;
        }
        else if (ajx.readyState == 4 && ajx.status == 400) {
            alert("Page Error. Please refresh and try again.");
        }
        else if (ajx.readyState == 4 && ajx.status == 500) {
            alert("Server Error. Please refresh and try again.");
        }
    }
    UtilLogger.log(HtmlLogger.INFO, "-END AJAX Call for " + url + " in " + element + "-");
}

Ajax Login Check (C#)

/* Checks for ajax request validity
 * @param HttpResponse resp : response to redirect if not ajax request
 * @param HttpRequest req : request to check for ajax
 */
public static void checkAjax(HttpResponse resp, HttpRequest req)
{
    if(req == null || 
        (req["X-Requested-With"] != "XMLHttpRequest" && 
        (req.Headers != null && req.Headers["X-Requested-With"] != "XMLHttpRequest"))){
           // resp.Redirect("./ajaxerror.aspx");
            resp.Write(req["X-Requested-With"] + ":" + req.Headers["X-Requested-With"]);
    }
}

Answer №1

If your client-side request does not automatically include an "X-Requested-With" header or query parameter to the server, you can manually add it in an AJAX call. Some frameworks like Microsoft AJAX may do this automatically, but for those that don't, you can add the header yourself:

xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");

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 functionality of the TURF booleanwithin feature is malfunctioning and not producing the

Currently, I am working on validating whether a polygon is completely within another polygon. However, there are cases where more complex polygons should return false, but turf interprets them as valid. If you'd like to see the sandbox, click here: ...

Transforming iframe programming into jquery scripting

Currently, I have implemented an Iframe loading the contents within every 5 seconds. It works well, however, there is a consistent blinking effect each time it loads which can be quite bothersome. I am looking to replace the iframe with a scrolling div so ...

Revise my perspective on a modification in the backbone model

I am new to using Backbone and I am currently practicing by creating a blog using a JSON file that contains the necessary data. Everything seems to be working, although I know it might not be the best practice most of the time. However, there is one specif ...

JSON Date Format

I'm facing an issue where I am unable to retrieve the current date using new Date() because it is in JSON format. This particular code was written using MVC C#. The date appears as \/Date(1531364413000)\/. The dates stored in the database ...

Error encountered while trying to eliminate array element

I have a project in the works that involves creating a page where users can filter suggestions and vote for their favorites. The screen is divided into 3 tabs: [Top Rated], [Newest], and [My Votes]. Upon loading the screen, a call to the database is made ...

Retrieving script data from a webpage

I found a link that I want to extract content from, here is the link: https://www.whatever.com/getDescModuleAjax.htm?productId=32663684002&t=1478698394335 However, when I try to open it using Selenium, it doesn't work. It opens as plain text wit ...

Managing date validation for a three-part field using AngularJS

I am currently working on validating a three-part date field using AngularJS. I have managed to create a custom validation function, but I am struggling with determining how the fields should update each other's status. How can I ensure that all thre ...

The request to remove the product from the server at URL http://localhost:8000/product/[object%20Object] encountered an internal server

I'm having trouble setting up the AJAX delete method. I keep getting a 500 internal server error and despite following tutorials, I remain frustrated. Can someone please help me correct my code? This is using Laravel 5.8 and jQuery 3.3. <section ...

What is the best strategy for queuing AJAX requests when they depend on input from previous requests for efficiency?

I am currently developing an application within the SharePoint platform that requires making three distinct AJAX requests: Firstly, a call to the Search API is made to retrieve all individuals with a specific job title associated with the account ID (sea ...

Navigating horizontally with buttons in VueJS

I am searching for a way to implement horizontal scrolling using buttons in VueJS. The idea is to have a container with multiple divs arranged horizontally, and I wish to navigate through them using the buttons. If you want to see a similar solution using ...

javascript unusual comparison between strings

I am working on an ajax function that is responsible for sending emails and receiving responses from the server in a JSON format with type being either success or error. $("#submit_btn").click(function(event) { event.preventDefault(); var post_d ...

Is there a way to verify the presence of multiple array indices in React with TypeScript?

const checkInstruction = (index) => { if(inputData.info[index].instruction){ return ( <Text ref={instructionContainerRef} dangerouslySetInnerHTML={{ __html: replaceTextLinks(inputData.info[index].instruction) ...

Having trouble populating Extjs Grid with JSON data

In this simple grid, I am attempting to display three columns - Subject ID, Subject Name, and Subject Short Name by obtaining JSON data. The data is stored in a variable called myData in JSON format, which has been received from the server. Despite pasting ...

The data in Node AngularJS is not loading upon the page's initial load

When I log in, I am redirected to a different page where a partial page is loaded using an AngularJS route. By clicking on any anchor tag, the respective partial view is displayed. However, I encountered an issue. Upon logging in, I use res.render(pagenam ...

There seems to be a problem with the sorting functionality on the table in React JS,

My React table is functioning well with all columns except for the country name column. I double-checked the API and everything seems to be in order, but I'm stuck on how to troubleshoot this issue. const Table = () => { const[country, setCount ...

Transfer the output to the second `then` callback of a $q promise

Here is a straightforward code snippet for you to consider: function colorPromise() { return $q.when({data:['blue', 'green']}) } function getColors() { return colorPromise().then(function(res) { console.log('getColors&ap ...

Encountering problems during JSON response deserialization

Upon calling an API, I received the following response as part of a functional test for handling a bad query: HTTP/1.1 400 Bad Request Date: Fri, 24 Jan 2014 17:43:39 GMT Sforce-Limit-Info: api-usage=5/5000 Content-Type: application/json;charset=UTF-8 ...

The CollapsiblePanelExtender remains unresponsive

I am currently utilizing a CollapsiblePanelExtender in combination with a checkbox. The goal is to have the panel expand or collapse based on the checkbox being checked or unchecked. While this functionality does work, I am facing an issue where the panel ...

Unable to modify attributes of LinkButtons in code-behind

I am struggling with what should be a simple task, something I have done countless times before. However, this time, I can't seem to get it right. Within my Gridview, I have LinkButtons set up like this: <asp:TemplateField> <ItemTemplat ...

Retrieving HTML elements from the website address

Imagine having a URL like www.example.com. On this webpage, there is a DOM element <a>. To programmatically click on this element, you would typically use document.getElementById('#link')[0].click(). The challenge arises when dealing with ...