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

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.

Related

Web API session managment

My requirements - I have a web api whch gives me all data from db. I have a .net website which consumes this api to get all data. Now what I want is when I'm login my website I want to manage session in "API".
I know session in web api is not a good approach but still I need to do this.
I have already implemented session management in web api(taken reference from here) and its working fine if I'm sending all my request from postman(i.e. I'm setting variables in session by calling 1 method and retrieving that session variable by calling 2nd method). But when I'm doing the same from asp.net website with jQuery then I'm not getting stored session variable(what I noticed is I'm getting session id different every time-for each request).
code of saving variable in session
$.ajax({
url: 'http://localhost:63726/api/Login/Login',
type: "GET",
dataType: "JSON",
success: function (data) {
alert("success");
},
error: function (data) {
alert("error");
}
});
code of retrieving variable stored in session
$.ajax({
url: 'http://localhost:63726/api/SessionCheck/LoginName',
type: "GET",
dataType: "JSON",
success: function (data) {
alert("success");
},
error: function (data) {
alert("error");
}
});
What I need to do to achieve my goal..Your opinion will save my days...
I found my answer Session management in web api.
Please, read this Web Api Session storage before.
To retreive data from session use javascript sessionStorage (instead ajax).

jQuery Ajax Stop is not invoked (No error; 200 OK)

I have a working ASP.Net 2.0 code in my development server that uses jQuery Ajax. The result of the ajax call is used to load dropdown values.
But when this code is deployed to a new DMZ server, the result is not getting populated in dropdown – though I am getting 200 OK as response. One obvious thing is that the Type is different in the response. It is expected as application/json but coming as text/plain.
I have success call back and error callback codes. Along with this I have handlers for ajax start and stop. But none of these events are getting fired. What is the reason error/stop handlers are not getting fired? How can we make it work?
Note: The behavior is same in both IE and Chrome.
Update
Also observed that there is an error logged in console, as shown below. Is it related to the "Type"? How can we address this?
Note: Also note that the Content-Length is 0 in the response headers shown below.
Success Callback
jQuery
function loadASN()
{
var receiveScanParameter = getContainerParameters();
// console.log(receiveScanParameter);
$.ajax({
type: "POST",
url: "rcvScanTXAdd.aspx/GetASNForPlant",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ receiveScanParameter: receiveScanParameter }),
success: successPopulateASN,
error: errorFunction
});
}
Global jQuery Code
//Global Ajax Error handling Function
function errorFunction(xhr, status, error)
{
if(xhr == 'undefined' || xhr == undefined)
{
alert('xhr undefined');
}
alert(status);
alert(error);
}
$(document).ready(function ()
{
//Ajax Start
$('body').ajaxStart(function()
{
//Change cursor to waiting
$(this).css({'cursor':'wait'})
});
//Ajax End
$('body').ajaxStop(function() {
//Reset the cursor
$(this).css({'cursor':'default'})
});
});
Screenshots
I figured it out.
Step 1: Observed that there is an error logged in browser’s console (saying result is null). [This screenshot is updated in the question]
Step 2: Observed that the content length of the response is zero. Also observed that there is a gzip compression happened on the response (by reading the response headers).
Step 3: Analyzed the server's web.config. It was uisng a C# httpModule for compression. In that httpModule added bypassing logic for json. [I don’t want json to be compressed with this custom module. Later I will consider adding compression to JSON when I use IIS for compression instead of custom module]. Following is the C# code segment for by-passing JSON compression
request.ContentType.ToLower(CultureInfo.InvariantCulture).StartsWith("application/json")
WHen in doubt, read the API docs:
As of jQuery 1.8, the .ajaxStop() method should only be attached to document.
http://api.jquery.com/ajaxStop/
Same note can be found in $.ajaxStart docs

Returning json to client via webmethod

I'm trying to implement a very simple login system for a webapi backend. The site will only have one login, which is an admin, which will allow create/update/delete actions.
For this reason, I'm trying to implement a simple login with usernames and passwords coded directly into the pages in C#.
Here's how I want it to work:
On the Login.aspx page, the user enters the username and password to a form, which gets sent to the server via a webmethod:
[WebMethod]
public static something Login(string username, string password)
{
if (username == "bob" && password == "password")
{
*Send some response indicating authentication success*
}
}
This response needs to be something I can obtain from the client-side. Ideally, I'd like to be able to grab it using javascript. Is this possible using WebMethod? And I'm not sure what the method signature should be like.. I assume it would be "public static something methodName" but I'm not sure what that something would be.
Basically, If the user login is a success, I'll pass back a string such as "A(#I#ASGJAWIAW", the client will cache it in the browser, and from there, when they need to make any CREATE, UPDATE, or DELETE requests, they will also send in that value to the webapi methods. The webapi methods will determine whether the have the correct value before running the action.
Does anyone have any experience doing something like this?
If you can use jQuery, you can make a simple call to the WebMethod. Make sure your webmethod returns a String.
ajaxreq = $.ajax({
type: "POST",
url: "LoginService.asmx/Login",
data: "{'username':'" + $('#txtUser').val().trim() + "','password':'" + $('#txtPwd').val()+"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess
});
function OnSuccess(data, status) {
// Check response from server here and do your stuff here...
}
In the above code, txtUser and txtPwd are the textboxes where it picks up the up the User Name and Password supplied by the user.

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.

Ajax GET requests to an ASP.NET Page Method?

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.

Resources