Can JavaScript read HTTP Session object? - javascript

Is it possible to read the value of a dynamic variable like httpRequest.getSession("attr_name") from within a JavaScript?

(With Javascript, I assume that you mean client script in the browser.)
No, that is not possible. The contents of the Session object never leaves the server, so client script can't read Session data directly.
If you want to access it in the browser, you have to read the data out of the Session object and send it along in the response (for example in a hidden field), or provide a web service that reads data from the Session object and returns to the browser.

As I said in my comment, the only way would be some kind of Ajax call and request it from the server. I dont know what backend your using, here's how I would do it in Asp.net MVC and jQuery.
(If there are minor syntax errors, I apologize - not in front of a compiler)
public class HomeController : Controller
{
//abstract the session code away, don't let the evil javascript touch
//it directly. Ideally this would all be in a seperate logic class or something.
public string NameAttribute
{
get
{
return Session["attr_name"] as string ?? string.empty;
}
}
[HttpGet]
public string GetNameAttribute()
{
return NameAttribute;
}
public ActionResult Index()
{
return View();
}
}
<script>
$(function(){
$.get( 'home/GetNameAttribute', function( response ) {
var name = response; //don't forget error checking, ommited
});
});
</script>
Alternatively, you could always write down the values you need into hidden fields, and read them with normal javascript.

Related

Passing javascript variable to spring MVC controller with request param

Is it possible to send a javascript variable to a controller endpoint, and then have the controller return a new view?
I've tried using a requestbody and ajax to do it, which passes the variable correctly, but is unable to load a new view.
Maybe there's a way to do it with thymeleaf?
If you're using Thymeleaf then just reference the template you want to return to the user by its filename.
#Controller
public class YourController {
#GetMapping("/someUrl")
public String getTemplate(#RequestParam String templateName){
return templateName;
}
}
This would be the bare minimum that you'd need, assuming your templates are in the correct folder - by default in resources/static. If the frontend sends a GET (/someUrl?templateName=xyz) to the backend, it would return the xyz.html from your templates. If it does not find the template that was requested in the parameters then it will return a 404.
Edit: Reading through the comments I realized there might be a confusion between #RequestParam and #PathVariable. In case you want to use a path variable to define the template name, so that the frontend can call GET (/someUrl/xyz), then you can do
#Controller
public class YourController {
#GetMapping("/someUrl/{templateName}")
public String getTemplate(#PathVariable String templateName){
return templateName;
}
}
Resources for both below:
https://www.baeldung.com/spring-request-param
https://www.baeldung.com/spring-pathvariable

Passing spring java object to javascript

I want to pass a java object to javascript. I am using spring as backend. For html I just passed the object to my model and I can call them in html through the "$" parameter. But in javascript it seems that this will not work.
So my question is. How can I call a passed object (which is already a json string) in javascript?
// java side
model.addAttribute("data", jsonObject);
// javascript side
// ???
You need to use ajax and call the api in the from spring controller.
#RequestMapping(value = 'url', method = RequestMethod.methodType)
public #ResponseBody List < SomeClass > getAllData(pass parameter here) {
return someResultFromHere;
}
You should add an ajax call for that specific api endpoint and use the name of the model to extract anything with in.. As brk stated you will call it and it will get value.Then you can use that to parse the data comming from the beckend of your server this is an example of the code.
// java side
model.addAttribute("data", jsonObject);
//ajax side
$getJSON('http://<yourserverip>:<yourport>/myapi/values/', function(data){
console.log(data.<yourValue>);
});

How to get JSON file from server? (ASP.NET)

I have a simple web application that operates with a set of words using JS. In order to test the main code I just put a needed data in a variable in my script.
CONST WORDS = [
["Computer", "Ordinateur", "https://www.lifewire.com/thmb/nNDKywb8qvKzhxelVAR95sEHBj0=/768x0/filters:no_upscale():max_bytes(150000):strip_icc()/Acer-aspire-x3300-5804ec185f9b5805c2b6b9e6.jpg"],
["Function", "Fonction", "http://latex-cookbook.net/media/cookbook/examples/PNG/function-plot.png"],
["Server", "Serveur", "https://effortz.com/wp-content/uploads/dedicated-hosting-server.png"]
]
Now I need to build a database (already done) and get such data from the server. So, the question is how do I acquire JSON file from the server using JS? I know how to make GET requests, but what should I do on the server to make it response? (or may be there is an easier way to get this data in JS, considering that I already got it from DB and can easy display on the webpage).
Here is a backend code
namespace LFrench
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<Words> WordsSet = Words.GetWords("Business");//recieving from DB a set of words, that i need to use in JS
}
}
}
The thing you need to understand is the flow of your request. if you strictly want to do it in the Page_Loag event then I suppose you will have to make a method in your Javascript that will actually accept your data as parameter and then call the Javascript method from the C# CodeBehind Assuming that the data in the parameter is in JSON format. This method works but is not very efficient.
Other way is, in your JQuery side, you should make an ajax call to a WebMethod of yours in the CodeBehind that will actually send the response in JSON format. This is cleaner way of doing it.
Your JQuery should look like:
$(document).ready(function(){
$.ajax({
method: "GET", accept: "application/json; charset=utf-8;",
url: 'MyPage.aspx/GetDataFromDB', success: function(data){
console.log('Success Response in JSON: ' + data.d); // notice *data.d*, Calling from WebMethods returns the object encoded in the .d property of the object.
}, fail: function(err){
console.log(err);
}
});
});
And your CodeBehind should look like:
[WebMethod]
public static string GetDataFromDB()
{
var myData = YourDbCall(); // Some method to retrieve data from database
var body = new
{
Firstname = myData.Firstname,
Lastname = myData.Lastname,
Email = myData.Email,
// Any Other Information
};
var json = JsonConvert.SerializeObject(body);
return json;
}
EDIT
Here is how your Word Set will be sent back as JSON:
[WebMethod]
public static string GetDataFromDB()
{
List<Words> WordsSet = Words.GetWords("Business");
return JsonConvert.SerializeObject(WordsSet);
}
Make sure you have installed Newtonsoft.JSON from Nuget Package Manager Console. if not you can Open Package Manager Console and run this command:
PM> Install-Package Newtonsoft.Json
You need to make json return type method on serverside. Than call it from your get method and do your method on serverside and fill the List and return that list by converting JSON format.

