I am using the eBay JavaScript Finding API. The currency id member of the findItemsAdvancedResponse object is defined as #currencyId. So I am retrieving this value as:
function _cb_findItemsAdvanced(root) {
var items = root.findItemsAdvancedResponse[0].searchResult[0].item || [];
var html = [];
if (items.length == 0) {
html.push('No Results');
}
for (var i = 0; i < items.length; ++i) {
var item = items[i];
var title = item.title;
var pic = item.galleryURL;
var viewitem = item.viewItemURL;
var price = Number(item.sellingStatus[0].currentPrice[0].`__value__`).toFixed(2);
var currency = ""
var currency = item.sellingStatus[0].currentPrice[0].#currencyId;
if (null != title && null != viewitem) {
html.push('<div class="item-layout5"><table><tr><td><div style="width:102px;overflow:hidden;">');
html.push('<img src="' + pic + '" border= "" alt="' + title + '" /></div></td>');
html.push('<td><span class="itemname">' + title + '</span></td></tr>');
html.push('<tr><td><img src="PTMFOG0000000064.gif" alt="" /></td><td><span class="buyprice">' + currency + ' $' + price + '</span></td></tr></table></div>');
}
}
document.getElementById("results").innerHTML = html.join("");
} // End _cb_findItemsByKeywords() function
This works fine for Firefox browsers, but not for Google Chrome or IE (I get a compilation error).
Is using the # symbol in a member name acceptable in JavaScript? And what workaround can I use so that the above code will work in all browsers?
Thanks
In javascript, the syntax
foo.bar
is equivalent to
foo['bar']
and the latter works even when 'bar' is not a valid identifier name, as in this case.
Related
I have a url link:
http://mywebsite.org/product/page?var_one=result1&var_two=result2&var_three=result3&var_four=result4
The parameters are dynamic so it will not be static numbers.
In my example are 4, but maybe less or more.
I have a jquery code that pre selects a dropdown:
jQuery(document).ready(function( $ ) {
$("#var_one").val("result1");
});
Now I want to, depending on the url parameters above to populate jquery code like:
jQuery(document).ready(function( $ ) {
$("#var_one").val("result1");
$("#var_two").val("result2");
$("#var_three").val("result3");
.
.
.
});
Use regex to form a array of key value pair based on the url and use forEach to loop through the array and add the value to the id using .text()
Hope this helps!
var a = "http://mywebsite.org/product/page?var_one=result1&var_two=result2&var_three=result3&var_four=result4"
var query = a.split('?')[1] //extract query param
var queries = query.split(/&/g) //extract key value pairs from query param
queries.forEach(function(el){ //loop through the key value pair
var newElm = '<div id="' + el.split('=')[0] + '">'+el.split('=')[1]+'</div>' //create new elm
$('body').append(newElm) //append into DOM Body
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here's a function to retrieve URL-parameters:
function GetURLParameter(sParam) {
if (sParam != undefined && sParam.length > 0) {
var sPageHref = window.location.href;
var sPageURL = window.location.search.substring(1);
var sURLVariables = (sPageURL.length != '') ? sPageURL.split('&') : sPageHref.split('&');
for (var i = 0; i < sURLVariables.length; i++) {
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam) {
return sParameterName[1];
}
}
} else {
var sPageURL = document.location.pathname.split('&');
var sParameterName = sPageURL[0];
return sParameterName;
}
}
If you specify a parameter, like GetURLParameter('something') it will fetch that. If you just use GetURLParameter() it will fetch the link used, ie /index.php or whatever.
Update: to answer your question correctly as i understood you need to convert url parameters to JSON then use for loop and use keys, values to fill inputs values. so inputs are and values dynamic.
$(document).ready(function() {
String.prototype.allParams = function() {
return JSON.parse('{"' + decodeURI(this.split("?")[1]).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}')
}
var url = "http://mywebsite.org/product/page?var_one=result1&var_two=result2&var_three=result3&var_four=result4";
//var url = location.href
var params = url.allParams();
for (var k in params) {
if ($("#" + k).length) $("#" + k).val(params[k]);
//if input id not exist append to body or any container
//you can remove next line
else $("body").append("<input value='" + params[k] + "'/>");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Try this prototype url.param("param"); to get parameter value.
String.prototype.param = function(str) {
e = this.indexOf("?" + str + "=") > -1 ? "?" + str + "=" : "&" + str + "=";
return this.indexOf(e) == -1 ? undefined : this.split(e)[1].split("&")[0];
}
var url = "http://mywebsite.org/product/page?var_one=result1&var_two=result2&var_three=result3&var_four=result4";
console.log(url.param("var_one")); //result1
console.log(location.href.param("param")); //undefined
I have a folder with images that have long filenames, but they all have unique product ID numbers at the beginning
e.g. 1023-Very-Long-Image-Name.jpg.
What I'm trying to do is to get full image filename into my javascript, by just using this unique ID number.
e.g. I need to find an image with ID 1023, which is this one - 1023-Very-Long-Image-Name.jpg
All unique IDs stored in JSON database. So below is an example of my code:
$('.choose-range-cta').click(function () {
var rowID = $(this).attr("id");
var stylesTable = JSON.parse(stylesDB);
var styleHTML = "";
for (var i = 0; i < stylesTable.length; i++) {
if (stylesTable[i].collectionID == rowID) {
var blockTitle = stylesTable[i].styleName;
var blockPrice = stylesTable[i].fromPrice;
var blockSize = stylesTable[i].size;
var blockImageID = stylesTable[i].frontImageID;
styleHTML += "<div class=\"col-lg-4 style-block\"><span class=\"style-name\">" + blockTitle + "</span><span class=\"from-price\">from £" + blockPrice + "</span><span class=\"cta\">Select</span><div class=\"img-box\"><img src=\"" + ImagePath + blockImageID +"\"></div><span class=\"copy\">" + blockSize + "</span></div>";
}
}
$('#style-list').html(styleHTML);
});
Assuming your list is an array, use filter:
var imageArray = [
'1021-Don-Long-Image-Name.jpg',
'1022-Very-Long-Image-Name.jpg',
'1023-Dan-Long-Image-Name.jpg',
'1024-BobLong-Image-Name.jpg'
];
function getName(data, id) {
return data.filter(function (el) {
return el.substring(0, 4) === id;
})[0];
}
var name = getName(imageArray, '1023'); // 1023-Dan-Long-Image-Name.jpg
DEMO
I figured adding &outputSelector=GalleryInfo to the url would provide a higher resolution thumbnail, but that doesn't seem to work. I'm new to JSON, and the tutorial isn't very clear on the exact syntax to add to the URL to make this happen. Thanks!
<script>
function _cb_findItemsByKeywords(root)
{
var items = root.findItemsByKeywordsResponse[0].searchResult[0].item || [];
var html = [];
html.push('<table width="100%" border="0" cellspacing="0" cellpadding="3"><tbody>');
for (var i = 0; i < items.length; ++i)
{
var item = items[i];
var title = item.title;
var pic = item.galleryURL;
var viewitem = item.viewItemURL;
if (null != title && null != viewitem)
{
html.push(
'<tr id="api_microposts"><td>'
+ '<img src="' + pic + '" border="0" width="190">' + '<a href="' + viewitem + '" target="_blank">' + title +
'</a></td></tr>');
}
}
html.push('</tbody></table>');
document.getElementById("api").innerHTML = html.join("");
// Define global variable for the URL filter
var urlfilter = "";
// Generates an indexed URL snippet from the array of item filters
function buildURLArray() {
// Iterate through each filter in the array
for(var i=0; i<filterarray.length; i++) {
//Index each item filter in filterarray
var itemfilter = filterarray[i];
// Iterate through each parameter in each item filter
for(var index in itemfilter) {
// Check to see if the parameter has a value (some don't)
if (itemfilter[index] !== "") {
if (itemfilter[index] instanceof Array) {
for(var r=0; r<itemfilter[index].length; r++) {
var value = itemfilter[index][r];
urlfilter += "&itemFilter\(" + i + "\)." + index + "\(" + r + "\)=" + value ;
}
}
else {
urlfilter += "&itemFilter\(" + i + "\)." + index + "=" + itemfilter[index];
}
}
}
}
} // End buildURLArray() function
// Execute the function to build the URL filter
buildURLArray(filterarray);
url += urlfilter;
}
</script>
<!--
Use the value of your appid for the appid parameter below.
-->
<script src=http://svcs.ebay.com/services/search/FindingService/v1?SECURITY-APPNAME=*APP ID GOES HERE*&OPERATION-NAME=findItemsByKeywords&SERVICE-VERSION=1.12.0&RESPONSE-DATA-FORMAT=JSON&callback=_cb_findItemsByKeywords&REST-PAYLOAD&sortOrder=PricePlusShippingLowest&paginationInput.entriesPerPage=6&outputSelector=GalleryInfo&outputSelector=AspectHistogram&itemFilter(0).name=Condition&itemFilter(0).value(0)=New&itemFilter(1).name=MaxPrice&itemFilter(1).value=450.00&itemFilter(1).paramName=Currency&itemFilter(1).paramValue=USD&itemFilter(2).name=MinPrice&itemFilter(2).value=350.00&itemFilter(2).paramName=Currency&itemFilter(2).paramValue=USD&itemFilter(3).name=ListingType&itemFilter(3).value=FixedPrice&keywords=Moto%20x%2016gb>
</script>
It seems like you're looking for the galleryPlusPictureURL: http://developer.ebay.com/Devzone/finding/CallRef/types/SearchItem.html#galleryPlusPictureURL
After following eBay's API guidelines for displaying fixed price items that fall within a specified price range, results are still showing auction based items of varying prices outside the range. I followed their tutorial word for word, so I'm not sure what I'm doing wrong.
Code:
<div id="api"></div>
<script>
function _cb_findItemsByKeywords(root)
{
var items = root.findItemsByKeywordsResponse[0].searchResult[0].item || [];
var html = [];
html.push('<table width="100%" border="0" cellspacing="0" cellpadding="3"><tbody>');
for (var i = 0; i < items.length; ++i)
{
var item = items[i];
var title = item.title;
var pic = item.galleryURL;
var viewitem = item.viewItemURL;
if (null != title && null != viewitem)
{
html.push(
'<tr id="api_microposts"><td>'
+ '<img src="' + pic + '" border="0" width="190">' + '<a href="' + viewitem + '" target="_blank">' + title +
'</a></td></tr>');
}
}
html.push('</tbody></table>');
document.getElementById("api").innerHTML = html.join("");
// Create a JavaScript array of the item filters you want to use in your request
var filterarray = [
{"name":"MaxPrice",
"value":"500",
"paramName":"Currency",
"paramValue":"USD"},
{"name":"MinPrice",
"value":"200",
"paramName":"Currency",
"paramValue":"USD"},
{"name":"FreeShippingOnly",
"value":"true",
"paramName":"",
"paramValue":""},
{"name":"ListingType",
"value":["FixedPrice"],
"paramName":"",
"paramValue":""},
];
// Define global variable for the URL filter
var urlfilter = "";
// Generates an indexed URL snippet from the array of item filters
function buildURLArray() {
// Iterate through each filter in the array
for(var i=0; i<filterarray.length; i++) {
//Index each item filter in filterarray
var itemfilter = filterarray[i];
// Iterate through each parameter in each item filter
for(var index in itemfilter) {
// Check to see if the parameter has a value (some don't)
if (itemfilter[index] !== "") {
if (itemfilter[index] instanceof Array) {
for(var r=0; r<itemfilter[index].length; r++) {
var value = itemfilter[index][r];
urlfilter += "&itemFilter\(" + i + "\)." + index + "\(" + r + "\)=" + value ;
}
}
else {
urlfilter += "&itemFilter\(" + i + "\)." + index + "=" + itemfilter[index];
}
}
}
}
} // End buildURLArray() function
// Execute the function to build the URL filter
buildURLArray(filterarray);
url += urlfilter;
}
</script>
<!--
Use the value of your appid for the appid parameter below.
-->
<script src=http://svcs.ebay.com/services/search/FindingService/v1?SECURITY-APPNAME=*App ID*&OPERATION-NAME=findItemsByKeywords&SERVICE-VERSION=1.0.0&RESPONSE-DATA-FORMAT=JSON&callback=_cb_findItemsByKeywords&REST-PAYLOAD&keywords=iphone%205%2016gb%20unlocked&paginationInput.entriesPerPage=3>
</script>
The specifications come from this page. I would tackle this problem in two steps:
Check to see if you get the same results even if you comment out this line:
url += urlfilter;
If that happens then your problem is the way you make the request and the parameters you set are not yet relevant. If it does change then the request is going through well enough and you need to fiddle what you pass in.
In that case the parameters need some fiddling. If you are getting any results then one issue could be with the ListingType filter. The specifications say that ListingType takes a string OR can take multiple values. It might be that you want to use:
{"name":"ListingType",
"value": "FixedPrice",
"paramName":"",
"paramValue":""}
When utilizing eBay's API, the listings show using the low res thumbnail pictures, rather than the high res version that the seller uploaded. What must I alter in the code to fix this? I've looked at solutions on eBays API forum, but it doesn't seem to be relevant to the code used in the tutorial.
Javascript code:
<div id="api"></div>
<script>
function _cb_findItemsByKeywords(root)
{
var items = root.findItemsByKeywordsResponse[0].searchResult[0].item || [];
var html = [];
html.push('<table width="100%" border="0" cellspacing="0" cellpadding="3"><tbody>');
for (var i = 0; i < items.length; ++i)
{
var item = items[i];
var title = item.title;
var pic = item.galleryURL;
var viewitem = item.viewItemURL;
if (null != title && null != viewitem)
{
html.push(
'<tr id="api_microposts"><td>'
+ '<img src="' + pic + '" border="0" width="190">' + '<a href="' + viewitem + '" target="_blank">' + title +
'</a></td></tr>');
}
}
html.push('</tbody></table>');
document.getElementById("api").innerHTML = html.join("");
}
// Create a JavaScript array of the item filters you want to use in your request
var filterarray = [
{"name":"MaxPrice",
"value":"500",
"paramName":"Currency",
"paramValue":"USD"},
{"name":"MinPrice",
"value":"200",
"paramName":"Currency",
"paramValue":"USD"},
{"name":"FreeShippingOnly",
"value":"true",
"paramName":"",
"paramValue":""},
{"name":"ListingType",
"value":["FixedPrice"],
"paramName":"",
"paramValue":""},
];
// Define global variable for the URL filter
var urlfilter = "";
// Generates an indexed URL snippet from the array of item filters
function buildURLArray() {
// Iterate through each filter in the array
for(var i=0; i<filterarray.length; i++) {
//Index each item filter in filterarray
var itemfilter = filterarray[i];
// Iterate through each parameter in each item filter
for(var index in itemfilter) {
// Check to see if the parameter has a value (some don't)
if (itemfilter[index] !== "") {
if (itemfilter[index] instanceof Array) {
for(var r=0; r<itemfilter[index].length; r++) {
var value = itemfilter[index][r];
urlfilter += "&itemFilter\(" + i + "\)." + index + "\(" + r + "\)=" + value ;
}
}
else {
urlfilter += "&itemFilter\(" + i + "\)." + index + "=" + itemfilter[index];
}
}
}
}
} // End buildURLArray() function
// Execute the function to build the URL filter
buildURLArray(filterarray);
</script>
<!--
Use the value of your appid for the appid parameter below.
-->
<script src=http://svcs.ebay.com/services/search/FindingService/v1?SECURITY-APPNAME=*APPNAME*&OPERATION-NAME=findItemsByKeywords&SERVICE-VERSION=1.0.0&RESPONSE-DATA-FORMAT=JSON&callback=_cb_findItemsByKeywords&REST-PAYLOAD&keywords=iphone%205%2016gb%20unlocked&paginationInput.entriesPerPage=3>
</script>
By default the Finding API returns a 140px thumbnail. You will have to specify an outputSelector in your API call in order to retrieve a larger thumbnail (400px or 800px). Adding either outputSelector=PictureURLLarge or outputSelector=PictureURLSuperSize to the call should make it return a URL for a larger image.
I struggled with this for a long time too. Make these changes:
Replace item.galleryURL; with item.pictureURLSuperSize;
Add &outputSelector=PictureURLSuperSize right after &paginationInput.entriesPerPage=3
That should do the trick. Make sure to use the same capitalization structure.
I wrote a longer blog post about this with more examples here