0

I want to send some information along with every AJAX request to server side from my JavaScript application (it could be vanilla JS, JQuery, or any SPA based framework). We are using JQuery to make AJAX calls. I do not want to use QueryString or Headers to send information to server. I want to keep this information abstract from user. I was thinking of cookie but cookie created on client side using JavaScript is not available on the server side. I also want to destroy this information once browser is closed (meaning this information is session specific).

On the server side, we are using ASP.NET WPI (C#)

What is the way to achieve this?

OpenStack
  • 3,045
  • 6
  • 23
  • 44
  • what are you using in your backend....also in the client, are you using fetch? if so, can send cookies to the server https://developers.google.com/web/updates/2015/03/introduction-to-fetch#sending_credentials_with_a_fetch_request ... if using axios, the cookies are sent to the server without additional settings ... for nodejs server you can use stuff like `cookie-parser` at your backend... – gdh Apr 29 '20 at 05:17
  • @gdh On the server side, we are using `ASP.NET WPI (C#)`. We are not using `fetch`. All the AJAX calls are made using Jquery. – OpenStack Apr 29 '20 at 05:49
  • Maybe your cookie had wrong domain associated with it? Try going through https://stackoverflow.com/questions/1458724/how-do-i-set-unset-a-cookie-with-jquery – zmii Apr 29 '20 at 09:56

1 Answers1

0

You can set a cookie using a library like js-cookie (or in plain JS using document.cookie). A cookie with no max-age or expiration date will be a session cookie and will expire when the user closes the browser tab.

All cookies are automatically sent to the backend if the api and the web app are on the same domain. If your app is for example on https://www.yourdomain.com and your api is on https://api.yourdomain.com this would be a cross-domain request, and sending cookies has to be manually enabled in jQuery, using withCredentials: true:

$.ajax({
   url: a_cross_domain_url,
   xhrFields: {
      withCredentials: true
   }
});

see the documentation for jQuery AJAX .

(the same applies for other AJAX libraries like axios)

I am no expert in C# but here a link to the docs with an example on how to retrieve the request cookies.

EmAnt
  • 36
  • 6