1110
1110

Reputation: 6829

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?

Upvotes: 0

Views: 3485

Answers (3)

Tran Anh Hien
Tran Anh Hien

Reputation: 747

can use library using Newtonsoft.Json;

JsonConvert.SerializeObject(Request["paramater"])

Upvotes: 0

Michael B.
Michael B.

Reputation: 2809

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

Upvotes: 2

Maverick
Maverick

Reputation: 478

Well, first of all, calling Page methods inside UserControl will not work, so they should be defined in the aspx page.

Secondly, check for errors in firebug.

Also, make sure that you are calling from the same page.

Thirdly, use a webservice (*.asmx)

Upvotes: 0

Related Questions