Add values to the cookie using URL - javascript

I'm working on my webshop and since I dont want users to have to register to use the webshop, im using javascript cookies to hold the values the user has entered. But I want people who go to the webshop with a different url (for example: http://test.com/index.php?124&342), having 2 values in the cart, I made some functions to work on this. Here is the following code:
function getUrlVars() {
var variabelen = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
var urls = $.cookie($.cookie('cart')) || [];
for (var i = 0; i < variabelen.length; i++) {
urls.push(variabelen[i]);
}
}
if ($.cookie('cart')) {
var Orders = $.parseJSON($.cookie('cart'));
} else {
var Orders = new Array;
}
getUrlVars();
Where "orders" is the json array with the selected product-ID's. Now this is not working as I wanted to. It's not pushing the URL variables into the cart.
Okay UPDATE:
I succeed in pushing the URL variables in the cookie, but now the following problem accurs.
function UpdateTotals() {
ToAddHTML = '<h1>Cart</h1></br>';
console.log(Orders);
TotalPrice = 0;
for (var i = 0; i < Orders.length ; i++) {
var Result = SubMenuItems.filter(function(v) {
return v.submenu_id === Orders[i];
})[0];
TotalPrice += parseFloat(Result.price);
ToAddHTML += '<div class=orderd> <span class="order" Orders='+i+'> </span>'+'€'+zoekresultaat.price+' '+zoekresultaat.title+'</br></div><hr>';
}
The live website is on(nb. im using dutch description so the functions have different names):
Website

If I understand the problem correctly this should do the trick:
// Given: page.html?109&10
// -----------------------
// Split the query string on '&', after the '?' and push
// each value into the array 'Bestellingen'
// -----------------------
$.each(document.location.search.substr(1).split('&'),function(key,value){
Bestellingen.push(value);
});
You can replace your method haalUrlVars with the two lines above and you should find that items 109 & 10 are added to your list as though the were in the cookie when the page loaded.
Does that help?

Related

How can I dynamically index through datalayer tags in GTM?

I'm using the DuracellTomi datalayer plugin to push cart data from woocommerce to a GTM model to handle some tracking.
The DuracellTomi plugin pushes content to the transactionProducts[] array in the following format:
transactionProducts: Array[1]
0 : Object
category:""
currency:"USD"
id:8
name:"Test"
price:100
quantity:"1"
sku:8
I'd like to loop through this array and unstack it into three separate arrays, pricelist, skulist, and quantitylist. Currently I anticipate doing so as some variation on
//Get Product Information
if(stack = {{transactionProducts}}){
for(i = 0; i < stack.length; i++) {
if(stack.i.sku){
skulisttemp.i = stack.i.sku;
}
if(stack.i.price){
pricelisttemp.i = stack.i.price;
}
if(stack.i.sku){
quantitylisttemp.i = stack.i.quantity;
}
}
{{skulist}} = skulisttemp;
{{pricelist}} = pricelisttemp;
{{quantitylist}} = quantitylisttemp;
}
Obviously this is not going to work because of how the tag referencing is set up, but I'm wondering if anyone has dealt with this and knows what the best way to index through these arrays might be. (For those who don't know, the square bracket array call doesn't work with GTM variables and instead the . format is used instead.)
You would need to create 3 variable type custom javascript function that picks your required value from dataLayer and returns it in an array.
Something like
function(){
var products = {{transactionProducts}};
var skuArray = [];
for(i = 0; i < products.length; i++) {
if(products[i].sku){
skuArray.push(products[i].sku)
}
}
return skuArray
}
hope this helped you :)

My update tag function here isn't working

Hi all I am new to angular and would like to know what I am doing wrong in this function.
I am trying to retrieve a firebase child array of tags and compare it with users tags and get an union and post that union back to the firebase array .
Here is my function:
//this retrieved the tag arrays from firebase
$scope.utags = Tag.gettag();
This function converts a firebase array to a JS array .. I initialize it with {{universaltags(utags)}} from the view. Any attempt to initiate the function in the controller using $scope.unversaltags($scope.utags); gives me a blank array
but it works with the views initiation.
$scope.universaltags = function(utag){
var arr1 = [];
for (var i = 0 ; i < utag.length; i++) {
arr1.push(utag[i].$value);
}
return arr1;
};
Also this is the function which I use to find the union and post it back to firebase.
$scope.universaltagupdate = function union_arrays (x,y,Tag) {
var obj = {};
for (var i = x.length-1; i >= 0; -- i) {
obj[x[i]] = x[i];
}
for (var i = y.length-1; i >= 0; -- i) {
obj[y[i]] = y[i];
}
var res = [];
for (var k in obj) {
if (obj.hasOwnProperty(k)) { // <-- optional
res.push(obj[k]);
}
}
//this uses a service to set firebase value
return Tag.updatetag(res);
}
I am not able to initialize both the functions within the controller.
Can you please tell me what is wrong with this approach and what can be the best way to achieve the result? Right now using the functions in curly braces show the results, but how do I accomplish this in the controller?

