Search code examples
asp.netjquerywebformsdotnetnuke

Jquery AJAX doesn't call a code behind method


I am trying to invoke method from code behind via jquery.ajax... but nothing happens, no error's just methood is not invoked.
Maybe important to note I use DotNetNuke.
jQuery(document).ready(function () {

    jQuery(window).scroll(function () {
        if (jQuery(window).scrollTop() == jQuery(document).height() - jQuery(window).height()) {
            InfiniteScroll();
        }
    });

function InfiniteScroll() {
        jQuery.ajax({
            type: "POST",
            url: "LoadItemsHandler.aspx/GetData",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                if (data != "") {
                    alert('comething happened! :)');                    
                }
            }
        })
    };

I have tried to add handler method to .ascx and .aspx but none works:

[WebMethod]
        public static string GetData()
        {
            return "<div><h2>I am comming in peace from code behind.</h2><p>Lorem ipsum dolor sit amet ... :)</p></div>";
...

I have tried to put alert() in InfiniteScroll() and it's invoked on scrolling, but background method... nothing :(



UPDATE 1

public string Test(string input)
{
    var serializer = new JavaScriptSerializer();
    return serializer.Serialize(new { Name = input });
}
public static string GetData()
        {
            string json = Test("Mike");
            return json;
}

And I get:

Error:SyntaxError: JSON.parse: unexpected character



UPDATE 2

Ok I got it.
From code behind I return:

var serializer = new JavaScriptSerializer();
            return serializer.Serialize(new { NewTotal = "777", OfType = "love" });

On the ajax call success I have:

success: function (data) {
                if (data != "") {
                    alert(data.d);
...

Now this present following data:

{"NewTotal":"777", "OfType":"love"}

And now the only issue I have is how to get NewTotal or OfType value because when I use data.NewTotal I get undefined?


Solution

  • You don't need to convert result to JSON, it is auto. serialized to JSON

     [WebMethod()]
        public static object GetData()
        {
            return (new { NewTotal = "777", OfType = "love" });
        }
    

    On JS, refer to newTotal like this

    data.d.NewTotal