Send AJAX request to .aspx page and return JSON - asp.net

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?

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.

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";

$.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

Related

call a static method in User Control from js or ajax

I am trying to call a static method in User Control from js or ajax.
It is possible to do this if the code method lies directly in WebForm but it is not possible to do it if we put the code method in UserControl and then put this UserControl in a WebForm.
Code Behind:
[WebMethod]
[ScriptMethod(ResponseFormat= ResponseFormat.Json)]
public static string GetNameFromCodeBehind (string name)
{
return "Hello from Code-Behind, " + name ;
}
AJAX Code:
$.ajax({
type: "POST",
url: "MyUserControl.ascx/GetNameFromCodeBehind",
data: JSON.stringify({ name: "Anton" }),
contentType: "application/json; charset=utf-8",
dataType: "json",
processdata: true,
success: function (data) {
alert(data.d);
},
error: function (e) {
alert(e.statusText)
}
});
Ajax Error:
Not Found
If GetNameFromCodeBehind is inside MyUserControl.ascx, then it will be able to find a URL. Moreover, you have written the name of static method as callFromCodeBehind. So, you need to write the URL sccordingly

Jquery Ajax error for asp.net page

I have a very simple page and a [WebMethod] inside it which returns a simple message. I would like to show this message through $.ajax on client side. however my website is using rewrites rules so my url becomes readable to user.
EX:
Actual webpage: www.mysite.com/about // which has about folder and a user control inside it
there is no aspx page for this instead i am using a method which gets a webpage data which is actual html page and show the content on user control.
here is Jquery part.
$(document).ready(function () {
$('.info a').click(function () {
$.ajax({
type: 'POST',
url: '/about/showServer', //which url to put here
async: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("result.d");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
});
});
});
C#
[WebMethod] // this method is in the user control
public static string showServer()
{
return "Hello from server";
}
How to call this method from client using $.ajax
appreciate your time and help.
EDITS
I have this structure for my website
mysite.com/about
/about/defualt.aspx --> which loads the user controls
user controls resides in
mysite.com/ConLib/Custom/about.ascx/showServer
So i set it to like this
url: '/ConLib/Custom/about.ascx/showServer',
BUT i see error in chrome developer tool in XHR request "404 error" because when you type mysite.com/conlib/blah blah ..reqrites does not allows this and throws 404 error..
Your ajax success method should be this:
alert(result.d);
Instead of this:
success: function (result) {
alert("result.d");
}
and url should be:
url: "Default.ascx/showServer", // UserControlPage/MethodName
you need to decorate your web method
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.Wrapped,
ResponseFormat = WebMessageFormat.Json)]
public static string showServer()
{
return "Hello from server";
}
If your WebMethod is inside a User Control, then it needs to be moved to the ASPX page. See this post:
How to call an ASP.NET WebMethod in a UserControl (.ascx)
The url: param should be in the form of '/MyPage.aspx/showServer'

webservice not returning values to on jquery ajax request

