Ajax GET requests to an ASP.NET Page Method? - asp.net

A situation I ran across this week: we have a jQuery Ajax call that goes back to the server to get data
$.ajax(
{
type: "POST",
contentType: "application/json; charset=utf-8",
url: fullMethodPath,
data: data,
dataType: "json",
success: function(response) {
successCallback(response);
},
error: errorCallback,
complete: completeCallback
});
fullMethodPath is a link to a static method on a page (let's say /MyPage.aspx/MyMethod).
public partial class MyPage : Page
{
// snip
[WebMethod]
public static AjaxData MyMethod(string param1, int param2)
{
// return some data here
}
}
This works, no problem.
A colleague had attempted to replace this call with one where type was "GET". It broke, I had to fix it. Eventually, I went back to POST because we needed the fix quick, but it has been bugging me because semantically a GET is more "correct" in this case.
As I understand it, jQuery translates an object in data to a Query String: /MyPage.aspx/MyMethod?param1=value1&param2=value2 but all I could get back was the content of the page MyPage.aspx.
Is that just a "feature" of Page methods, or is there a way of making a GET request work?

For security reasons, ASP.Net AJAX page methods only support POST requests.

It is true that ASP.NET AJAX page methods only support POST requests for security reasons but you can override this behavior by decorating your WebMethod with this these both attribute:
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
I felt that the accepted answer was incomplete without pointing out a work around.

Related

How do I do an AJAX post to a url within a class library but not the same IIS Web Application?

I have been working with ajax and there has been no problems below is how my ajax post code look like:
$.ajax({
type: "POST",
url: '<%=ResolveUrl("TodoService.asmx/CreateNewToDo")%>',
data: jsonData,
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function () {
//if (msg.d) {
$('#ContentPlaceHolder1_useridHiddenField').val("");
$('#ContentPlaceHolder1_titleTextBox').val("");
$('#ContentPlaceHolder1_destTextBox').val("");
$('#ContentPlaceHolder1_duedateTextBox').val("");
alert('Your todo has been saved');
// }
},
error: function (msg) {
alert('There was an error processing your request');
}
});
However, the problem came up when I try to get the url to a webservice that is located in a class library within the same solution.
This ASP.Net
says If you want to put the webservice in the classlibrary, you could try placing the Webservice.asmx.cs file in the class library and place the Webservice.asmx file in the web application project, and then using jquery to consume it in the .aspx page
If it's a different application than yours that's considered an XSS (Cross-site scripting) and it is not allowed.
You could however wrap the call to the external service in your own application (let's say in a REST service) and just call your service from jquery

ASP.NET webservice responds with Internal Server Error (500) to post and get requests

The webservice code is simple:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void receiveOrder(string json) {
Context.Response.Write("ok");
}
And the jquery calling the webservice is as follows:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: 'http://localhost:50730/GingerWeb.asmx/receiveOrder',
data: 'test', //JSON.stringify(webOrder),
dataType: "text",
success: function(data){
if(data === "ok")
orderPlaced();
}
});
And yet the chrome console reads in provocative red:
500 (Internal Server Error)
The problem is that ASMX web-service need to find all input parameters in the request. If at least one input parameter will be not found in the request to the server the web service failed with the status code 500 (Internal Server Error).
The reason is that you send the data in the wrong way. The name of the input parameter of the web method is json (see void receiveOrder(string json)). So the data option of the $.ajax should be in the form
data: JSON.stringify({json: webOrder})
if you use type: "POST" instead of data: JSON.stringify(webOrder) which you tried before. In the case in the body of the POST request will be json=theVlue instead of just theValue.
If you would use type: "GET" the format of data parameter should be changed to
data: {json: JSON.stringify(webOrder)}
The value of the dataType should be 'json'. After the changes the $.ajax should work.
Moreover I would recommend you to use relative paths in the url option. I mean to use '/GingerWeb.asmx/receiveOrder' instead of 'http://localhost:50730/GingerWeb.asmx/receiveOrder'. It will save you from same origin policy errors.
Hello Oleg: Your explanation is simple and to the point. I had a similar problem which your explanation solved. I am providing code snippet to help 'searchers' understand what I was facing and how the above helped solve. In short I am issuing a simple jquery (.ajax) from a aspx page. I have created a webservice that gets some data from backend (cache/db) and return's the same in json format.
JS CODE:
var parameters = "{'pageName':'" + sPage + "'}"
var request = $.ajax({
type: "POST",
url: "/NotificationWebService.asmx/GetNotification",
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json"
});
ASP.NET Code Behind for Web Service
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetNotification(string pageName)
{
JavaScriptSerializer js = new JavaScriptSerializer();
Notification ns = NotificationCache.GetActiveNotificationForPage(pageName);
if (ns != null)
{
NotificationJSData nJSData = new NotificationJSData();
nJSData.Code = ns.Code;
nJSData.displayFreq = (short)ns.DisplayFreq;
nJSData.expiryDate = ns.ToDateStr;
return js.Serialize(nJSData);
}
return null;
}
It is ABSOLUTELY necessary to ensure that you match 'pageName' variable name specified in web service code with what is sent in your data parameter of the ajax request. I had them different and changed it to be the same, after spending hours, I finally found the right solution, thanks to this post. Also, in my case I am only passing a single "name:value" pair so I didn't even have to use some json De-serialization function to get the value, pageName above gives me only the value.

