Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send AJAX request to .aspx page and return JSON

I know that it is possible to send an AJAX request to an .asmx page. And I also know that an .asmx page handles an AJAX request via a web method.

Is it also possible to send an AJAX request to an .aspx page? If so, does an .aspx page also handle an AJAX request via a web method? Note that I would like to return a JSON response from the .aspx page. Is this possible?

like image 231
Rahul Murari Avatar asked Jan 31 '13 10:01

Rahul Murari


3 Answers

You can define web methods in the code-behind of your .aspx page and then call them:

[WebMethod]
public static string doSomething(int id)
{
    ...
    return "hello";
}

And then, to call a web method in your jQuery code:

$.ajax({
    type: "POST",
    url: "YourPage.aspx/doSomething",
    data: "{'id':'1'}",
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function (data) {
        var returnedstring = data.d;
        var jsondata = $.parseJSON(data.d);//if you want your data in json
    }
});

Here is a good link to get started.

like image 77
ZedBee Avatar answered Oct 22 '22 07:10

ZedBee


 $.ajax({
            url: "(aspx page name/method to be called from the aspx.cs page)",
            type: "POST",
            dataType: "json",
            data: $.toJSON(jsonData),
            contentType: "application/json; charset=utf-8",
            success: function (data, textStatus, jqXHR) {
                 //TO DO after success
        }
});

Try the above code

like image 1
ravithejag Avatar answered Oct 22 '22 09:10

ravithejag


if i understood question correctly, Aspx is same as HTML. It will be rendered as HTML. but only difference is Server Side and Controls retaining the states with state mechanism.

so you can do jquery $.ajax() function.

$.ajax({
     url: UrlToGetData,
     dataType:'json',
     success:function(data){
             //do some thing with data. 
           }
});

or if you want to write out json value to the response, then use Response.ContentType first use any Javascript serializer(JSON.NET) , then set the contentType like this.

Response.ContentType="application/json";
like image 2
Ravi Gadag Avatar answered Oct 22 '22 07:10

Ravi Gadag