I would like consume cross-domain web-service from client with jquery.here is my code
function getId() {
var testid = ($('#<%=PreviousTest.ClientID %> OPTION:selected').val());
jQuery.support.cors = true;
jQuery.ajax({
type: "POST",
url: "../FalconWebService.asmx/minlatency",
data: "{'testId':" + testid + "}",
contentType: "application/json; charset=utf-8",
dataType:"json",
success: function (data) {
alert("catch");
var msg = jQuery.parseJSON(data.Table);
return msg;
},
Error: function () {
alert("error");
}
my webservice returns values in this format
{"Table":[{"minlatency":16.0,"Time":"/Date(1328248782660+0530)/"},{"minlatency":7.0,"Time":"/Date(1328248784677+0530)/"},{"minlatency":13.0,"Time":"/Date(1328248786690+0530)/"},{"minlatency":6.0,"Time":"/Date(1328248788690+0530)/"},{"minlatency":20.0,"Time":"/Date(1328248790707+0530)/"},{"minlatency":12.0,"Time":"/Date(1328248792723+0530)/"},{"minlatency":26.0,"Time":"/Date(1328248794723+0530)/"},{"minlatency":18.0,"Time":"/Date(1328248796723+0530)/"}]}
Calls in cross-domain work in a different way. They create dynamic javascripts that are inserted to the page using a callback function. This function is used to handle the response from the service. The Jquery calls add a "?callback=?" to the URL of the service, where "callback" is the name of the function that will be inserted.
To call cross-domain services with JQuery you have to do the following:
jQuery.ajax({
type: "POST",
url: "../FalconWebService.asmx/minlatency",
data: "{'testId':" + testid + "}",
contentType: "application/json; charset=utf-8",
dataType: "jsonp", //The data type that you must use is JSONP. Basically tells JQuery that the request is cross-domain
success: function (data) {
alert("catch");
var msg = jQuery.parseJSON(data.Table);
return msg;
},
Error: function () {
alert("error");
},
jsonpCallback: 'callback' //Dude to the fact that the JS is being generated dynamicaly, this tells JQuery to use the name "callback" for the function that will handle the result, as it adds "?callback=?" to the URL
});
You could also use "jsonp" instead of "jsonpCallback" if you want to "override the callback function name in a jsonp request" (from JQuery).
It worked for me (in WCF REST services which communicate with JSON messages, but it should work the same way in your case). This is all explained in the JQuery Ajax documentation.
Hope this helps.

Parameter from codebehind to jquery [ Master Page]

I am creating Menu in the master page using JQuery. i am passing the id of the link to jquery using $.ajax({});
Problem:
Getting failed: Showing error message in AjaxFailed(result) function.
Code:html[JQuery]
$.ajax({
type: "POST",
url: "Master.Master.cs/UserStatus",
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
function AjaxSucceeded(result) {
if (result.d.length != 0) {
for (var i = 0; i < result.d.length; i++) {
$(result.d[i]).hide();
}
}
}
function AjaxFailed(result) {
alert("Error");
}
c# Code:Codebehind
private static List<string> xx;
[WebMethod]
public static List<string> UserStatus()
{
return xx;
}
protected void Page_Load(object sender, EventArgs e)
{
xx = new List<string> {"#ll1", "#ll2" };
}
What the webmethod attribute does is to say that this method should respond to a certain url (a little bit like routing in asp.net mvc). As I don't use webforms I don't really know what logic it uses when it decides what url the method should respond to. But my guess is that the url should be something like "Master.cs/UserStatus" (not sure about the .cs extension). And that is of course a relative url, so you can try something like this: <%=ResolveUrl("~/Master.cs/UserStatus")%> (if the masterpage is in your root folder). Then your example should be something like this:
$.ajax({
type: "POST",
url: '<%=ResolveUrl("~/Master.cs/UserStatus")%>',
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
Update
The .cs extension is probably wrong. But I don't think you should have that in a master page anyway. You should probably have it in a web service or in a .ashx handler or something if you want to use ajax. But with you last comment it seems that you don't need to use ajax (and if you don't need that, you shouldn't). The problem in the code you wrote in the comment is probably that the id is wrong (remember that you need the client id in javascript).
But I would probably do it something like this:
<script type="text/javascript">
var statuses = [];
<%foreach(var status in UserStatus()) {%>
statuses.push(<%=status%>);
<%}%>
</script>
This will render this javascript in the browser:
<script type="text/javascript">
var statuses = [];
statuses.push("#ll1");
statuses.push("#ll2");
</script>
Then you will have your statuses in the statuses array.
Like Andre and Mattias mentioned, the .cs extension is not served, so you would have to use a .aspx extension to get to the WebMethod.
The problem I see in your example is that you are placing the method in the MasterPage (which would have a .master extension) which is also not served, so you can't call the web method from it.
A workaround you could use is to define it in a class that inherits from Page, and have all of your pages inherit from that class. Since its a public method, it will be public on all of your pages and therefore available. Basicly, a base page for your project's pages. In that case you would only need to use your current page's address to make the call. This is only usefull if it's something you will use on every page, like a menu.
A second workaround you can use is to define the WebMethod in a .asmx Webservice placed in the project. It would work like calling the WebMthod on a page, only you would have to use the .asmx Webservice's address instead of the page's to make the call.
If you've not done so you will need to add the [ScriptService] attribute to your webmethod as this
Indicates that a Web service can be
invoked from script
See ScriptServiceAttribute
I think that the problem is that you try to post to the .cs file. The extension .cs is not served by ISS due to security reasons. So even though your method lifes in the code behind file, you have to post to the .aspx file. ASP.NET will do the rest for your.
So try:
$.ajax({
type: "POST",
url: "/Master.Master.aspx/UserStatus",
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
function AjaxSucceeded(result) {
if (result.d.length != 0) {
for (var i = 0; i < result.d.length; i++) {
$(result.d[i]).hide();
}
}
}
function AjaxFailed(result) {
alert("Error");
}

How to post data using jQuery in ASP.NET?

I have an ASP.NET application in which i want to post data using jQuery to another page. It means i want post the data of page.
How can i do this with jQuery or AJAX?
Please help me.
$(document).ready(function() {
alert("start");
$("#btnSave").click(function() {
alert("start1");
var aa = 'bb';
var json = "{'ItemName':'" + aa + "'}";
alert("start2");
var ajaxPage = "Default3.aspx?Save=1"; //this page is where data is to be retrieved and processed
alert("start3");
var options = {
type: "POST",
url: ajaxPage,
data: json,
contentType: "application/json;charset=utf-8",
dataType: "json",
async: false,
success: function(response) {
alert("success: " + response);
},
error: function(msg) { alert("failed: " + msg); }
};
alert("start4");
});
});
I am using this code I am getting all alert response but its posting page.
Jquery and JSON works great with ASP.NET. You can call a code behind method directly from javascript and return complex objects, not just string. (for this example to work you need json2.js found here https://github.com/douglascrockford/JSON-js)
//javascript
function postMethod(text){
var jsonText = JSON.stringify({ name:text });
$.ajax({
type: "POST",
url: "yourpage.aspx/GetPerson",
contentType: "application/json; charset=utf-8",
data: jsonText,
dataType: "json",
success: function(response) {
var person = response.d;
alert(person.Name);
}
});
}
//aspx code behind
[WebMethod]
public static Person GetPerson(string name)
{
Person person = new Person(name);
return person;
}
There is load function.
You may use it like this:
$('#somediv').load('http://someaddress',{key:value}, function callback(){});
Second parameter is important - only written in this way performs post.(if you pass array then it performs get)
PS> This is good when you want to read the data, if you want to just do the POST and don't care about what comes back then you may want to use:
http://docs.jquery.com/Ajax/jQuery.post#urldatacallbacktype
Look at $.post() - http://docs.jquery.com/Ajax/jQuery.post
Add all your relevant data, and post away, handling the response with the supplied callback method.
There is a post function in jQuery:
$.post("test.php", { name: "John", time: "2pm" } );
This is copied directly from the jQuery API, so for more details and examples you can look there.
jQuery api
choose Ajax > Ajax Requests > $.post

Resources