I'm trying to build a simple site that will check and print out "Buy It Now Prices" for cars. I can't get the JavaScript push function to print out anything but strings.
The eBay API says that buyItNowPrice returns an Amount.
I have experimented with the other Item functions, and the only ones that are working for me are ones that return a String.
The question is, how should the line var itemPrice = item.buyItNowPrice; be formatted to output a number?
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;
var itemPrice = item.buyItNowPrice;
var timeLeft = item.watchCount;
if (title != null && null != viewitem) {
html.push('<tr><td>' + '<img src="' + pic + '" border="1">' + '</td>' +
'<td><a href="' + viewitem + '" target="_blank">' +
title + '</a>' // end hyperlink
+
'<br>Item Price: ' + itemPrice +
'<br>Time Remaining: ' + timeLeft +
'</td></tr>');
}
}
html.push('</tbody></table>');
document.getElementById("results").innerHTML = html.join("");
}
// Create a JavaScript array of the item filters you want to use in your request
var filterarray = [{
"name": "MaxPrice",
"value": "250000",
"paramName": "Currency",
"paramValue": "USD"
},
{
"name": "MinPrice",
"value": "15000",
"paramName": "Currency",
"paramValue": "USD"
},
//{"name":"FreeShippingOnly", "value":"false", "paramName":"", "paramValue":""},
{
"name": "ListingType",
"value": ["AuctionWithBIN", "FixedPrice", /*"StoreInventory"*/ ],
"paramName": "",
"paramValue": ""
},
];
// Generates an indexed URL snippet from the array of item filters
var urlfilter = "";
function buildURLArray() {
for (var i = 0; i < filterarray.length; i++) {
var itemfilter = filterarray[i];
for (var index in itemfilter) {
// Check to see if the paramter 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];
}
}
}
}
}
buildURLArray(filterarray);
// Construct the request
var url = "http://svcs.ebay.com/services/search/FindingService/v1";
url += "?OPERATION-NAME=findItemsByKeywords";
url += "&SERVICE-VERSION=1.0.0";
url += "&SECURITY-APPNAME=REDACTED";
url += "&GLOBAL-ID=EBAY-MOTOR";
url += "&RESPONSE-DATA-FORMAT=JSON";
url += "&callback=_cb_findItemsByKeywords";
url += "&REST-PAYLOAD";
//url += "&categoryId=6001";
url += "&keywords=Ferrari 575";
url += "&paginationInput.entriesPerPage=12";
url += urlfilter;
// Submit the request
s = document.createElement('script'); // create script element
s.src = url;
document.body.appendChild(s);
You are reading the wrong eBay documentation. FindItemsByKeywords is part of the Finding API service. The buyItNowPrice field is found in the item.listingInfo field. Changing the code to the following will output the price.
var itemPrice = '---';
// buyItNowPrice may not be returned for all results.
if(item.listingInfo[0].buyItNowPrice) {
itemPrice = item.listingInfo[0].buyItNowPrice[0]['#currencyId'] + ' ' + item.listingInfo[0].buyItNowPrice[0].__value__;
} else if(item.sellingStatus[0].currentPrice) {
itemPrice = item.sellingStatus[0].currentPrice[0]['#currencyId'] + ' ' + item.sellingStatus[0].currentPrice[0].__value__;
}
Related
The script below will loop through and generate 50 records. I have a dynamic value RANKS = "8". How can I check if 8 is exists in id="rankN"?
The value[RANKS] is dynamic from 1-50
var RANKS = "8";
var ranking;
for (var i = 0; i < rankingList.length; i++) {
var a = 1;
ranking = "<div > " +
("<div id=rank" + a + " class='RankCol'>" + rankingList[i].rankNo + "</div>") +
("<div>" + rankingList[i].username + "</div>") +
("<div>" + rankingList[i].winningAmt + "</div>") +
("<div> " + rankingList[i].uCoin + "</div>") +
(" </div>");
};
Expected result:
A
A
B
B
C
B
A
A
B
G
so if my ranking is 8, the text will bold. IF the value is not within 50, then i will do another css. my main problem is how can i check whether the looped' ID contains the id number same as my RANKS(which is 8)
If you want to check in DOM, then simply var exists = $('#rank8').length !== 0.
If you want it to check inside loop:
var ranks = {};
for (var i = 0; i < rankingList.length; i++) {
newRank = 'rank' + i;
if (typeof ranks[newRank] !== 'undefined') {
// skip
continue;
} else {
ranking = '<div id="' + newRank + '" ...';
}
ranks[newRank] = newRank;
}
Try this
rankingDiv.html(rankingList.map((rank,i) => `<div>
<div id="rank${i+1)" class='RankCol'>${rank.rankNo}</div>
<div>${rank.username}</div>
<div>${rank.winningAmt}</div>
<div>${rank.uCoin}</div>
</div>`);
const $myRank = $(`#rank${RANKS}`);
if ($myRank.length===1) myRank.html(`<b>${$myRank.text()}</b>`)
Older sugggestion
$(\`#rank${RANKS}\`).length===1
I've a sample JSON as given below:
[
{
"componentid": 4,
"displayImageUrl": "https://via.placeholder.com/350x200",
"title": "theme",
"shortdesc": "to set theme for different applications"
},
{
"componentid": 7,
"displayImageUrl": "https://via.placeholder.com/350x200",
"title": "preferences",
"shortdesc": "preferences screen for apps"
}
]
And I prepared a HTML content based on that data. Code is given below:
function prepareTopComponentList(data) {
var preparedHtml = "";
for (var count = 0; count < data.length; count++) {
preparedHtml += "<div class=\"col-lg-4\" style=\"margin-top: 20px\">\n" +
" <div class=\"card wow fadeIn\" data-wow-delay=\"0.2s\">\n" +
" <img class=\"img-fluid\" src=\"";
preparedHtml += data[0].displayImageUrl;
preparedHtml += "\" alt=\"N/A\">\n" +
" <div class=\"card-body\">\n" +
" <h4 class=\"card-title\">";
preparedHtml += data[0].title;
preparedHtml += "</h4>\n" +
" <p class=\"card-text\">";
preparedHtml += data[0].shortdesc;
preparedHtml += "</p>\n" +
" <a onclick = \"redirect(this, this);\" href='#' class=\"btn btn-info\" id=\"";
preparedHtml += "component_desc_" + data[count].componentid;
/*I replaced 0 with count so that we can get proper ids*/
//console.log(data[0].componentid);
preparedHtml += "\">Learn more</a>\n" +
" </div>\n" +
"\n" +
" </div>\n" +
" </div>";
}
$("#div_top_component").append(preparedHtml);
}
Now, I'm redirecting to a page based on value of componentid. Redirection function code is given below:
function redirect(element, data) {
// data = prepareTopComponentList(data);
for (var count = 0; count < data.length; count++) {
var url = "inside.dell.com";
var query = data[count].componentid;
var finalUrl = "inside.dell.com/componentid=" + query;
console.log(finalUrl);
}
window.location = "inside.dell.com/componentid=" + query;
}
When I run this code, I get this error:
The requested URL /Reusable Components/pages/inside.dell.com/componentid=undefined was not found on this server.
That error is fine, I don't have any problem with that. However in redirection URL, component id is undefined. How do I make sure that value of component ID gets passed to URL?
In your HTML
"<a onclick = \"redirect(" + data[count].componentid + ");\" href='#' class=\"btn btn-info\" id=\"";
And then your function
function redirect(id) {
window.location = "inside.dell.com/componentid=" + id;
}
The variable query used for windows.location is defined in the for loop block and therefore is undefined outside of it.
Declare your query variable outside of for loop.
function redirect(element, data) {
// data = prepareTopComponentList(data);
var query;
for (var count = 0; count < data.length; count++) {
var url = "inside.dell.com";
query = data[count].componentid;
var finalUrl = "inside.dell.com/componentid=" + query;
console.log(finalUrl);
}
window.location = "inside.dell.com/componentid=" + query;
}
This question already has answers here:
How can I access object properties containing special characters?
(2 answers)
Closed 5 years ago.
I'm working with JSON to query the API provided by themoviedb.org.
I want to make a list of episodes. To do so I need to access the length property of several objects named "season/1", "season/2", "season/3" etc., but I get errors all the time.
The returned JSON Code looks as follows:
"season/1": {
"_id": "5256c89f19c2956ff6046d47",
"air_date": "2011-04-17",
"episodes": [
{
"air_date": "2011-04-17",
"crew": [],
"episode_number": 1,
"guest_stars": [],
"name": "Der Winter naht",
"overview": "Ein Deserteur der Nachtwache bringt erschreckende Nachrichten von den Ländern nördlich der Mauer, und Lord Eddard \"Ned\" Stark soll die Hand des Königs Robert Baratheon werden.",
"id": 63056,
"production_code": "101",
"season_number": 1,
"still_path": "/wrGWeW4WKxnaeA8sxJb2T9O6ryo.jpg",
"vote_average": 7.493,
"vote_count": 67
},
{...},
.
.
.
]
}
My Javascript code:
var urlBase = 'https://api.themoviedb.org/3/tv/';
var tvId = 'XXX';
var apiKey = '?api_key=MYKEY';
var apiLang = '&language=de_DE';
var descElement = document.getElementById('description');
var titleElement = document.getElementById('title');
var posterElement = document.getElementById('poster');
var castElement = document.getElementById('cast');
var seasonsElement = document.getElementById('seasons');
var episodesElement = document.getElementById('episodes');
var votesElement = document.getElementById('votes');
var epGuideElement = document.getElementById('epGuide');
var showRequest = new XMLHttpRequest();
var showUrl = urlBase + tvId + apiKey + apiLang + '&append_to_response=credits';
showRequest.open('GET', showUrl);
showRequest.send();
showRequest.onload = function() {
var data = JSON.parse(showRequest.responseText);
var title = data.name;
var description = data.overview;
var episodes = data.number_of_episodes;
var seasons = data.number_of_seasons;
var votes = data.vote_average;
var cast = '';
for (i = 0; i < data.credits.cast.length; i++) {
cast +=
'<div style="background-color:#dedede;text-align:center;width:145px;height:215px;margin:10px;padding:10px;display:inline-block;float:left;position:relative;"><img src="http://image.tmdb.org/t/p/w90/'
+ data.credits.cast[i].profile_path
+ '" alt="'
+ data.credits.cast[i].name
+ '" style="margin-top:5px;"><br><div style="width:160px;bottom:20px;left:50%;transform:translate(-50%);position:absolute;"><span style="font-size:14px;">'
+ data.credits.cast[i].character
+ '</span><br><strong>'
+ data.credits.cast[i].name
+ '</strong></div></div>';
}
var epGuide = '';
for (i = 1; i <= seasons; i++) {
epGuide += '<h3>Staffel ' + i + '</h3>';
for (ii = 1; ii < data['season/'+i].episodes.length; ii++) {
epGuide += '<p>Folge ' + (ii + 1) + '</p>';
}
}
titleElement.insertAdjacentHTML('beforeend', title);
descElement.insertAdjacentHTML('beforeend', description);
posterElement.src = 'http://image.tmdb.org/t/p/w92' + data.poster_path;
castElement.insertAdjacentHTML('beforeend', cast);
episodesElement.insertAdjacentHTML('beforeend', episodes);
seasonsElement.insertAdjacentHTML('beforeend', seasons);
votesElement.insertAdjacentHTML('beforeend', votes);
epGuideElement.insertAdjacentHTML('beforeend', epGuide);
};
How can I select the "season/i" object with the slash and a variable inside its name?
//EDIT:
There you go, the whole code. Hope, we can find a solution.
In the javascript every variable is a hashTable data-structure and you can access/change its items like an array/hashTable for example:
var person = {name:'Siamand',family:'Maroufi'};
we can access the name property of person object by :
var name= person.name;
or
var name =person['name']
so in your case you can change you code into follwoing:
var epGuide = '';
for (i = 1; i <= seasons; i++) {
epGuide += '<h3>Staffel ' + i + '</h3>';
for (ii = 1; ii < data['season/'+i].episodes.length; ii++) {
epGuide += '<p>Folge ' + (ii + 1) + '</p>';
}
}
example snippet:
var response = `
{
"season/1": {
"_id": "5256c89f19c2956ff6046d47",
"episodes": [{
"air_date": "2011-04-17"
}]
}
}
`;
var data = JSON.parse(response);
var seasons = 2;
var epGuide ="";
for(var i=1;i<seasons;i++){
epGuide += '<h3>Staffel ' + i + '</h3>';
for (ii = 0; ii < data['season/'+i].episodes.length; ii++) {
epGuide += '<p>Folge ' + (ii + 1) + '</p>';
}
}
console.log(epGuide);
by the way the api that you are use hasent such result you said before , it something like follwoing, it has a simple array for seasons
var swTitle = {};
var favorite = [];
$.each($("input[name='Title']:checked"), function() {
favorite.push($(this).val());
console.log($("input[name='Title']:checked"));
});
swTitle.domain = favorite;
var List = {};
for (var m = 0; m < favorite.length; m++) {
var swTitleObj = [];
$.each($('input[name="' + swTitle.domain[m] + '"]:checked'), function() {
console.log(swTitle.domain[m]);
swTitleObj.push($(this).attr("class"));
console.log(swTitleObj);
});
List[swTitle.domain[m]] = swTitleObj;
}
var swSkillData = " ";
$.each(List, function(key, value) {
console.log(key + ":" + value);
swSkillData += '<li>' + key + ' ' + ':' + ' ' + value + '</li>';
});
Output will be like:
Fruits:Apple,Banana,Orange,Grapes
I want my output be like:
Fruits:Apple,Banana,Orange & Grapes
I have an array of keys and values separated by commas. I want to insert "and" and remove the comma before the last checked element. Kindly help me out with this issue.
I think you can reduce your code, with an option of adding and before the last element like,
var inputs=$("input[name='Title']:checked"),
len=inputs.length,
swSkillData='',
counter=0;// to get the last one
$.each(inputs, function() {
sep=' , '; // add comma as separator
if(counter++==len-1){ // if last element then add and
sep =' and ';
}
swSkillData += '<li>' + this.value + // get value
' ' + ':' + ' ' +
this.className + // get classname
sep + // adding separator here
'</li>';
});
Updated, with and example of changing , to &
$.each(List, function(key, value) {
console.log(key + ":" + value);
var pos = value.lastIndexOf(',');// get last comma index
value = value.substring(0,pos)+' & '+value.substring(pos+1);
swSkillData += '<li>' + key + ' ' + ':' + ' ' + value + '</li>';
});
Snippet
var value ='Apple,Banana,Orange,Grapes';var pos = value.lastIndexOf(',');// get last comma index
value = value.substring(0,pos)+' & '+value.substring(pos+1);
console.log(value);
Here is an easy and customizable form of doing it.
(SOLUTION IS GENERIC)
$(document).ready(function() {
var ara = ['Apple','Banana','Orange','Grapes'];
displayAra(ara);
function displayAra(x) {
var str = '';
for (var i = 0; i < x.length; i++) {
if (i + 1 == x.length) {
str = str.split('');
str.pop();
str = str.join('');
str += ' and ' + x[i];
console.log(str);
$('.displayAra').text(str);
break;
}
str += x[i] + ',';
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Fruits : <span class="displayAra"></span>
str = str.replace(/,(?=[^,]*$)/, 'and')
I solved my own issue. I replaced my last comma with "and" using the above regex. Thanks to Regex!!!
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