Invoking an ASP.NET page with JavaScript and transmitting a response

I'm struggling with a JavaScript script that makes an AJAX call to a service:

  $.ajax({
        type: "GET",
        url: ServiceAddress + "/Service.aspx?action=LoadRandomImagePath&userID=" + USER_ID,
        success: function (result) {
            if (result.LoadRandomImagePathResult.ID != 0) {
        //something
        }

Here is what happens when the Service.aspx is called:

Response.Write(svc.LoadRandomImagePath(int.Parse(Request.QueryString["userID"])));

The svc.LoadRandomImagePath method returns JSON data and writes it to the Response.

However, my issue arises when I receive the result on the JavaScript side - it includes the full code of the Service.aspx page:

{JSON HERE}  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head><title> </title></head> <body> <form method="post" action="Service.aspx?action=LoadRandomImagePath&amp;userID=18" id="form1"> <div class="aspNetHidden"> <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE2MTY2ODcyMjlkZLyq7A39QtHu0Ngft6E/6ZwTABk29noGDsoP6FKK6UIo" /> </div> <div> </div> </form> </body> </html>

My goal is to only get the JSON response without any additional page code. Is there a way to achieve this?

Answer №1

Have you attempted setting the return data type to JSON in your original request?

 $.ajax({
        type: "GET",
        dataType: "json",
        url: ServiceAddress + "/Service.aspx?action=LoadRandomImagePath&userID=" + USER_ID,
        success: function (result) {
            if (result.LoadRandomImagePathResult.ID != 0) {
        //something
 }

Furthermore, it is important to clear any existing content and update the data type for the JSON page:

Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(svc.LoadRandomImagePath(int.Parse(Request.QueryString["userID"])));
Response.End();

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

Activate jscolor following an ajax submission that clears the form

After an AJAX post that resets a form's elements back to their default values, how can you reinitialize the jscolor component? The AJAX function below successfully posts data and restores form values when clicking the "Restore Default" button. Howeve ...

Looking for a JSON deserializer to work with a third-party case class

I am currently setting up a SecureSocial service in my Scala Play! application, utilizing the ReactiveMongoPlugin to interact with the MongoDB database. Below is the code snippet that I am using: lazy val users: JSONCollection = ReactiveMongoPlugin.db.co ...

Having trouble getting anime.js to function properly in an Ionic 3 project?

I have been attempting to incorporate anime.js into my Ionic 3 project, but I keep encountering an error when using the function anime({}) in the .ts file. Error: Uncaught (in promise): TypeError: __webpack_require__.i(...) is not a function TypeError: _ ...

`Hovering over a div triggers a continuous animation loop`

I've gone through various questions and solutions related to this issue, but unfortunately, none of them seem to work for me. It's possible that I might be overlooking something or my scenario is slightly unique. The main problem I'm facing ...

The JavaScript file is not compatible with Internet Explorer 9

My website's JavaScript functions normally work on all browsers except for Internet Explorer 9. In IE7 and IE8, they also work normally. After extensive testing, I have concluded that the JS file simply does not work in IE9, but why is that? The curio ...

Sharing Variables with $(document).ready

I need help understanding why this code is not functioning and how I can fix it. Despite my efforts to use namespaces and IIFEs, I am still unable to make it work. $(document).ready(function() { alert (hi); }); $(document).ready(function() { var hi = ...

Having trouble extracting the selected date from a datetimepicker to pass it via AJAX

The datetimepicker on my webpage is structured like this: <table class="table borderless" id="schedule_time"> <tbody> <tr> <td align="center"> <div id="timepicker" class="form-group" style="width:30%"> ...

JavaScript Array Randomizer with the Ability to Add Names to the List

I've been working on a JavaScript program lately. It's supposed to randomly select two characters from Once Upon A Time and match them up. The randomizing part is fine, but I'm struggling with the "Add Name to Array" feature. Here's my ...

How to use the sha512 hash function in Node.js for Angular2 and Ionic2 applications

I'm attempting to generate a SHA512 Hash in Angular2 (Ionic2) that matches the PHP function hash('sha512'). After trying out different modules like crypto-js, crypto, and js-sha512, I keep getting a different Hash compared to PHP. I even a ...

Is it feasible to access a service instance within a parameter decorator in nest.js?

I am looking to replicate the functionality of Spring framework in nest.js with a similar code snippet like this: @Controller('/test') class TestController { @Get() get(@Principal() principal: Principal) { } } After spending countless ho ...

Querying Parse Server for objectId information

Within my web app that utilizes the Parse Server Javascript SDK, I have implemented the following query. While the console log accurately displays the retrieved information, the objectId field appears as "undefined." var query = new Parse.Query("myClass") ...

Angular UI and Node backend causing CORS issues

Just diving into the world of node and could use a little assistance. Encountering this error message: Access to XMLHttpRequest at 'http://localhost:3000/api/auth/signin' from origin 'http://localhost:4200' has been blocked by CORS pol ...

What could be causing my php code to fail to trigger an alert when using Ajax technology?

As a novice in web programming, I have successfully created a website but now I am facing challenges while trying to integrate a database. Despite having everything properly set up, my ajax function doesn't seem to be working and I can't figure o ...

Toggle the display of selected options based on the presence of multiple classes within a td element

Upon selecting an option from a dropdown, certain columns are shown while others are hidden. Some columns have multiple classes assigned to them. For instance: "object 7" belongs to "category 1" and "category 3". "objec ...

Incorporating events into a calendar using JSON in IOS Titanium

Is there a way to prevent duplicate entries when adding events to the iOS calendar from a JSON file timetable? I want to avoid adding events if there is already an existing event on the same date. How can this code be modified to achieve that? var fileN ...

What steps should I take to troubleshoot the issue when utilizing full HTML link paths in my links?

I have come across the recommendation to use full link paths between pages on my website for various reasons. However, I am concerned about how to debug and work on my local testing environment when all of the links are using full paths. (Manually replaci ...

The D3 force layout is currently displaying just a single connection

I've been experimenting with a graph that I found in this demo and now I want to modify it to display data from Spotify. I created a sample JSON file and adjusted the script accordingly for the new data format, everything seems to be working fine exc ...

Developing an HTML table using information from JSON dataset

I am working with an HTML file that includes the following code snippet: <div> <table id="apps"></table> </div> Recently, I started receiving JSON data structured like this: { "1": [ { "A": "", ...

Swapping out components or features within AngularJS

Is it possible to make my dependencies interchangeable in AngularJS? For example, if I have a service named myService stored within the module myDependency, how can I switch out myDependency with a new service without disrupting the main application? Shou ...

Guide to arranging an object in ascending order based on a key's value using JavaScript

Is there a way to sort the following values: 1, 99, 1, 50 in javascript? Given the input: var map = {test:1, test2:99, test3:1, test4: 50} The desired output is: {test2:99, test4:50, test3:1, test:1} This is the approach I have attempted: function sort ...