Do a query for every loop item and wait for result

I am making a CloudCode function that returns all users that are matching to my settings. In this function I am looping through a list of users and I need to get their settings in order to see if I should return them. The only problem is that the loop doesn't wait for the query to finish.
How can I get the Settings object for every user in the loop, check if the settings are correct and then push them in an array and return the array when the loop has finished?
The code I am using now:
for (var i = 0; i < connectResults.length; i++) {
var connect = connectResults[i];
for (var j = 0; j < matchResults.length; j++) {
var match = matchResults[j];
if (connect.get("sendBy").id == match.id) {
var indexOf = matchResults.indexOf(match);
matchResults.splice(indexOf, 1);
} else if (connect.get("receivedBy").id == match.id) {
var indexOf = matchResults.indexOf(match);
matchResults.splice(indexOf, 1);
}
if(typeof match.get("settings") != 'undefined') {
var settingsQuery = new Parse.Query("Settings");
settingsQuery.equalsTo("objectId",match.get("settings").id);
settingsQuery.find({
success: function(setting) {
console.log(match.get("username") + " " + setting.get("radius"));
}
});
}
}
}
response.success(matchResults);
Instead of querying all users and attempting to match their settings, I would instead query all users using the setting as a query constraint. In other words, tell the database that you want it to return all the users with the right settings.
var usersQuery = new Parse.Query("Users");
//Below, "settings" is the column name in your Users table
usersQuery.equalTo("settings", /* Settings value you are matching */);
usersQuery.find({
//...
});
You might need a containedIn query if there are multiple setting possibilities. See the docs for an example: https://parse.com/docs/js/guide#queries-query-constraints
Good luck! :)

Merging JSON data from multiple URL's and sorting them based on a key

