I just finished localizing my web application using spring boot configuration as a base.
#Bean
public LocaleResolver localeResolver() {
return new CookieLocaleResolver();
}
Due to a requirement one is supposed to be able to change locale/language of the website by pressing a button. Said function is implemented with a little bit of JS and a cookie.
<script>
function updateCookie(lang) {
let name = "org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE"
document.cookie = name+"="+lang
location.reload()
}
</script>
<a onclick="updateCookie('de')" class="flag-icon flag-icon-de mr-2"></a>
The idea is to update said cookie on click of a button and use it throughout the whole application. This works fine until I am trying to call a specific endpoint in my application.
In order to debug my application I use:
window.onload = function () {
alert(document.cookie)
}
Now to my problem:
When User-Testing the application this is the alert-feedback:
org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE=de
Switching to other pages, refreshing, changing language etc. properly resets the cookie with a different value.
When calling a specific endpoint though, I get the following alert:
org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE=de;
org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE=fr
Instead of resetting/changing the existing cookie, a new one is added with the value 'de;'. A seemingly random semicolon is added.
This doesn't happen with endpoints using similar logic and almost identical implementation.
There is no further logic outside the little bit of JS code I've posted and I'm not touching the cookie in the backend.
Unfortunately I'm out of ideas. Any tips/help would be appreciated.
Related
I'm developing my project with Blazor Server-side.
While I develop, I used javascript code to implement things that hard to implement by C#.
However, I'm facing something weird situation. (I guess it is problem for javascript)
Suppose there are 2 users(A, B). When 'A' user do some action that call javascript code, if 'B' user into same page, 'A' users action affects to 'B' user.
I implemented web page that have 3d scene with threejs. As I explained above, when User 'A' move some object with mouse event(mousemove, mousedown..), if User 'B' accesses the same page, 3d objects of B are moved to the location where User 'A' moved.
Originally, when user access to web page I developed, 3d objects's position should be 0,0,0.
My Guess
I don't use prototype or class(use variable and functions globally. I'm new to javascript.. )
Javascript runs on server-side(share resources??, If then, how can I solve it)
I'm guessing the javascript would be problem, but if you have any other opinions, would you please share?
Edited
I've solved this problem using DotNetObjectReference.Create(this);
C#
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
//send created instance to javascript
var dotNetObjRef = DotNetObjectReference.Create(this);
await JSRuntime.InvokeVoidAsync("SetObjectRef", dotNetObjRef);
}
await base.OnAfterRenderAsync(firstRender);
}
[JSInvokable]
public async Task enableSomething(bool bEnable)
{
var something = bEnable;
}
//== before edit
//[JSInvokable]
//public static async Task enableSomethingStatic(bool bEnable)
//{
// var something = bEnable;
//}
Javascript
var objectRef;
function SetObjectRef(ref) {
objectRef = ref;
}
//call c# function
objectRef.invokeMethodAsync("enableSomething", true);
It was problem of 'static' method as I guessed.
If you declare C# method called from javascript as 'static' and this method changes something of UI variable, this method can affect another users.
So I create instance of current page and send it javascript and when I need to call C# methods from javascript, I call methods using created instance.
Is there any problem or issue, please share it.
Sorry for my bad English.
JavaScript runs client side only. I don't see how two windows, let alone two users, would share data.
Almost for sure, the problem is that you are injecting a singleton service-- which means the server will use one instance for all users.
If so, you have two choices:
(1) add logic to your singleton service to incorporate users. (For example, a dictionary with UserID/Property name for key, and a column for Value)
(2) go to Startup.cs and change the suspect singleton service to .AddScoped(), which will create a new instance for each user.
For right now, I think the latter solution will solve your problem immediately. However, don't underestimate the value of Singletons-- they'll be very useful for other things.
I currently have a Chat application which opens a new Chatwindow for every Chat (just like on facebook & co). To get this working so far I did some weird hacks since all of the n open chatwindows use the same $scope Variables. This is neither good programming nor does it help with bugfixing later on.
Therefore I'd like to redesign the chat part of my application and use one MessageCtrl instance for every Chatwindow. Is this possible in angular.js and if yes, how could I implement it?
If not, can you give me some guidelines on how to implement it "the angular way"?
edit: What I'm currently doing:
I create the Chatwindow from the MessageCtrl and save the necessary data into a MessageService. Since the next time a user writes a message in one of the Chatwindows I dont know if the $scope Variables are set correctly I check the MessageService again to find the correct Chat.
The problem is currently the only way of knowing what the correct chat is for me by saving the chat id in the parent <div id=<chatId> of the chatwindow. Thats far from good, but the only solution I got working so far
edit2: my code:
When a user starts a new Chat the following happens in some Ctrl:
`$rootScope.newChat = {roomId: roomId};
the MessageCtrl listens on this:
$rootScope.$watch('newChat', function (newVal, oldVal) {
startChatWindow();
// other preperation like setting $scope.roomId
}
startChatWindow() just appends the following html:
var $el = "<div id='" + $scope.roomId + "'class='bottomChat'>";
<!-- other things, like displaying the old messages -->
</div>";
$("#messageTab").append($compile($el)($scope));
PS: by chatwindow I just mean a visually appearing window, in reality it's just a styled like a window. This also means that every chatwindow uses the same messageCtrl. Which also means that I loose reference to e.g. $scope.roomId
edit3: SOLUTION
after removing the jQuery code and creating a directive every chatWindow has it's own Ctrl.
First I would like to say that I searched and found plenty of answers and even tried a couple (more than...) but to no avail! The error is probably mine but it is time to turn to SO and ask.
Problem description: I have a variable that I want to change the value through the user input (click on btn). As soon as the user chooses the btn it will navigate to a different page that will use the result of the variable to perform certain actions. My issue is that if I alert on my 1st page I get the value being passed by the btn... But on the second page I only get "undefined"
I think it has to do with variable scope and the fact that (I think it works that way anyway) even a window.var will be deleted/purged in a different window.
Anyway, the code is something like this (on the 1st page/file):
var somAlvo;
$('#omissL').click(function(){
somAlvo = 'l';
window.location.href='index_ProofOfConcept_nivel1.html';
});
And on the "receiving end" I have the following code
<head>
...
<script type="text/javascript" src="testForm_javascript.js"></script>
to "import" the js file with the variable and:
var processo = somAlvo;
alert(processo);
I tried declaring window, not using var inside the function and so on...
This is a proof of Concept for a project in my local University, where I'm working as a research assistant (so, this is not homework ;) )
Thanks for any help/hints...
You are right in that when you navigate to another page, the entire JavaScript runtime is reset and all variables lost.
To preserve a value across page loads you have two options:
Include it as part of a query string when navigating to the new page.
Set a cookie.
You may also want to look into loading the new content through an AJAX call and replacing what is displayed. This way you won't reload the entire page which won't cause the JavaScript runtime to be reset.
to help teach myself PHP I've tasked myself with updating old mysql_* code with PDO.
This has been going great, and as I've been learning I've been able to greatly reduce the amount of code. However my research has ran into a brick wall in a particular area.
Currently, we have it so projects are recorded in a list view, with a set of 'actions/options' for each project. Each of these actions links to a PHP file which runs a small amount of code then sends you back to the list view.
Here is an example:
function projectComplete(id) {
location.href = "complete.php?id=" + id;
}
<button type="button" class="projectComplete" onclick="projectComplete('<?= htmlentities($row['projectid']); ?>')"></button>
The complete.php file simply contains an SQL update query that sets a column in the record a completed state of '1'.
I originally wanted to ask the question 'what is the best practice for handling this type of interaction' however that may attract opinion based answers which I read is not allowed here.
Instead I will phrase it like this: Is there a way of having all of these 'actions' run in the same page? (ideally able to use buttons rather than forms, due to difficulty in layout styling of forms)
I know that if it used forms, I could simply name each form's submit button differently then run an if statement (the only issue would be passing the id, but I'm sure I could figure that out e.g.
if (isset($_POST['exampleAction'])) { Run the code.. }
Any links to guides/tutorials/similar questions etc would be very much appreciated. As previously stated, I'm self-learning PHP - I know very few 'best practices' and would like to learn more.
One thing you could consider is an MVC pattern, where a page call will run some function based on some parameters. A full-blown MVC framework is probably more than you need for this project, but mimicking the controller dispatching is certainly doable. Something to this effect could work (code untested):
if (isset($_GET['action'])) {
new Actions()->dispatch('action_'.$_GET['action']);
}
class Actions {
public function dispatch($action) {
if (method_exists($this, $action)) {
$this->$action($_GET);
} else {
http_response_code(400);
exit(1);
}
}
// The following functions are examples only!
public function action_Create($parameters) {
// Create database record
}
public function action_Read($parameters) {
// Read database record
}
public function action_Update($parameters) {
// Update database record
}
public function action_Delete($parameters) {
// Delete database record
}
}
Then you'd call (for example) action.php?action=Read&name=foo&author=bar
This is a MVC3 project using razor. Instead of displaying another view to inform the user that the changes have been saved successfully I would like to simply fire a JavaScript popup informing them... Everything I have found on the web either opens a whole new browser window, or misses what I am trying to accomplish all together... I know there is a simpler way to go about doing this but this is where I am... At the end of the controller function that does the save on the return I simply use redirect and send it to another controller function that displays a screen saying "Changes Have Been Saved Successfully" then the user clicks a button there which will take them back to the index page... IMO this is a bit shotty and think it can be cleaned up through the use of Javascript...I have not found any luck on this yet.. Currently the below code is what I am using:
Function SomeFunctionName()
db.SaveChanges()
Return RedirectToAction(ChangesSaved)
End Function
Function ChangesSaved()
Return View()
End Function
And the javascript that I have implemented in the ChangesSaved view.
#Code
ViewData("Title") = "ChangesSaved"
End Code
<script type="text/javascript">
alert("Changes Have Been Saved Successfully");
</script>
There are a few problems with this though...
How do I tell the javascript When the user clicks OK it should take them to another page.
I did just try the below and since I am very new to java/javascript it failed:
var r=alert("Changes Have Been Saved Successfully");
if (r == true) {
#html.Action("***********","Admin")
}
If I were you I would post your form using Jquery. Then you can set a callback. In Mvc you can return JSON data, a simple value indicating that the save worked would be enough. Then you can call your alert although you might consider using a jQuery UI dialog as it's way more flexible. If you haven't ever used jQuery I wouldn't be afraid, it's easy and there is a lot of great examples out there.
Take a look at this http://api.jquery.com/jQuery.post/ and this, ASP.NET MVC controller actions that return JSON or partial html