Sending array from php to javascript, parsing PHP variables to JS

I want to be able to pickup variables from php example: public var $PHPVariable = "Hello World"; or something in that way. But how will I possible send this to javascript without XML HTTP(S) requests?
PHP File example
<?php
public var $secure_connection = $secure['ssl']['type']['connection']['valid_id'] // This is equal to (int)25
public var $userRank = $_SESSION['user']['active']['secure']['rank']; // Returns Admin or Default
public var $userFullName = $_SESSION['user']['unactive']['secure']['require']['name']['first'.'middle'.'last']
?>
JavaScript file / document
function get(variable, type){
if(!empty(variable) && !empty(type)){
if(!exist(variable)){ // the exist function will check if the public variable exist in the php setting file.
return 'The variable does not exist!';
}
if(type=='output'){
return recieve(variable, 'As String'); // the recieve function will collect the data from the public variable.
}
if(type=='setting'){
return recieve(variable, 'As Setting') // returning the recieve function as a setting will basicly mean it can return anything such as string/array/integer/boolean
}
}else{
return 'ERROR: Please fill in required fields!';
}
}
if(get('secure_connection', 'setting')==25){/* Returns true */}
if(get('userRank', 'setting')=='Admin'){/* Returns true */}
if(get('userFullName', 'output')){/* Returns the variable as a string no matter what the php variable was in ex int/boolean*/}
Take in mind I want to do this without XML http(s) requests!
Thanks for taking your time help! Richard.
EDIT
I know it is possible sending JSON Requests to a PHP Object class, which could solve this solution but it is not secure enough for my website, though it allows the user to even edit their own rank into other ranks or change SQL Connection properties of databases and change the row values, etc. Just with enough knowledge of using the (example) Chrome Console to use the function to change the php files content. Which will result resolving no ones problems.

In an action method, how can I bind post data to a dynamic object?

I want to do this:
public ActionResult SaveStuff(dynamic vm) {
StoreTheValue(vm.myvalue);
return Content("Saved :)");
}
This doesn't work, MVC doesn't seem to want to create a dynamic object with properties that correspond to the post data of the request.
Now I know that the whole point of properly defined view models is to create strongly typed data structures and have MVC bind data into them, but given that I'm posting data from javascript using ajax it's not strongly typed data anyway, so I don't see that I'm loosing any maintainability by doing this, and it will save me time and effort creating view model classes.
Can anyone help suggest how I can bind post data to a dynamic object, posssibly using a custom model binder?
One possible way to achieve this would be to use a custom model binder, assuming that you are posting Json to the action
public class DynamicBinder : IModelBinder
{
public object BindModel( ControllerContext controllerContext, ModelBindingContext bindingContext )
{
using( var streamReader = new StreamReader( controllerContext.HttpContext.Request.InputStream ) )
{
return JsonConvert.DeserializeObject< dynamic >( streamReader.ReadToEnd() );
}
}
}
then in your action you can tell it, to use the custom binder
public ActionResult SaveStuff([ModelBinder(typeof(DynamicBinder))]dynamic vm) {
StoreTheValue(vm.myvalue);
return Content("Saved :)");
}
then post your json as such :
{
"myvalue":{...}
}
dynamic type and ajax request that you do with javascript is not corresponding.
You always can create your strongly typed object properties on javascript side.
Anyway you can use FormCollection like this:
[HttpPost]
public ActionResult yourAction(FormCollection collection)
{
StoreTheValue(Convert.ToString(collection["myvalue"]));
return Content("Saved :)");
}
But I think it's better to think of a strongly typed way.

Categories

Resources