Are AJAX PageMethods causing issues with Routing?

UPDATE: More recent information located at the end of this post.

I have implemented an Update Panel on a page that triggers a postback using the __doPostBack function.

When accessing the page directly at /path/page.aspx, everything functions as expected.

However, if the page is accessed through a different route such as /otherpath/page, the postback does not initiate.

Any ideas or suggestions for resolving this issue?

Below is the JavaScript code:

/// <reference name="MicrosoftAjax.js"/>
function Check() {
   // Invokes the static page method.
   PageMethods.GetLatestHeadlineTick(OnSucceeded, OnFailed);
}

function OnSucceeded(result, userContext, methodName) {
   // Converting the results from the page method and the hidden value to integers for comparison.
   var LatestTick = parseInt(result);
   var LatestDisplayTick = parseInt($get('LatestDisplayTick').value);

   // If the result from the page method is greater than the latest display tick, trigger a panel refresh.
   if (LatestTick > LatestDisplayTick)
    __doPostBack('UpdatePanel1', '');
   // Otherwise, recheck in five seconds.
   else
    setTimeout("Check()", 5000);
}

// Placeholder function to handle failed calls to page method.
function OnFailed(error, userContext, methodName) { }

function pageLoad() {
  // For initial load and partial postbacks, check for new articles every five seconds.
  setTimeout("Check()", 5000);
}

And the Markup section:

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True">
        <Scripts>
            <asp:ScriptReference Path="/resources/js/bus-times.js" />
        </Scripts>
    </asp:ScriptManager>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server" ClientIDMode="Static">
        <ContentTemplate>
            <asp:GridView ID="gvSchedule" runat="server" AutoGenerateColumns="False" Width="80%">
                <AlternatingRowStyle CssClass="altrowstyle" />
                <HeaderStyle CssClass="headerstyle" />
                <RowStyle CssClass="rowstyle" />
                <Columns>
                    <asp:BoundField DataField="RouteName" HeaderText="Route" />
                    <asp:BoundField DataField="TimeTillDeparture" HeaderText="Departs In" />
                    <asp:BoundField DataField="ScheduledDepartureTime" HeaderText="Est. Departure Time" />
                </Columns>
                <EmptyDataTemplate>
                    Data is currently unavailable.
                </EmptyDataTemplate>
            </asp:GridView>
            <div class="updatedstyle">
                Last updated:
                <asp:Label ID="updated_time" runat="server" ></asp:Label></div>
            <asp:HiddenField runat="server" ID="LatestDisplayTick" ClientIDMode="Static" />
            <asp:HiddenField runat="server" ID="hf_stopID" ClientIDMode="Static" />
        </ContentTemplate>
    </asp:UpdatePanel>

Lastly, the AJAX Method in the code-behind:

<WebMethod()> _
Public Shared Function GetLatestHeadlineTick() As Long

    Dim stopID As String
    If HttpContext.Current.Request.QueryString("stop_id") <> Nothing Then
        stopID = HttpContext.Current.Request.QueryString("stop_id")
    Else
        stopID = "678036"
    End If

    ' Retrieve the cached DataTable.
    Dim dt_added As DateTime = CType(BusScheduleService.GetBusDataDateAdded(stopID), DateTime)

    ' Return the timestamp of that bus data in ticks.
    Return dt_added.Ticks

End Function

UPDATE:

A Fiddler screenshot displaying a successful version at the top and an error at the bottom has been added. The bottom one shows a 405 request error. It seems like the Ajax request is mistakenly being interpreted as a route when resolved, which leads to it not working. How can I overcome this? It appears that when Ajax calls a function, it appends a /functionName after the URL, resembling a route syntax...

Thus, when trying to call the GetLatestHeadLineTick via /path/page.aspx/GetLatestHeadLineTick, it works fine. However, with a route, it goes to /otherpath/page/GetLatestHeadLineTick, causing my site to treat it as a route rather than an AJAX request.

I also noticed that on the successful request, the content type is JSON, while on the failed request, it's interpreted as HTML.

Answer №1

After much time spent investigating, I finally managed to resolve the issue at hand. It turned out that the problem did not lie in conflicts with __doPostBack or AJAX function calls due to routing. Instead, the conflict stemmed from the interaction between the PageMethods class and routing.

PageMethods.GetLatestHeadlineTick(OnSucceeded, OnFailed);

The code snippet above was attempting to fetch page methods from the route, which proved unsuccessful.

All it took to fix the issue was adding the following line just before the problematic one:

PageMethods.set_path('/actualpath/actualpage.aspx')

And just like that, everything started working smoothly!

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

When attempting to compile Angular in production mode, errors may arise such as the Uncaught SyntaxError caused by an Unexpected token '<'

I encountered some errors in the console of my Angular 8 app. When I opened the browser window, it was blank and this error appeared: Uncaught SyntaxError: Unexpected token '<' https://i.sstatic.net/a16DD.png I tried running different ng bui ...

