Smarty foreach to json javascript - javascript

I am trying to build google dynamic remarketing for online store and I have problem with many product id's in cart.
Here is my code:
{literal}
<script type="text/javascript">
var ids = "{/literal}{foreach from=$products|json_decode key=pId item=p name=i}{$p.id_product}{if not $smarty.foreach.i.last}, {/if}{/foreach}{literal}";
var total = "{/literal}{displayPrice price=$total_products_wt}{literal}";
total = total.replace(/[zł]/g, "");
total = total.replace(/[,]/g, ".");
dataLayer.push({
'event': 'fireRemarketingTag',
'google_tag_params': {
'ecomm_prodid': ids,
'ecomm_pagetype': 'cart',
'ecomm_totalvalue': total
}
});
</script>
{/literal}
Still getting error from google tag assistant - "Multiple product IDs need to be stored in an array."
it looks like this
ecomm_prodid:367\, 74, ecomm_pagetype:cart, ecomm_totalvalue:109.80
"ecomm_prodid": "367,
74",
it should look like this;
ecomm_prodid:367,74, ecomm_pagetype:cart, ecomm_totalvalue:109.80
"ecomm_prodid": [
367,
74
],

I think the only thing you need to do, is to change the " characters around the var ids definition to [ and ], like this:
var ids = [{/literal}{foreach from=$products|json_decode key=pId item=p name=i}{$p.id_product}{if not $smarty.foreach.i.last}, {/if}{/foreach}{literal}];

Related

Make a query with JSON

I have JSON data gets Vedios data of youtube list. And the following link display structure of my JSON.
<a href="https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=UUbW18JZRgko_mOGm5er8Yzg&key=AIzaSyDGm1uzuqPPUGzG-qN7u6gTaS8ApXBJYvw">
Click me to get all list videos ID ...
</a>
And here is the channel with its ID
After analyses of my JASON, I have JSON array named "items" (row 9).
Now all I need to get specific information from all units included with this array "items".
All I need to make a query using JavaScript or c# to return JSON with this specific data
title
description
thumbnails - standard
videoId
Finally, I found a solution for my problem. Not very professional but good for now.
I used Jquery selectors to extract data from my JSON object as following.
$(document).ready(function () {
var jsonLink = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=PL0zTBP9-UnPaIurxKLr3rfPZwHrFl2mEq&key=AIzaSyDGm1uzuqPPUGzG-qN7u6gTaS8ApXBJYvw&maxResults=50";
$.getJSON(jsonLink).done(function (data) {
var items = [];
$.each(data.items, function (i, item) {
items.push("<li>" + item.snippet.title + "</li>");
if (i === 5) {
return false;
}
});
$("<ul/>", {
"class": "my-new-list",
html: items.join("")
}).appendTo("body");
});
});

prestashop get product information on category list

I have many product categories in my store and some of them don't have products. I would like to erase the link on them, so the user can see them but wouldn't lose time exploring categories without products.
However I can't manage to get the number of products in the category. I've tried this but it gives me a 403 error
$.get('/themes/theme/product.tpl', function(r){
var obj = $(r).find('body');
var PageText = $(r).find('.center_indent').text();
if (PageText===""){alert("yes")}
else {alert("no")}
});
Does anyone have an idea? I'm working with prestashop 1.6.1.9
Edit: I found out I couldn't make an array of subcategories, so I added a function in the Category class:
public static function countProductInCat($id_category)
{
$category = new Category($id_category, 1);
$productCount = $category->getProducts(1, 1, 10000, null, null, true);
return $productCount;
}
And I called it in the category-description.tpl file:
{if (Category::countProductInCat($subcategory_id)) > 0}
{else}
<span style="opacity:0.3;background:#999"></span>
{/if}
I don't quite know which template you want to modify, but if you have access to a category object in Smarty (be it a single category or within a loop), you could test the presence of products this way :
{if count($category->getProducts()) > 0}
{link .....}
{else}
{$category->getName()}
{/if}

Getting Currency Information From Country Code in PHP

I want to get the currency code information (for example:USD etc.) from country code.I tried most of methods but I cannot have this data.I had the country code from geolocation.
How can I solve this problem and get the currency code?
Copy the object in this page into your code, like this
var countryCurrencies = {
"BD": "BDT",
"BE": "EUR",
"BF": "XOF",
...
"UA": "UAH",
"QA": "QAR",
"MZ": "MZN"
}
//get your country code
var countryCode = "ma"; //For example
var currency = countryCurrencies.hasOwnProperty(countryCode.toUpperCase()) ? countryCurrencies[countryCode.toUpperCase()] : "Unkonw";
//The result : curreny = "MAD"
You can do with this following api its very easy and good
https://restcountries.eu/rest/v1/alpha/in
"in" be the country code for india.
Eg with jquery
jQuery.getJSON(
"https://restcountries.eu/rest/v1/alpha/in,
function (data) {
console.log(data.currencies)
}
);
in data: you get almost every information related to country
Here an Array with all Country Information:
<?php $location = unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip='.$_SERVER['REMOTE_ADDR'])); print_r($location) ?>

Parse JSON without specific element name in AngularJS

