Getting json data through ajax in asp.net

I am facing an issue with the variable data in the function ShowFavorites as it is showing as undefined even though my ajax call is returning a json string.

<script type="text/javascript">
$(document).ready(function () {
    ShowFavorites();

    function AjaxGet() {
        var param = "{'_userID': '1337'}";
        $.ajax({
            type: "POST",
            url: "/webservices/MinSide.asmx/GetFavorites",
            data: param,
            contentType: "application/json;",
            dataType: "json",
            success: function (data) {
                if (data.hasOwnProperty("d")) {                      
                    return (data.d);
                }
            },
            error: function (data) {
                //error
            }
        });
    }

    function ShowFavorites() {
        var data = AjaxGet();

        $("#addedList").html(
        $("#addedTemplate").render(data)
        );
    }
});

        [WebMethod]
    public string GetFavorites(string _userID)
    {
        JavaScriptSerializer jss = new JavaScriptSerializer();
        jss.MaxJsonLength = int.MaxValue;
        string JsonData = string.Empty;

        var db = new ModelDataContext();
        var list = db.table.Where(x => x.userID == _userID).OrderBy(x=> x.TimePin).ToList();

        JsonData = jss.Serialize(list);  
        return (JsonData);
    }

Why am I unable to return the result from my ajax call?

I hope someone can assist me as I have been stuck debugging this issue for hours now.

Thank you in advance.

Answer №1

The $.ajax function call within the AjaxGet function is performed asynchronously. This means that the function will return undefined immediately because the ajax call is still in progress.

To ensure that the call to ShowFavourites is executed only after the ajax call is successfully completed, you need to move it inside the ajax success function.

<script type="text/javascript">
$(document).ready(function () {
    // Initiate the ajax request
    AjaxGet();

    function AjaxGet() {
        var param = {_userID: '1337'};
        $.ajax({
            type: "POST",
            url: "/webservices/MinSide.asmx/GetFavorits",
            data: param,
            dataType: "json",
            success: function (data) {
                if (data.hasOwnProperty("d")) {                      
                    ShowFavourites(data.d); // Send the data to the template
                }
            }
        });
    }

    function ShowFavourites(data) {
        $("#addedList").html(
            $("#addedTemplate").render(data)
        );
    }
});

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 issue with the jQuery Mobile onclick event is that it fails to remove the ui-disabled

Ever since I delved into coding with jQuery Mobile, I've noticed a change in the function that once effortlessly removed the "ui-disabled" class. Now, all it does is display an alert message... Snippet from the HTML code: <div data-role="navbar ...

What is the best way to retrieve information in an autosuggest textbox from a server or database?

I am looking for a way to modify my autosuggest textbox to fetch data from a server instead of a defined array. Can anyone provide guidance on how to achieve this? Here is the code snippet I am currently working with: HTML code- <!doctype html> &l ...

The functionality of TypeScript's .entries() method is not available for the type 'DOMTokenList'

I'm currently working with a stack that includes Vue3, Vite, and TypeScript. I've encountered an issue related to DOMTokenList where I'm trying to utilize the .entries() method but TypeScript throws an error saying Property 'entries&apo ...

The dynamic trio: Ajax, PHP, and MySql

Having some trouble with Ajax. Nothing seems to be happening when I change the select value. I've set up a div called textHint to display the result. This is my select setup: <form> <select id="choix" name="choix" onchang ...

Struggling with passing data to a child component in React

I am currently working on a gallery project where users can click on an image to view it in a separate component using props. The images are sourced from a hardcoded array, and the challenge lies in connecting this data to the component accurately. I have ...

What is the best way to encode a GLTF file without compromising the encoding of other meshes and textures?

Currently, I am working on a fascinating web AR app that enables users to don GLTF head models. (You can check it out at ) To ensure optimal lighting of the GLTF model, I have implemented renderer.outputEncoding = THREE.sRGBEncoding, which has been very ef ...

The Sluggishness of MongoDB Aggregation in Determining Distinct IDs within Retrieved Documents

Not only does my Mongo view return a filtered set of documents to the end user, but it also runs a couple of functions to calculate running totals. Strangely though, while my find() operation is blazingly fast (225ms), this additional aggregation process t ...

After upgrading to react native version 0.73, the user interface freezes and becomes unresponsive when working with react-native-maps

After upgrading my app to the newest version of react native 0.73.x, I encountered an issue where the UI on iOS starts freezing and becoming unresponsive in production. The main screen loads react-native-maps with numerous markers, and this was not a pro ...

React Component for Toggling a Click Event on a Select Tag

I'm currently developing a react app where clicking on a specific text triggers the display of a select tag with several items. However, I've encountered two issues: Upon clicking the text, the select tag appears on ALL list items instead of ju ...

How can I verify a particular value from a table in asp.net using C#?

string connectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; SqlConnection connection = new SqlConnection(connectionString); connection.Open(); string selectStatusQuery = "select status from Status where c_email=@c_email"; S ...

The Material-ui paper component fails to display on the screen

The material-ui paper component is implemented on my homepage and functioning correctly. However, when navigating to another page and returning to the homepage, the paper component disappears, leaving only text rendered. Can you help me identify the issue? ...

Issue with mouseMove function not aligning correctly with object-fit:contain CSS property

My current code allows users to select a color from an image when hovering over the pixel with the mouse. However, I am encountering an issue where the colors do not map correctly when using object-fit: contain for the image. The script seems to be treatin ...

It is my goal to populate the array with numbers while avoiding any duplicate entries

I am currently facing an issue with my code as it is returning a length of 0 instead of the expected result of 5 after excluding duplicates from the array. I have a feeling that there might be something missing in my code, but I just can't seem to fig ...

Leverage variable as an expression when utilizing ng-include

Here is an example of working code: <div ng-include src="'Test.html'"></div> However, this code does not work: <div ng-include src="ctrl.URL"></div> (When ctrl.URL is set to "Test.html"). I have also tried setting it t ...

Crafting redirect rules in React that avoid redirecting to the same route

In my project, there is a file named AuthenticatedRoute.tsx, which serves as a template for all the protected/authenticated routes in my Router.tsx file. export default ({ component: C, authUser: A, path: P, exact: E }: { component, authUser, path, ex ...

Explore our array of images displayed in an interactive gallery featuring clickable

I have a query I'm facing an issue with my code. Currently, I have a gallery that displays images perfectly. Now, I want to enhance it by showing a larger resolution of the image when clicked. However, when I add the href tag to link the images, they ...

Utilizing JSON data for Autocomplete with Ajax and Jquery

I have been working on setting up my Jquery UI autocomplete field to pull data from an ajax connection. Here is the progress I've made so far: $("#mainIngredientAutoComplete").autocomplete({ source: function (request, response) { $.ajax({ ...

"Utilizing regular expressions in JavaScript to check for multiple

I have a function that replaces HTML entities for & to avoid replacing &amp; but it still changes other entities like &, ", >, and <. How can I modify the regex in my function to exclude these specific entities? &apos; &quo ...

A guide on Implementing PastBack Functionality with AJAX Responses

When I make a GET request for an HTML page, I come across the following element: <a id="ctl00_cphRoblox_ClaimOwnershipButton" href="javascript:__doPostBack('ctl00$cphRoblox$ClaimOwnershipButton','')">Claim Ownership</a> My ...

The width values in the array are constantly shifting upon refreshing

Would it be possible to create an array called slide_widths, which will contain the widths of all the .slide elements? $( document ).ready(function() { var $slider = $('.slider ul'); var slider_width = $slider.width(); var $slides = $(&apo ...