Pass Variables in Url in Framework7 Inside Pages - javascript

I am new to Framework7.io. I have got the following script which fetches the data from sqlite based on the parameters passed in the url.
However all the Js is called in index.html (the first page of F7), whereas I have get parameters in the inside pages.
code in b.html
<a href="a.html?type=new&ok=fine" >Go to a with values of ok & type</a>
code in a.html
function getParameterValue(type) {
type = type.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + type + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var type1 = getParameterValue('type');
Update:
Currently using this code with no successs.
$$(document).on('page:init', function (e) {
var page = e.detail.page;
myApp.alert(page);
if (page.name === 'a') {
var count = page.query.count;
myApp.alert(count);
// Now we can generate some dummy list
var listHTML = '<ul>';
for (var i = 0; i < count; i++) {
listHTML += '<li>' + i + '</li>';
}
listHTML += '</ul>';
// And insert generated list to page content
$$(page.container).find('.page-content').append(listHTML);
}
// Code for Services page
if (page.name === 'inch') {
myApp.alert('Here comes our inch!');
}
});
Thanks for your time and any help is highly appreciable.

Use page.query.your_url_parameter to get the parameter value.
Example:
To get <a href="a.html?type=new&ok=fine" >Go to a with values of ok & type</a> parameter :
$$(document).on('page:init', function (e) {
var page = e.detail.page;
if (page.name === 'a') {
var type = page.query.type; // returning "new"
var ok = page.query.ok; // returning "fine"
alert(type);
alert(ok);
}
// Code for Services page
if (page.name === 'inch') {
myApp.alert('Here comes our inch!');
}
});
Please see the documentation

Related

How to append event listener script to dynamically created element formed from server side event data

I've looked through various similar questions but honestly I don't understand any of the answers (such as they are) in order to apply any of them to what I've written. I'd really appreciate some help as I'm extremely new to this and I'm very lost!
I'm attempting to update an existing page used by moderators for clearing created data as it comes in from users. It uses server side events to check for new items, the old version uses regular forms but the page takes too long to refresh after submitting data. I'm trying to use to set the form data in the background without the need for a refresh but I'm struggling to get the event listeners to attach to the visual elements. They are created dynamically from the event source data. Visually the output looks how I want it to, but it's not behaving as it needs to. One response to a similar-ish question said don't trust the console log, it could be working, but it definitely isn't, the process on the receiving end is a copy of the existing form handler for the old page, so I know that works.
I'm unsure if it's a syntax error or if I need a different approach, the errors I'm getting look like this - it can't find the element I want it to attach the script to:
Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
at :1:37
at EventSource.source.onmessage (MOD.php:39)
This is what I've written on the receiving page:
window.onload = function() {
var last = "";
var lastqueue = "";
var source = new EventSource("MOD-data.php");
source.onmessage = function(event) {
var mydata = event.data;
var data = mydata.split('&&');
var upddate = (data[0]);
var queuedata = (data[1]);
if (mydata != last) {
last = mydata;
if (queuedata != lastqueue) {
var Qdata = queuedata.split('||');
for (let i = 0; i < Qdata.length; i++) {
var itmdata = Qdata[i].split('.');
var itmID = "Q" +(itmdata[0]);
var exists = document.getElementById(itmID);
if (exists === null) {
var itmclass = (itmdata[1]);
var itmbg = (itmdata[2]);
var itmwho = (itmdata[3]);
var itmimg = (itmdata[4]);
var rewbox = "<div id=\"" + itmID + "\" class=\"Qitm " + itmclass + "\" style=\"background:#" + itmbg + "\">" + itmwho + "<input type=\"image\" class=\"rew\" name=\"submit\" src=\"/web/rewards/" + itmimg + ".png\"></div>";
document.getElementById("Qcon").innerHTML += "" + rewbox + "";
var newScript = document.createElement("script");
var inlineScript = document.createTextNode("document.getElementById(" + itmID + ").addEventListener(\"click\", Qclear, true);function Qclear() {\$.ajax({type: \"POST\",url: \"MOD-queue-clear.php\", data: \"timestamp=" + itmID + "\"})}");
newScript.append(inlineScript);
document.getElementById(itmID).appendChild(newScript);
};
};
lastqueue = queuedata;
};
document.getElementById("debug").innerHTML = "<!--" + queuedata + "-->";
};
};
};

Storing items as cookies, works perfectly fine on a normal browser, but on a native device browser there are implications

I am creating a website for a client at the moment, we decided an easy way to store "items" which will be passed down to a subdomain from the root would be to store them as cookies. This works perfectly fine in a normal browser, yet when I tested it on a native device browser it didn't work as smoothly. I am wondering where some of these problems may have been coming from and hoping you wonderful developers can lend a man a hand.
The idea is that on the frontend when a "Your Order" side drawer is pressed, a function runs grabbing the cookies and then sorts them into their specified content area's -> Downloadable Content, Requested Material and Bespoke Content. I have created two separate functions for this, one that was the original working piece and another more tailored and "good practice".
Tried having the "Value" of the cookie containing the values that need to be stored such as, [itemname],[itemlocation], [itemdescription], [itemtype].
The second function stores the item data in an object, the object is then JSON.stringified and iterated over in a for loop. This is then taken out of a string with JSON.parse() and further iterated over in an .each() iterating over the index(key) and val(value).
FIRST FUNCTION:
$('section#review-downloads a.toggle-btn').bind('click tap', function() {
let cookies;
let itemSplit;
var section = $('section#review-downloads');
if(section.hasClass('active')) {
section.removeClass('active');
setTimeout(function() {
$('section#review-downloads .selected-items div').find('p').remove();
}, 900);
} else {
section.addClass('active');
$.each(document.cookie.split(';'), function() {
cookies = this.split('=');
let trimId = cookies[0].trim();
vals = cookies[1].replace(/[\])}[{(]/g, '');
if(!(cookies[0] === "envFilter")) {
$.each(vals.split('[ ]'),function() {
itemSplit = this.split(',');
let itemId = trimId;
let itemName = itemSplit[0];
let itemUrl = itemSplit[1];
let itemType = itemSplit[2];
let itemDesc = itemSplit[3];
if(itemType === ' Downloadable Content ') {
$('<p id="selected-item-'+itemId+'"><strong>'+itemName+'</strong>'+itemDesc+'</p>').appendTo('section#review-downloads .review-container .selected-items .downloadable-content');
} else if (itemType === ' Requested Materials ') {
$('<p id="selected-item"><strong>'+itemName+'</strong>'+itemDesc+'</p>').appendTo('section#review-downloads .review-container .selected-items .requested-material');
} else if (itemType === ' Bespoke Content ') {
$('<p id="selected-item"><strong>'+itemName+'</strong>'+itemDesc+'</p>').appendTo('section#review-downloads .review-container .selected-items .bespoke-content');
}
});
};
});
}
return false;
});
THE SECOND FUNCTION (best practice)
$('div.support-item-wrapper div.order-add').bind('click tap', function() {
let id = $(this).data('id');
let name = $(this).data('title');
let file = $(this).data('file');
let type = $(this).data('type');
let desc = $(this).data('description').replace(/(\r\n|\n|\r)/gm, "");
let url = $(this).data('url');
let cookieVal = {
name: name,
file: file,
type: type,
desc: desc,
url: url
};
let string = JSON.stringify(cookieVal);
setCookie('product-'+id, string, 1);
});
$('section#review-downloads a.toggle-btn').bind('click tap', function() {
var section = $('section#review-downloads');
if(section.hasClass('active')) {
section.removeClass('active');
} else {
section.addClass('active');
let decoded_user_product;
cookie_values = document.cookie.split(';');
for(i = 0; i < cookie_values.length; i++) {
cookie_split = cookie_values[i].split("=");
cookie_key = cookie_split[0].trim();
cookie_value = cookie_split[1].trim();
// console.log(cookie_value);
if(cookie_key != "envFilter") {
decoded_user_product = JSON.parse(cookie_value);
}
$.each(decoded_user_product, function(index, val) {
// console.log("index:" + index + "& val:" + val);
if(index === "name") {
console.log(val);
} else if (index === "type") {
console.log(val);
} else if (index === "desc") {
console.log(val);
}
});
}
// console.log(decoded_user_product);
};
});
On Desktop, the results are perfectly fine. Each item is easily console.log()'able and has been easily sorted in the FIRST FUNCTION.
On Mobile, the same results were as to be expected. But after realising it hadn't worked I used chrome://inspect along with a lot of console.logs to come to the conclusion that I may be too inexperienced to understand what parts of my code are unable to run on a native browser.

JSON string not loading data into local storage

I am building an application that will load bus schedules into local storage, then based on a search term provides the stops on the bus schedule. It works by clicking the load button and sending the information to local storage. Then you search a route name, and the stops information will be displayed into results. When I run in a browser my data is not loading into local storage when I press load.
<html>
<head>
<script type="text/javascript">
/**
* A JSON string that holds data. There is no problem with the JSON string
* #type {String}
*/
var busSchd = '{"Routes": [{"routeName": "Milledge","stops":[{"Stop 1":"Main Library","Stop 2":"Clarke Central","Stop 3":"Five Points South","Stop 4":"Five Points North","Stop 5":"Waddell"}]},{"routeName": "Orbit","stops":[{"Stop 1":"Main Library","Stop 2":"Clarke Central","Stop 3":"Five Points South","Stop 4":"Five Points North","Stop 5":"Waddell"}]},{"routeName": "East West","stops":[{"Stop 1":"East Campus Deck","Stop 2":"Creswell Hall","Stop 3":"Hull St Deck","Stop 4":"Main Library","Stop 5":"Joe Frank Harris"}]}]}';
const load = () => {
let data = JSON.parse(busSchd);
console.log("a");
for (var i = 0; i < data.Routes.len;)
{
let route = data.Routes[i];
let routeStr = route.routeName;
localStorage.set(routeStr, JSON.stringify(route.stops));
}
};
const clicked = () => {
var search = document.getElementById("search");
var results = localStorage.getItem("search");
if (results === null) {
document.getElementById("result").innerHTML = "<b>There are no results for that route name.</b>";
} else {
var stops = results;
var output = '';
for (var key in stops[0]) {
output = output + '<b>' + key + '</b> : ' + stops[0][key] + '<br>';
}
document.getElementById("result").innerHTML = output;
}
};
</script>
</head>
<body>
<input type="button" value="Load Route Data" id="load" onclick="load();">
<br>
<br>
<input type="text" id="search"><input type="button" value="Find Route" id="submit" onclick="clicked();"><br>
<br><br>
<div id="result">
</div>
</body>
</html>
There were a few mistakes within your code which prevented you from saving to localStorage. Here are some pointers.
Use localStorage.setItem() to save and localStorage.getItem() to retrieve data.
There's no need for creating a localStorage item for each bus route. LocalStorage can handle quite some data, depending on the browser and user browser settings. See What is the max size of localStorage values? for more info.
I'd simplify your data structure. Why put stops data into an array and then into an object? I've simplified this in my example.
When iterating over items use for (var i = 0; i < data.Routes.length; i++) { // your code here } another alternative is to user .map when iterating over items within an array.
Here's how to load data and save it to localStorage and into the app.
let BusSchdDataFromLocalStorage = [];
const load = () => {
// access localStorage and save the result in data
let data = JSON.parse(localStorage.getItem('routesInfo'));
if (data === null) {
// if no data is present, save InitialBusScheduleData to localStorage
localStorage.setItem('routesInfo', JSON.stringify(InitialBusScheduleData));
}
// Now that data is present in localStorage, read it.
data = JSON.parse(localStorage.getItem('routesInfo'));
if (data.Routes.length > 0) {
// if routes are present, save its data to a global var in our app
BusSchdDataFromLocalStorage = data;
statusEl.innerHTML = 'localStorage data present'
} else {
statusEl.innerHTML = 'localStorage data absent'
}
};
Here's how the search part works.
const search = () => {
const searchString = document.querySelector('#search').value;
// data from localStorage is present in the variable below
const routes = BusSchdDataFromLocalStorage.Routes;
// Filter route data based on the search input.
const busStopInfo = routes.reduce((stops, route) => {
return (route.routeName.toLowerCase() === searchString.toLowerCase()) ? route.stops : stops;
}, []);
const stops = Object.keys(busStopInfo);
// map over the stops and return the html structure with the stop number and the value
const results = stops
.map((stop) => '<div>' + stop + ' - ' + busStopInfo[stop] + '</div>')
.join('');
// add the html result to the result div.
resultEl.innerHTML = results.length > 0 ? results : 'No route found with that name.';
};
If you'd like to see the code in action. Here's a JSFiddle.

Storing arrays in localStorage error

I have a bug in my code that only saves the last object in an array upon reload. I have a feeling that my addAccount() function is not saving or inserting data correctly. Everything else works correctly. In my console, it shows that the data is being inserted into the array, but when I refresh I only get the last object saved.
I'm not sure what to do.
// The list of accounts array.
var accountsArray = [];
function addAccount() {
// Take fields and put user data into varables.
var accountName = document.getElementById('accountName').value;
var accountBalance = document.getElementById('accountBalance').value;
var accountType = document.getElementById("accountType");
var accountTypeSelected = accountType.options[accountType.selectedIndex].text;
var accountCurrency = document.getElementById("accountCurrency");
var accountCurrencySelected = accountCurrency.options[accountCurrency.selectedIndex].text;
var temporaryObject = {
'accountName': accountName,
'accountBalance': accountBalance,
'accountTypeSelected': accountTypeSelected,
'accountCurrencySelected': accountCurrencySelected
};
accountsArray.push(temporaryObject);
console.log(accountsArray);
saveAccountData();
showAccountsArray();
}
function saveAccountData() {
localStorage.setItem('accountsArray', JSON.stringify(accountsArray));
}
function showAccountsArray() {
//var accountsLocalStorage = JSON.parse(localStorage['accountsArray']);
if (localStorage.getItem("accountsArray") === null) {
document.getElementById("getStarted").style.visibility="visible";
document.getElementById("balanceToolbarName").style.visibility="hidden";
document.getElementById("accountsMainList").style.visibility="hidden";
} else {
var accountsLocalStorage = JSON.parse(localStorage['accountsArray']);
console.log(accountsLocalStorage);
var accountInfo = '';
var i = 0;
while (i < accountsLocalStorage.length) {
accountInfo += '<li class="swipeout"><div class="swipeout-content item-content"><div class="item-inner"><div class="item-title">' + accountsLocalStorage[i].accountName + '</div><div class="item-after">$' + accountsLocalStorage[i].accountBalance + '</div></div></div><div class="swipeout-actions-left"><a href="#" class="action1">Clear</div><div class="swipeout-actions-right">Delete</div></a></li>';
document.getElementById("accountsList").innerHTML = accountInfo;
i++;
}
document.getElementById("getStarted").style.visibility="hidden";
document.getElementById("balanceToolbarName").style.visibility="visible";
document.getElementById("accountsMainList").style.visibility="visible";
}
}
*
all of your functions work correctly as tested by the link you've provided. When the page loads it successfully retrieves the data (if any) from the local storage and displays on the page. However, the global array variable accountsArray is populated with data retrieved from the local storage.
You need to repopulate the global array otherwise when you call saveAccountData it will save whatever the array holds which indeed overrides whatever you had in the local storage. To fix it, simply add add this code block...
$(function(){
var data = localStorage.getItem("accountsArray");
if(data != null)
accountsArray = JSON.parse(localStorage.getItem("accountsArray"));
});

How to define this variable below?

I have a Cancel button which appears when the user is uploading a file. If the user wishes to cancel a file upload then they can by clicking on the Cancel Button and it would display the cancel message to user.
The only problem when attempting this is that it is stating that cancel_image_file_name is undefined in the stopImageUpload function where I want to display the message. But I did define this in the startImageUpload function. So my question is that how can I grab cancel_image_file_name from the startImageUpload function and define it in the stopImageUpload function?
Below is the code showing the 2 functions:
startImageUpload function:
var cancelimagecounter = 0;
function startImageUpload(imageuploadform, imagefilename){
cancelimagecounter++;
var _cancelimagecounter = cancelimagecounter;
$('.imageCancel').on("click", function(event) {
var cancel_image_file_name = $(this).attr('cancel_image_file_name');
return stopImageUpload(2, cancel_image_file_name);
});
return true;
}
stopImageUpload function:
var imagecounter = 0;
function stopImageUpload(success, imagefilename){
var result = '';
imagecounter++;
if (success == 1){
result = '<span class="imagemsg'+imagecounter+'">The file was uploaded successfully!</span><br/><br/>';
$('.listImage').eq(window.lastUploadImageIndex).append('<div>' + htmlEncode(imagefilename) + '<button type="button" class="deletefileimage" image_file_name="' + imagefilename + '">Remove</button><br/><hr/></div>');
}
else if (success == 2){
result = '<span class="imageemsg">' + cancel_image_file_name + ' Upload Was Cancelled!</span><br/><br/>';
}
else {
result = '<span class="imageemsg">There was an error during file upload!</span><br/><br/>';
}
return true;
}
In JavaScript variables have function-level scope, to get cancel_image_file_name in your other function too, define it outside of both functions.
BTW, you can use imagefilename from your stopImageUpload function because you are already passing it to that function:
return stopImageUpload(2, cancel_image_file_name);
So in your stopImageUpload function, change line:
result = '<span class="imageemsg">' + cancel_image_file_name + ' Upload Was Cancelled!</span><br/><br/>';
To:
result = '<span class="imageemsg">' + imagefilename + ' Upload Was Cancelled!</span><br/><br/>';
You're already passing in the value as the second parameter to "stopImageUpload", "imagefilename". Just use that.
In fact elsewhere in that same function you're using the parameter.
Restructure your code like this:
(function() {
var cancelimagecounter = 0,
imagecounter = 0,
cancel_image_file_name;
window.startImageUpload = function(imageuploadform,imagefilename) {
...
cancel_image_file_name = ... // (remove the var)
...
};
window.stopImageUpload = function(success,imagefilename) {
...
// cancel_image_file_name is not undefined now.
};
})();

Categories