Utilizing Bootstrap modal with dynamic content from MySQL database

My goal is to trigger popup windows when a user clicks on specific buttons within my app. To achieve this, I am utilizing the following code snippet: $('#modal').on('show', function () { $.ajax({ ... }); }); Through AJAX, I am r ...

The functionality of OnMouseOver event within CKEditor

I prefer using the CKEditor WYSIWYG editor. One issue I have encountered is with a div element that includes an onMouseOver attribute. When this element is within the editor, the onMouseOver attribute gets changed to data-cke-pa-onmouseover. Despite my eff ...

Using JavaScript to divide an associative array into separate arrays

I am dealing with an array of clubs var clubs =[{ team: {name: "fcb barca", rank: 4}, team: {name: "man utd", rank: 16}, team: {name: "man city", rank: 36}, team: {name: "fcb liverpool", rank: 57} }]; The task at hand is to separate this ...

Display information retrieved from a web service in a datagrid within a WPF application

I've been attempting to display data from a webservice in a datagrid using WPF, but I seem to be encountering errors or the data isn't being displayed at all. Here's what I have so far. WINDOWS.XAML <Window x:Class="IssueAddinOutlook.Wi ...

Select2 loading screen featuring preloaded value

Trying to populate a select2 box with instrument options on an edit profile page for a musician site. The information is pulled from the database, but I'm struggling to display the existing instrument list in the select2 box upon render - it always ap ...

I am currently experiencing difficulties with loading files in Magento even though they are present on the server

I am experiencing difficulties with a Magento 1.5.1 installation that was not a fresh setup, but rather one that was transferred to another server (files and database copied over). The issue I am facing is related to the failure of my Javascript files to ...

Updating a form section using Ajax and displaying the updated results on the current page

In my attempt to achieve a goal, I came across this helpful resource: Here is a condensed version of my model: public class Iro : EntityBase { public int ReportYear { get; set; } public Guid DcmDataCallId { get; set; } public ...

An error occurred while parsing the AJAX response: Unexpected token ':'

Here is the code snippet for my Ajax request: $(window).ready(function () { var $form = $(document).find('#name-form'); var $display = $(document).find('#display'); $form.on('submit', function (e) { e.prev ...

What could be causing the hidden div to disappear after a button click in asp.net?

I am having an issue where a hidden div is not staying visible after clicking the login button. I want the div to remain visible on the page until another action is taken, but it disappears right after the login click event. Here is my button code: <a ...

angular corresponding vue binding="$props"

If I wanted to take a shortcut, I could utilize v-bind="$props" to dynamically set key values as shown in the sample below : <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> ...

Retrieve the values of the checkboxes that have been selected using jQuery and pass them to another page for

I am seeking assistance with jQuery as I am a beginner in coding with it. Any solutions or guidance would be greatly appreciated. Here is the markup code I have: <input type='checkbox' data-headmark=".$row['HEAD_MARK']." data-id=". ...

Managing the DBNull.Value occurrence

When working with DataTables connected to grid controls, I often find that custom updating results in a lot of code related to DBNull.Value. Although I came across a similar question on this topic, I believe there must be a better solution: What is the be ...

Currently exploring the capabilities of callback functions in jQuery using the $.post method

A jQuery script is functioning well, however it is having trouble sending the data via $.post and retrieving a response. Here's the applicable code: $.post( 'test.php', { userfname: f.editfname, userlname: f.editlname, userid: v.use ...

Trouble with FilterBy Feature in Bootstrap-Table

I am attempting to use filtering functionality with a table that is populated via JSON, utilizing bootstrap-table by wenzhixin. HTML snippet: <button class="btn btn-primary" id="filterBtn">Filter</button> <div class="container"> &l ...

What do you want to know about Angular JS $http request?

My goal is to send a request using $http with angular js in order to retrieve a json object from google maps. $http.get('http://maps.googleapis.com/maps/api/geocode/json?address=' + data[ 'street' ] + ',' + data[ 'city&a ...

Access the value within an object that contains an array and compare it with a different array

array1 = [{id: 1, email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="92e6f7e1e6a3d2e6f7e1e6bcf1fdff">[email protected]</a>', group_ids: ["25"], username: 'test1'}, {id: ...

Building dynamic 3D scenes using JSONLoader in Three.js and Angular4

Having trouble integrating a JSON file into an Angular 4 environment using a JSONLoader. The path to the JSON file is correct, but I can't add it to the scene. I'm receiving an error "cannot set property 'mesh' of undefined" on the line ...

Click on the parent element to trigger a reaction from its child elements when clicked

Here's how my document object model (DOM) is structured: <div class="profile"> <a href="#"><img src="/img1.gif" /></a> <b>100</b> <a href="#"><img src="/img2.gif" /></a> </div> ...

The value within the style.setProperty function does not get applied

I have a progress bar that dynamically increases based on user input: <div class="progressBarContainer percentBar"> <div class="progressBarPercent" style="--width:${gPercent}" id="${gName}-pbar">< ...