JSON Web service with ASP.NET - from a frustrated php guy

I've been a PHP developer for a few years now and have developed at least a dozen APIs using JSON. Create a url that does a task, and return json_encode($array)... Piece of cake...right?
Now, I used to be a .net developer a while back (about 8 yrs ago) and I've been given the task to develop a small api/webservice for a client. I've been doing some reading on WCF and have been tinkering with it for a few hours now. My question is.. Is it me or is it incredibly over complicated to just run a RESTFUL query and return a block of JSON? In other words, why can't I just create an ASPX page that takes an array and encodes it as JSON and spits it out? Does it really HAVE to be WCF? Or even ASMX for that matter? Feels like overkill? No? Can someone offer a valid reson on why I need to go through the pain of WCF if I'm making a simple service that returns a few lines of JSON?
You can use WebMethods:
Using jQuery to directly call ASP.NET AJAX page methods
Code-behind:
public partial class _Default : Page
{
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
}
Script:
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// alert(msg.d);
}
});

Persisting Session State via multiple request using jQuery $.ajax()

just been trying to recieve the session value from multiple jquery ajax requests on the same domain name. i think i understand that each request is kind of a virtual browser request so the session is mutally exclusive to each request, but there must be a way some how, has anyone solved this. Basically this is what im trying to do:
I have tries using type: GET and POST but still no luck.
Can anyone help please, Thanks?
First request - Stores the product id in a session
$.ajax({
url: 'http://localhost/websitetest/test.aspx?storeproduct=' + productid,
type: 'GET',
async: true,
success: function(data) {
}
});
Second Request - From the callback variable "data" recieves the product id from the session
$.ajax({
url: 'http://localhost/websitetest/test.aspx,
type: 'GET',
async: true,
success: function(data) {
var productID = data;
}
});
There is no question to send ajax request while accessing Session variable from asp page.
Simply you can do is :
<%
String session_var = Session("name_of_session_variable");
%>
Even if you still want to try Ajax, I think you will need to print the session variable in test.aspx file using Response.Write(), which will automatically return the content.
Please check this for further reference.
Please correct me as well if I am wrong.
Thank you.

Access Session data from ASP.NET page using jquery

I'm trying to pass a variable stored in the Session object of my ASP.NET page with jQuery, representing the progress of a process running on the server as a percentage.
i.e:
Session['progress'] = 37;
I've looked through some of the answers here; my code uses the same method as a question aswered correctly here:
<head>
...
<script type="text/javascript">
function updateProgress() {
var progress = '<%Session["progress"].ToString();%>';
}
</script>
...
</head>
The ASP.NET compiler is returning a NullPointerException. I'm unsure if this is because the Session object hasn't been instantiated yet (as this is occurring at compile time); or perhaps the Session object isn't receiving the variable properly (if this is the case, how can I go about checking this out?)
Any ideas?
I need to find some way off passing this value from the server to the client so a jQuery progress bar may be updated for the user.
Thanks!
If you want to get a real-time changing number from a session variable in your page using jQuery, you'll need to make some type of ajax request. To access a value in the session state, you can write a function [WebMethod] to send gets/send the data back to your jQuery request.
jQuery Request :
jQuery.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{}',
dataType: 'json',
url: 'Default .aspx/TestMethod',
success: function(result){
alert(result.d);
}
});
Server Page WebMethod :
using System;
using System.Web.Services;
namespace JqueryAjaxText
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string TestMethod()
{
return Session["progress"].ToString();
}
}
}
I think you are misunderstanding the order in which things occur. While SageNS found your error, he did not solve your problem.
The code you have simply writes a number to the javascript code, and the user sees:
<head>
...
<script type="text/javascript">
function updateProgress() {
var progress = '37';
}
</script>
...
</head>
Successive calls to updateProgress() will always return 37.
You need to use jQuery's .ajax() function to make an asynchronous call to the server if you want to periodically update the server's progress.
You can build off Zachary's answer and take it a step further by creating a WCF service and switching your $.ajax() call to be a GET instead of a POST. It won't be as large of a request (not that the POST was that big), but you'll also be using the proper HTTP verb. (POST is used to insert; GET should be used to retrieve data).
Your jQuery call could look like this:
jQuery.ajax({
type: 'GET',
dataType: 'json',
url: 'MyService.svc/GetServerProgress',
success: function(result){
alert(result.d);
});
You would then create a WCF Service and create a service method named GetServerProgress.
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetServerProgress")]
public int GetServerProgress()
{
return 37;
}
Lastly, you'll probably want the client to have some JavaScript that calls setTimeout() to your $.ajax() method to that you periodically retrieve the server's progress from the WCF service.
Good luck!!
Use
<%=Session["progress"].ToString()%>
to output data to html page

Resources