I want to parse the JSON response of Country & State from below mentioned URL.
https://gist.githubusercontent.com/mayurah/5f4a6b18b1aa8c26910f/raw/countriesToCities.json
{
"China": [
"Guangzhou",
"Fuzhou",
"Beijing",
"Baotou",
"Hohhot",
"Guiyang",
"Yinchuan",
"Nanjing",
"Changzhou",
"Chuzhou",
"Hefei",
"Jinan",
"Qingdao",
"Harbin",
"Zhaodong",
"Taiyuan",
"Xi'an",
.
.
.
}
]
I want the result as,
Guangzhou, China
Taiyuan, China
I am using AngularJS, Following is a piece of code of my controllers.js file.
var
apiUrl = {
countryStateList: 'https://gist.githubusercontent.com/mayurah/5f4a6b18b1aa8c26910f/raw/countriesToCities.json'
};
countryData.controller('countryDataCtrl', ['$scope', '$http', function($scope, $http) {
$http.get(apiUrl.countryStateList).success(function(data) {
// console.log(data);
$scope.countryStateList = data;
});
}]);
And, in my HTML file, code is something like this,
<ul ng-repeat="country in countryStateList">
<li>{{ STATE_NAME, COUNTRY_NAME }}</li>
</ul>
STATE_NAME & COUNTRY_NAME are just for in display information. Both must be replaced with Angular code.
The problem is JSON element names are itself country names. Can someone tell me how to parse the same in AngularJS/Javascript.
You could start by parsing the whole JSON:
var jsonObject = JSON.parse(RAW_JSON_STING);
var newJsonObject = [];
// Loop through it
for (var interator in jsonObject)
{
for (var it = 0; it < iterator.length; it++)
{
newJsonObject.push(iterator[it] + ", " + iterator);
}
}
No guarantee the code above will work as intended.
Ng-repeat will not be useful in your case. This would be possible using directive.
<datalist id="stateCountry">
<custom-datalist-option data-array="countryStateList"></custom-datalist-option>
</datalist>
Link a directive function and create an option using using it.
Here is the Update Fiddle
Hope this will help you.

Change content of a div based on an array within an array

Pastebin of index.html: http://pastebin.com/kdKFqTxe
Just copy and paste that and run it (this works but with some broken img links & no css).
With regards to the pastebin, just click on a node, and then click the first broken image below the video. What should happen is a dialogue box should appear with links to articles (from tubeArray). All relevant code is pasted below.
I'm trying to dynamically change the contents of a div when I click an image. The image has it's respective id (the first index in the inner array) within the first inner array there's another array (index 3). I want to populate my div (id="articleLinks") with those links using JQuery when the image is clicked.
JavaScript & JQuery:
The tube array. *Note: the first index of each element in tubeArray is the ID & the news articles aren't linked to anything particular. Only interested in tubeArray[0] & tubeArray[4]
var tubeArray = [
['UQ', -27.495134, 153.013502, "http://www.youtube.com/embed/uZ2SWWDt8Wg",
[
["example.com", "Brisbane students protest university fee hikes"],
["example.com", "Angry protests over UQ student union election"],
]
],
['New York', 40.715520, -74.002036, "http://www.youtube.com/embed/JG0wmXyi-Mw",
[
["example.com" , "NY taxpayers’ risky Wall Street bet: Why the comptroller race matters"]
]
],
['To The Skies', 47.09399, 15.40548, "http://www.youtube.com/embed/tfEjTgUmeWw",
[
["example.com","Battle for Kobane intensifies as Islamic State uses car bombs, Syrian fighters execute captives"],
["example.com","Jihadists take heavy losses in battle for Syria's Kobane"]
]
],
['Fallujah', 33.101509, 44.047308, "http://www.youtube.com/embed/V2EOMzZsTrE",
[
["example.com","Video captures family cat saving California boy from dog attack"],
["example.com","Fines of £20,000 for dogs that chase the postman"]
]
]
];
A for loop which goes through each element in tubeArray then assigns id to the first index. Also an image that calls the function myFunctionId which takes the parameter this.id.
for (i = 0; i < tubeArray.length; i++) {
var id = tubeArray[i][0];
//other code
'<img src="img.png" onclick="myFunctionId(this.id);" id="' + id + '">' +
//other code
}
function myFunctionId (id) {
journal = id;
alert(journal) //just a test
//I want to search through tubeArray with the id and find the matching inner array.
//I then want to loop through the innerArray and append to my html a link using JQuery.
$('#articleLinks').append("<a href='"+innerArray[0]+"'>"+innerArray[1]+'</a>'); // use CSS to break lines
}
}
HTML:
<div id="articleLinks">
Example Link<br>
</div>
Any help would be greatly appreciated. I've tried to simplify & cut out as much as I can so it's readable.
try this...
function myFunctionId (id) {
console.log(tubeArray);
tubeArray.forEach(function(entry) {
if (entry[0]==id) {
entry[4].forEach(function(innerArray){
$('#articleLinks').append("<a href='"+innerArray[0]+"'>"+innerArray[1]+'</a>'); // use CSS to break lines
});
return;
}
});
}
it makes it look like this for me... you're gonna have to handle that encoding issue. with the apostrophe. there are a lot of ways to handle it...
so.... if it was me... which it's not. but if it was... i would use an associative array instead of a numerically indexed one because it's easier to read the code and understand what you're using and where and how and things and stuff.
tubeArray = {
'UQ' : { 'location': [-27.495134, 153.013502],
'youtube': "example.com/embed/uZ2SWWDt8Wg",
'articles': [["example.com/queensland/brisbane-students-protest-university-fee-hikes-20140521-zrk8o.html", "Brisbane students protest university fee hikes"],
["example.com/content/2012/s3578878.htm", "Angry protests over UQ student union election"], ]
},
'New York': { 'location': [0.715520, -74.002036],
'youtube': "example.com/embed/JG0wmXyi-Mw",
'articles': [["example.com/2014/10/19/ny-taxpayers-risky-wall-street-bet-why-the-comptroller-race-matters/" , "NY taxpayers’ risky Wall Street bet: Why the comptroller race matters"]],
},
}

Categories

Resources