Is it possible to send a track/api variable to the next cmp, while using history.back() in LWC.
this.var1 = false;
var compDefinition = {
componentDef: "c:Component-to-navigate",
attributes: {
leadId: this.SomeLeadId,
SomeId: this.SomeId,
Variable-To-send: true
}
};
var encodedCompDef = btoa(JSON.stringify(compDefinition));
this[NavigationMixin.Navigate]({
type: 'standard__webPage',
attributes: {
url: '/one/one.app#' + encodedCompDef
}
});
Instead of this i want to use history.back(), and also need to pass ' Variable-To-send' with this is this even possible ? tried directly with onclick funtion, not working.
Apart from navigation any other way ? basically i dont want to reload the previous page. ? tried history.back(), windows.location = etc, but not able to pass the same..
Please help with the approach if possible thanks.
well, history.back() method loads the previous URL (page) in the history list and only works if a previous page exists.
So, we cannot set any parameter while calling the history.back().
However, we can simulate the same thing by using some temporary storage that can store the parameter value that we want to communicate to the other component between the pages.
to do so we can either make use of:
local storage
session storage
cookie
or any other storage place where we can keep the data and access :)
Example:
we can use local storage like below:
// to set the param value
localStorage.setItem('param1', 'value1');
localStorage.setItem('param2', 'value2');
// going back or any navigation
history.back();
// to get the value at any other place
const param1 = localStorage.getItem('param1');
const param2 = localStorage.getItem('param2');
// to remove the data from storage
localStorage.removeItem('param1');
localStorage.removeItem('param2');
// or
localStorage.clear();
Related
I have form with a Grid (telerik), i think the technology behind it doesnt matter. I let user click on a row in the grid. During the click I extract a value from the Grid with Javascript, like so:
function RadDrillDoubleClick(sender, eventArgs) {
var Code = eventArgs.getDataKeyValue("Status");
if (Code == "In Progress" || Code == "")
{
location.href = "Main1.aspx?mode=edit&DID=" + eventArgs.getDataKeyValue("D_ID");
}
else {
location.href = "Main1.aspx?mode=view&DID=" + eventArgs.getDataKeyValue("D_ID");
}
}
After user has clicked the grid, I call this JS function and send them to correct .aspx page with either VIEW or EDIT mode dependent directly on the Code.
What I'm trying to do is once I get to the Main1.aspx page, I want to be able to continue to hold the CODE value, because when users performs a certain action, I'll need to call a javascript function and use the actual CODE to determine what the user will be able to do.....
var Code = eventArgs.getDataKeyValue("Status");
is there any way I can somehow create like a GLOBAL Variable called
CodeValue
that I can pass around to another form without doing it in the URL?
When the browser navigates to a page, all current JavaScript is unloaded from the browser. This means any functions/variables, etc. will not be accessible on the new page unless you've persisted the value in some way.
Common ways of persisting the value include:
Add it to the query string of the URL the user is navigating to
Save the value to a cookie
Save the value to local/session storage
For your scenario, #1 is probably your best bet (keep in mind the user can have multiple browsers/tabs open to your site).
One way to get the value from URL is like this: on the page Main1.aspx, you add to your JavaScript a function that will run after page loads and that will get what it needs from the current URL
var globalValue; // variable that will receive the value from URL
window.onload = function() {
var thisURL = window.location.href;
globalValue = url.split("?").pop();
// this will store in globalValue everything that comes after the last "?"
// example: if the url is www.site.com/text?value, it will store string "value" to globalValue
};
How can I save my HTML element tag data after user closed the browser. For example
<div class="classOne" data-random="50">
And i used jQuery to change the data attribute
$(".classOne").attr("data-random","40")
And if the user close out the browser and comes back the value for data-random will be 40. How can I achieve this ?
Have you tried looking at localStorage?
LocalStorage allows you to store data within the browser. So even after the user close out the browser and comes back, you still have the value stored in your LocalStorage
Here is a sample code on how you can use local storage:
localStorage.setItem("data-random", 40);
You can set it with:
localStorage.setItem("data-random","40")
And later load it:
localStorage.getItem("data-random")
If you want to store JSON objects, you should use stringify() before saving and JSON.parse() after loading.
try localStorage.
https://developer.mozilla.org/ko/docs/Web/API/Window/localStorage
$(document).onload(function(){
if(localStorage.rendomData){
var data = localStorage.rendomData - 10
localStorage.set(randomData,data)
}
else{
localStorage.set(randomData,50)
}
})
I hope this helps.
The easiest way to achive it is to use cookies. Just take this plugin: https://github.com/carhartl/jquery-cookie and then above the line:
$(".classOne").attr("data-random","40")
add:
var randValue;
if (typeof $.cookie('my-rand-value') == undefined) {
// generate random value
randValue = generateRandomValue //assign random value to variable
$.cookie('my-rand-value', randValue)
}
else {
randValue = $.cookie('my-rand-value')
}
at the end change static value to your variable:
$(".classOne").attr("data-random",randValue)
You can do that by using cookies as well as by using local storage -
for local storage first store first try to get value if it is stored like -
if(localStorage.getItem("data-random") != null){
return localStorage.getItem("data-random");
} else {
return 50;
}
and when user changes the value you can save that value by -
localStorage.setItem("data-random", value);
Use Jquery function beforeunload and save it into localStorage.
$(window).on('beforeunload', function() {
// Put the object into storage
localStorage.setItem('data', $(".classOne").attr("data-random"));
});
To Retrieve the data from storage whenever your page opens.
var retrievedData = localStorage.getItem('data');
I've built an app that is form-based. I want to enable users to partially fill out a form, and then come back to it at a later date if they can't finish it at the present. I've used iron router to create a unique URL for each form instance, so they can come back to the link. My problem is that Meteor doesn't automatically save the values in the inputs, and the form comes up blank when it is revisited/refreshes. I tried the below solution to store the data in a temporary document in a separate Mongo collection called "NewScreen", and then reference that document every time the template is (re)rendered to auto fill the form. However, I keep getting an error that the element I'm trying to reference is "undefined". The weird thing is that sometimes it works, sometimes it doesn't. I've tried setting a recursive setTimeout function, but on the times it fails, that doesn't work either. Any insight would be greatly appreciated. Or, if I'm going about this all wrong, feel free to suggest a different approach:
Screens = new Meteor.Collection('screens') //where data will ultimately be stored
Forms = new Meteor.Collection('forms') //Meteor pulls form questions from here
NewScreen = new Meteor.Collection('newscreen') //temporary storage collection
Roles = new Meteor.Collection('roles'); //displays list of metadata about screens in a dashboard
//dynamic routing for unique instance of blank form
Router.route('/forms/:_id', {
name: 'BlankForm',
data: function(){
return NewScreen.findOne({_id: this.params._id});
}
});
//onRendered function to pull data from NewScreen collection (this is where I get the error)
Template.BlankForm.onRendered(function(){
var new_screen = NewScreen.findOne({_id: window.location.href.split('/')[window.location.href.split('/').length-1]})
function do_work(){
if(typeof new_screen === 'undefined'){
console.log('waiting...');
Meteor.setTimeout(do_work, 100);
}else{
$('input')[0].value = new_screen.first;
for(i=0;i<new_screen.answers.length;i++){
$('textarea')[i].value = new_screen.answers[i];
}
}
}
do_work();
});
//onChange event that updates the NewScreen document when user updates value of input in the form
'change [id="on-change"]': function(e, tmpl){
var screen_data = [];
var name = $('input')[0].value;
for(i=0; i<$('textarea').length;i++){
screen_data.push($('textarea')[i].value);
}
Session.set("updateNewScreen", this._id);
NewScreen.update(
Session.get("updateNewScreen"),
{$set:
{
answers: screen_data,
first: name
}
});
console.log(screen_data);
}
If you get undefined that could mean findOne() did not find the newscreen with the Id that was passed in from the url. To investigate this, add an extra line like console.log(window.location.href.split('/')[window.location.href.split('/').length-1], JSON.stringify(new_screen));
This will give you both the Id from the url and the new_screen that was found.
I would recommend using Router.current().location.get().path instead of window.location.href since you use IR.
And if you're looking for two way binding in the client, have a look at Viewmodel for Meteor.
I am trying to implement a navigation to my ajax controlled site, and I am encountering some strange errors.
I am using History JS, the HTML5 only version.
This is how I initialize it:
function initializeHistory() {
var History = window.History;
if ( !History.enabled ) {
console.log("Not enabled!");
return false;
}
// Changing the main page state to -1.
History.replaceState({id:-1}, baseTitle, baseUrl);
// Bind to StateChange Event
History.Adapter.bind(window,'statechange',function(){
var State = History.getState();
console.log(History.savedStates);
if (historyData.manualStateChange)
{
if (State.data.id=='-1') alert('History start');
historyData.allowHistoryPushPop=false;
var gotoState=historyData.data[State.data.id];
var currentState=historyData.currentNavigation;
/* Some code here to revert to the previous state */
historyData.allowHistoryPushPop=true;
}
History.log(State.data, State.title, State.url);
});
};
I am using a global object, named historyData, in which I store the following things:
var historyData={
data: new Array(), //an array which contains objects that refer to the data that needs to be shown, when back or forward button is pushed
manualStateChange: true, //using this to figure out if the back or forward button was pressed in the browser, or if I am adding or removing a state from History programmatically
allowHistoryPushPop: true, //using this to prevent history from being changed in certain situations
currentNavigation: {
page: 'dashboard',
pageid: null,
module: null,
moduleid: null
}, // stores the current object from the historyData.data array
status: true // boolean that enables or disables History on my page
}
Whenever I click on a link in my page, a function, called navigation fires, which changes the History's state, and eventually runs a chain of functions to display the page which was asked for by the user. The relevant parts from the navigation function are as follows:
function navigation(gotofunc, navData) {
if ((historyData.allowHistoryPushPop) && (historyData.status))
{
if (navData['urlData']==null) // if this is null, then the title and the url for the asked page, will be returned by the server, after an ajax call, so we set it to the current url and current title
{
var curState=History.getState();
urlData={
title: curState.title,
url: curState.url
};
} else {
urlData=navData['urlData'];
if (!urlData['title']) urlData['title']=curState.title;
if (!urlData['url']) urlData['url']=curState.url;
}
navData['parameters']=new Array();
if (arguments.length>2) for (i=2;i<arguments.length ;i++) navData['parameters'].push(arguments[i]);
historyData.manualStateChange=false; // we are making a programmatic change, so we don't want the binded 'statechange' to fire
historyData.data.push(navData); // store the history data in our own array
History.pushState({id:historyData.data.length-1}, urlData['title'], urlData['url']); // push the History state, and set it's id to point to our newly added array element
historyData.manualStateChange=true; // re-enable the manual state change
}
}
If I don't know up front what the URL will be after I fetch the data via ajax, my Ajax call, replaces the current state with the correct data, this way:
if ((dataArray['navDat']) && (historyData.status))
{
historyData.manualStateChange=false;
var State = History.getState();
History.replaceState(State.data, dataArray['navDat']['title'], dataArray['navDat']['url']);
historyData.manualStateChange=true;
}
This works fine for the most part. If I navigate forward a few pages, and then go backwards, everything works greatly, if I then go forward once again(all by using the browsers back and forward button), it works greatly. There is only one exception: if I load the page, load a subpage, then try to click on the back button, this line never fires:
if (State.data.id=='-1') alert('History start');
It basicaly won't figure out that I arrived back at the front page, when I only navigate one page forward.
The other strange thing is the following(perhaps this is what's causing my original problem also): I tried fetching the savedStates of the History object, to see what is going on, and strangely, when I use the replaceState event, it adds a new state in savedStates. One of the objects that is added, is with the correct data id, the other one is with the previous data id.
What could be causing the problem, is there an error in my script somewhere? Or is this completly normal? (the part of adding multiple objects to History.savedStates after replaceState)
Thanks for the help in advance!
If I replace the url, or the title of the page with the first replaceState, the program realizes when I return to the front page, I dunno why, but till then this is the best solution I can figure.
I have a database and 2 drop down menus, using javascript I obtain the value from the selected drop down, and then send it to my PHP, the PHP then brings back information from the database and displays it in a table, there are two tables as there are 2 drop downs. Here is my javascript:
function choice1()
{
var x = document.getElementById("select1");
a = x.options[x.selectedIndex].value;
window.location.href = "index.php?a=" + a + "&b=" + b;
}
function choice2()
{
var y = document.getElementById("select2");
b = (y.options[y.selectedIndex].value);
window.location.href = "index.php?a=" + a + "&b=" + b;
}
what happens is it waits for both drop downs to change before changing both of the tables, what I would like it to do is change the table as soon as one changes but keep the other one the same. This I think means the javascript variable a or b needs to be stored so that when the page changes it can be called upon so that the PHP gives the same information for the second table.
You can persist data in many ways:
Examples are:
cookies: Javascript getCookie functions and
https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
localStorage, get variables, hidden input.
I recommend using the localStorage for this case (html5), because it's pretty safe and easy to use.
// getter function of 'persistent' variables.
function getPersistent(myVar) {
// ensure the localStorage object exists.
// return the variable we are looking for if it does or: undefined.
return (window.localStorage)? localStorage.getItem(myVar) : undefined;
}
// setter function of 'persistent' variables.
function setPersistent(myVar, value) {
// ensure the localStorage object exists.
if (window.localStorage) {
// set the variable.
localStorage.setItem(myVar, value);
}
}
// first run (page refresh) returns undefined.
// second run returns 4.
console.log(getPersistent('test'));
// we set the localStorage var 'test' to '4'.
// note that localStorage only saves strings.
// so you need to parse/convert the data if you want to modify.
console.log(setPersistent('test', '4'));
// returns localStorage var 'test' ==> 4.
console.log(getPersistent('test'));
fiddle: http://jsfiddle.net/kychan/2WJX4/
The simplest way to persist values across pages is to use the session storage API. It's much like local storage, but is torn down when the current window / session closes.
Of course, you could always just opt for updating your page by AJAX rather than reloading the document entire,