I need some help with Javascript. I have some data that I received from youtube APIs. The data is retrieved from the below URL's (I only showed 2 but I get from multiple other channels too)
https://www.googleapis.com/youtube/v3/search?key=AIzaSyDuS9LWv86VFCFr4ZD_Kwp5--Zi6YKo_rM&part=snippet,id&order=date&maxResults=50&channelId=UCpVm7bg6pXKo1Pr6k5kxG9A
https://www.googleapis.com/youtube/v3/search?key=AIzaSyDuS9LWv86VFCFr4ZD_Kwp5--Zi6YKo_rM&part=snippet,id&order=date&maxResults=50&channelId=UCLQZTXj_AnL7fDC8sLrTGMw
Every item in these json files has "publishedAt" value. Now I want to merge the data from both the JSON files and sort the list based on the "publishedAt" key i.e., the latest uploaded videos shown first.
Here is what I have currently which works perfectly for one file (I didn't do any magic, the URL itself sorts the items based on date)
$.getJSON(sourceUrl, function (data) {
//console.log(data);
//var you_data = JSON.stringify(data);
var videosCount = data.items.length;
console.log("The number of videos is: " + videosCount);
for ( i = 0 ; i < videosCount; i++) {
var title = data.items[i].snippet.title;
var url = "https://www.youtube.com/watch?v=" + data.items[0].id.videoId;
$("#reply").append(" " + title + "<br><br><br>");
//console.log(title);
//console.log(url);
};
});
How do I get this done?
EDITED (my thoughts):
Something that I can think of is using nested objects. I can create a new object that two looks something like:
grand_parent_object = { {'publishedAt':xxxxxxxx, 'wholeItem':{the whole item as shown in the JSON file}}, {'publishedAt':xxxxxxxx, 'wholeItem':{the whole item2 as shown in the JSON file}}, etc}
here the parent_object is {'publishedAt':xxxxxxxx, 'wholeItem':{the whole item as shown in the JSON file}}
Maybe I should sort the parent_objects based on their 'publishedAt' values first and then that should do the job???? PS: 'publishedAt' in parent_object is the same as 'publishedAt' in the 'wholeItem' value.
Solution:
I used Ross's logic and it worked. I had issues with .getJson since it wouldn't update the global variable, wholearray. So I used .ajax and it worked. Here is my working code:
function getAjaxData(sourceUrl) {
$.ajax({
async:false,
url:sourceUrl,
success: function(data) {
var videosCount = data.items.length;
for ( var i = 0 ; i < videosCount; i++) {
var tempobject = {};
tempobject.published = data.items[i].snippet.publishedAt;
tempobject.wholeItem = data.items[i];
wholearray.push(tempobject);
}
}
});
}
One solution is to create a new array of object literals, then sort the array based on the key:
var array = [];
$.getJSON(url, function(data){
for (var i=0; i<data.length; i++){
var object = {}
object.published = data.items[i].snippet.publishedAt
object.wholeItem = data.items[i]
array.push(object);
}
})
$.getJSON(otherUrl, function(data){
for (var i=0; i<data.length; i++){
var object = {}
object.published = data.items[i].snippet.publishedAt
object.wholeItem = data.items[i]
array.push(object);
}
})
Have a listener that waits for both AJAX calls to finish, then you can sort:
array.sort(function(a,b) { return a.published - b.published; });
This question gives more info on sorting
This may not be the most efficient way, but it's the first that comes to mind and will work swell!

unable to search for array items

In this program I am unable to search for items in an array. The db variable is already defined. I am unable to get into the search function and run it. Just curious why this might be happening. I am able to run the first validate function but then stops and will not perform the rest of the code.
// Create privatized scope using a self-executing function
(function() {
console.log("hello");
// Variable initialization (DO NOT FIX ANY OF THE BELOW VAR's)
var resultsDIV = document.getElementById("results"),
searchInput = document.forms[0].search,
currentSearch = '';
// Validates search query
var validate = function (query) {
console.log("validate");
// Trim whitespace from start and end of search query
query = query.trim();
// Check search length, must have 3 characters
if (query.length < 3) {
alert("Your search query is too small, try again.");
}else{
search(query);
// (DO NOT FIX THE LINE DIRECTLY BELOW)
searchInput.focus();
}
console.log("test");
};
console.log("outside search function");
// Finds search matches
var search = function (query) {
console.log("In search function");
// split the user's search query string into an array
var queryArray = query.split(" ");
// array to store matched results from database.js
var results = [];
// loop through each index of db array
for (var i = 0, j = db.length; i < j; i++) {
console.log(i);
// each db[i] is a single video item, each title ends with a pipe "|"
// save a lowercase variable of the video title
var dbTitleEnd = db[i].indexOf('|');
var dbItems = db[i].toLowerCase().substring(0, dbTitleEnd);
}
// loop through the user's search query words
// save a lowercase variable of the search keyword
for (var ii = 0, jj = queryArray.length; ii < jj; ii++) {
var qItem = queryArray[ii].toLowerCase();
}
// is the keyword anywhere in the video title?
// If a match is found, push full db[i] into results array
var compare = dbItems.indexOf(qItem);
if (compare !== -1) {
results = results.push(db[i]);
}
results.sort();
// Check that matches were found, and run output functions
if (results.length === 0) {
noMatch();
} else {
showMatches(results);
}
};
// Put "No Results" message into page (DO NOT FIX THE HTML VAR NOR THE innerHTML)
var noMatch = function() {
var html = '' +
'<p>No Results found.</p>' +
'<p style="font-size:10px;">Try searching for "JavaScript". Just an idea.</p>'
;
resultsDIV.innerHTML = html;
};
// Put matches into page as paragraphs with anchors
var showMatches = function (results) {
// THE NEXT 4 LINES ARE CORRECT.
var html = '<p>Results</p>',
title,
url
;
// loop through all the results search() function
for (var i = 0, j = results.length; i < j; i++) {
// title of video ends with pipe
// pull the title's string using index numbers
var titleEnd = results[i].indexOf('|');
title = results[i].subString(0, titleEnd);
// pull the video url after the title
url = results[i].substring(results[i].indexOf('|') + 1, results[i].length);
// make the video link - THE NEXT LINE IS CORRECT.
html += '<p><a href=' + url + '>' + title + '</a></p>';
resultsDIV.innerHTML = html; //THIS LINE IS CORRECT.
}
};
console.log("start of program");
/***** start of program *******/
// The onsubmit event will be reviewed in upcoming Course Material.
// THE LINE DIRECTLY BELOW IS CORRECT
document.forms[0].onsubmit = function(){
var query = searchInput.value;
validate(query);
// return false is needed for most events - this will be reviewed in upcoming course material
// THE LINE DIRECTLY BELOW IS CORRECT
return false;
};
})();
I checked your code and everything is there but somehow all wrongly connected. It seems that you have completely wrong concept about for loops. I did several minor changes:
query is trimmed on reading because we need it not just in validator
validator:
if query is too short set focus back
it validated but also allowed operation to continue in case of error - changed
changed to isValid() and checked in onsubmit handler
search:
wrong concept of for loops
you retrieve dbTitleEnd/dbItems and than overwrite them by the next one
there is no need to do results = results.push(db[i]); but just `results.push(db[i]);
subString() corrected to substring()
console.log() messages are left in
See Example in jsFiddle.

Categories

Resources