Fetching results from LinkedIn API through javascript - javascript

First of all thank you for reading this. I am having some trouble fetching the data given by the Linkedin sign-in API with javascript. Here is the script:
<script type="text/javascript">
function onLinkedInAuth() {
IN.API.Profile("me").fields(["firstName","lastName","headline","summary","location","educations","skills"]).result(displayProfiles);
}
function displayProfiles(profiles) {
member = profiles.values[0];
document.getElementById("name").value = member.firstName +" "+ member.lastName;
document.getElementById("pos").value = member.headline;
document.getElementById("city").value = member.location.name;
document.getElementById("sum").value = member.summary;
var i=0;
do {
var oldHTML = document.getElementById('para').innerHTML;
var newHTML = oldHTML + "<tr><td>" + member.educations.values[i].schoolName + "</td></tr>";
document.getElementById('para').innerHTML = newHTML;
i++;
}
while(i<=1);
var v=0;
do {
var oldHTML = document.getElementById('tara').innerHTML;
var newHTML = oldHTML + "<tr><td>" + member.skills.values[v].skill.name + "</td></tr>";
document.getElementById('tara').innerHTML = newHTML;
v++;
}
while(member.skills.values[v].skill.name);
document.getElementById("educ").value = member.educations.values[1].schoolName;
document.getElementById("skills").value = member.skills.values[0].skill.name;
}
</script>
It's a very basic script to get the user infos and, among it, the educational and professional background of the user. The thing is that member.educations.values[i].schoolName and member.skills.values[v].skill.name can have multiple values and I want to gather them all.
It works as long as the specified fields are not empty but then it outputs an error saying that member.skills.values[v] is undefined and it does not run the second loop.
I know the error is really basic but I'm not that great in javascript.
Thanks for your help anyways, have a good day!

You should check the length of the returned values and then loop through them as needed. Something along the lines of:
var educations = member.educations;
if(educations._total > 0) {
for(var i = 0; i < educations._total; i++) {
document.getElementById("educ").value += (i > 0) ? ', ' : '';
document.getElementById("educ").value += educations.values[i].schoolName;
}
}

Related

how to list all local storage on page properly in javascript?

I am trying to show all my localstorage items value on my index page but for some reason it is not showing. can anyone see what I am doing wrong in my code below. In my index page script I am looping thorough the length of local storage and trying to display them on screen, only thing that display is one item. Please help. thanks for your help.
here is my code (index page script):
document.addEventListener("DOMContentLoaded", function (event) {
var dataFromLocalStorage = "";
for (var i = 0; i < localStorage.length; i++) {
dataFromLocalStorage =
dataFromLocalStorage + " " + localStorage.getItem(`key${i}`);
}
document.querySelector("#content").innerHTML = dataFromLocalStorage; // Updating same thing
})
The other script where I load it to localStorage:
var addToTheContent = document.getElementById("canvas");
var scheduleEvent = document.getElementById("scheduleStartTime");
var candidateId = document.getElementById('candsId');
var getCandId = document.getElementById("candsId");
var displayCandId = candidateId.options[candidateId.selectedIndex].value;
var id = 1;
function addTheEvent() {
var showText = addToTheContent.innerHTML = displayCandId + " ( " + scheduleEvent.value + " ) ";
localStorage.setItem(`key${id}`, JSON.stringify(showText))
id += 1
localStorage.getItem(`key${id}`);
window.location = "/";
}
"key${id}" is a template string, you need to use backticks `` instead of quotation marks "".
You could also loop through localStorage as you normally would for most JavaScript objects:
for(var key in localStorage) {
if(localStorage.hasOwnProperty(key)) { // ignore the prototype methods
// Do whatever you want with key and value found here
console.log(key + ": " + localStorage[key]);
}
}
Typo: Use i instead id
var dataFromLocalStorage = localStorage.getItem(`key${id}`);
correct:
var dataFromLocalStorage = `localStorage.getItem("key${i}");
Another thing, You are updating same innerHTML
var dataFromLocalStorage = "";
for (var i = 0; i < localStorage.length; i++) {
dataFromLocalStorage =
dataFromLocalStorage + " " + localStorage.getItem(`key${i}`);
}
document.querySelector("#content").innerHTML = dataFromLocalStorage; // Updating same thing
// do something with localStorage.getItem(localStorage.key(i));
// missing template string 'key${id}'
var id = 1;
function addTheEvent() {
var showText = displayCandId + " ( " + scheduleEvent.value + " ) ";
localStorage.setItem(`key${id}`, JSON.stringify(showText));
id += 1;
window.location = "/";
}

JS Function Scope with Ebay API

js beginner here. the ebay website has sample code for sending an api request with javascript. the code works out of the box, but the code breaks when i wrap the entire code inside of:
(document).ready( function() {
('button').click( function() {
//(ebays sample code here)
}); });
google chromes console says my error is:
Uncaught ReferenceError: _cb_findItemsByKeywords is not defined
at http://svcs.ebay.com/services/search/FindingService/v1?OPERATION-NAME=findItemsByKeywords&SERVICE-VERSION=1.0.0&SECURITY-APPNAME=micahelr-layitont-PRD-f51ca6568-6366e278&GLOBAL-ID=EBAY-US&RESPONSE-DATA-FORMAT=JSON&callback=_cb_findItemsByKeywords&REST-PAYLOAD&keywords=accord&paginationInput.entriesPerPage=5&itemFilter(0).name=MaxPrice&itemFilter(0).value=30&itemFilter(0).paramName=USD&itemFilter(1).name=ListingType&itemFilter(1).value(0)=AuctionWithBIN&itemFilter(1).value(1)=FixedPrice:1:5
(anonymous) # svcs.ebay.com/services/search/FindingService/v1?OPERATION-NAME=findItemsByKeywords&SERVICE-VERSION=1.0.0&SECURITY-APPNAME=micahelr-layitont-PRD-f51ca6568-6366e278&GLOBAL-ID=EBAY-US&RESPONSE-DATA-FORMAT=JSON&callback=_cb_findItemsByKeywords&REST-PAYLOAD&keywords=accord&paginationInput.entriesPerPage=5&itemFilter(0).name=MaxPrice&itemFilter(0).value=30&itemFilter(0).paramName=USD&itemFilter(1).name=ListingType&itemFilter(1).value(0)=AuctionWithBIN&itemFilter(1).value(1)=FixedPrice:1
what i have come up with, is that the scope of my callback function is incorrect. ive moved the .ready() and .click() statements in many different places within the script tags, trying to solve the problem without completely understanding how it can be fixed. i tried reading about function scope but it seems like its something that i just cant figure out. the following is the content of mt HTML file with embedded JS code:
<html>
<head>
</head>
<body>
<button>click</button>
<script>
$(document).ready(function() {
$('button').click( function() {
var urlfilter = "";
item_MaxPrice = Number(document.getElementById('pagePrice').innerHTML);
inputKeywords = 'accord';
var filterarray = [ {"name":"MaxPrice", "value":item_MaxPrice, "paramName":"USD"}, ];
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">
for (var i = 0; i < items.length; ++i) {
var item = items[i];
html.push('text here');};
document.getElementById("results").innerHTML = html.join("");};
// Generates an indexed URL snippet from the array of item filters
function buildURLArray() {
for(var i=0; i<filterarray.length; i++) {
var itemfilter = filterarray[i];
for(var index in itemfilter) {
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];
}}}}}
// Execute the function to build the URL filter
buildURLArray(filterarray);
var url = "http://svcs.ebay.com/services/search/FindingService/v1";
url += "?OPERATION-NAME=findItemsByKeywords";
url += "&SERVICE-VERSION=1.0.0";
url += "&SECURITY-APPNAME=micahelr-layitont-PRD-f51ca6568-6366e278";
url += "&GLOBAL-ID=EBAY-US";
url += "&RESPONSE-DATA-FORMAT=JSON";
url += "&callback=_cb_findItemsByKeywords";
url += "&REST-PAYLOAD";
url += "&keywords="+inputKeywords;
url += "&paginationInput.entriesPerPage=5";
url += urlfilter;
s=document.createElement('script'); // create script element
s.src= url;
document.body.appendChild(s);
document.write("<a href='" + url + "'>" + url + "</a>");
})});
</script>
</body>
<footer>©darnell cross 2018</footer>
</html>
Uncaught ReferenceError: _cb_findItemsByKeywords is not defined
You are getting this error because Javascript can't find the _cb_findItemsByKeywords function.
What is the problem?
You are creating a script element and adding it to the DOM which is having _cb_findItemsByKeywords function as a callback in the URL.
s=document.createElement('script'); // create script element s.src=
url; document.body.appendChild(s); document.write("" + url + "");
Now, the script would run in the global context and wouldn't find any _cb_findItemsByKeywords function there because you defined it inside of another function.
$(document).ready(function() {...}
(Remember: Every function creates it's own context)
Solution:
Add the _cb_findItemsByKeywords function to the window object.
window._cb_findItemsByKeywords = function() {...}
Hopefully this helps you understand scope with indentation levels. Normally when you indent you use it to help you visualize the levels of scope. A variable declared in a parent scope can be accessed in the child but not the other way around.
<html>
<head>
</head>
<body>
<button>click</button>
<script>
$(document).ready(function() {
$('button').click(function() {
//start of scope
var urlfilter = "";
item_MaxPrice = Number(document.getElementById('pagePrice').innerHTML);
inputKeywords = 'accord';
var filterarray = [{
"name": "MaxPrice",
"value": item_MaxPrice,
"paramName": "USD"
}, ];
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">
for (var i = 0; i < items.length; ++i) {
//start of new scope (can access everything in parent scope but nothing in a scope that is further nested
var item = items[i];
html.push('text here');
//end of new scope
}; document.getElementById("results").innerHTML = html.join("");
};
// Generates an indexed URL snippet from the array of item filters
function buildURLArray() {
for (var i = 0; i < filterarray.length; i++) {
var itemfilter = filterarray[i];
for (var index in itemfilter) {
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];
}
}
}
}
}
// Execute the function to build the URL filter
buildURLArray(filterarray);
var url = "http://svcs.ebay.com/services/search/FindingService/v1";
url += "?OPERATION-NAME=findItemsByKeywords";
url += "&SERVICE-VERSION=1.0.0";
url += "&SECURITY-APPNAME=micahelr-layitont-PRD-f51ca6568-6366e278";
url += "&GLOBAL-ID=EBAY-US";
url += "&RESPONSE-DATA-FORMAT=JSON";
url += "&callback=_cb_findItemsByKeywords";
url += "&REST-PAYLOAD";
url += "&keywords=" + inputKeywords;
url += "&paginationInput.entriesPerPage=5";
url += urlfilter;
s = document.createElement('script'); // create script element
s.src = url;
document.body.appendChild(s);
document.write("<a href='" + url + "'>" + url + "</a>");
})
//end of button scope
});
</script>
</body>
<footer>©darnell cross 2018</footer>
</html>

Javascript onmousehover event to connect information

So in my code I created a table pulling from an XML file that displayed two columns of information about plants. The goal of my program is to be able to hover over the first and print out the other information about that plant and print it in another section to the right of my table. The issue is that I am not gettign any console errors and the hover affect is not printing any information.
window.addEventListener("load", link_events);
var xhr = false;
function link_events() {
xhr = new XMLHttpRequest();
if(xhr) {
xhr.addEventListener("readystatechange", ShowFile);
xhr.open("GET", "plants.xml", true);
xhr.send();
} else {
alert("XHR not supported.");
}
}
function ShowFile() {
var i;
var title;
var cover;
var plant_table = "<table><tr><th>Common Name </th><th>Botanical Name </th></tr>";
if (xhr.readyState == 4) {
if (xhr.status == 200) {
//here we have gotten the file correctly
//loop through it and print out cover and title
var plantlist = xhr.responseXML.getElementsByTagName("PLANT");
//booklist is an array and each element is an object sub i
//so you have to use getElementBy something in order to pull the information
for (i = 0; i < plantlist.length; i++) {
var Common = plantlist[i].getElementsByTagName("COMMON")[0].firstChild.textContent;
var Botanical = plantlist[i].getElementsByTagName("BOTANICAL")[0].firstChild.textContent;
plant_table += "<tr>" +
"<td class =\"plant\">" + Common + "</td>" +
"<td>" + Botanical + "</td>" +
"</tr>";
}
plant_table += "</table>";
document.getElementById("outarea").innerHTML = plant_table;
}
var plants = document.getElementsByClassName("plant");
for (i=0; i < plants.length; i++) {
plants[i].onmouseover = HoverChoice;
}
}
function HoverChoice() {
var input = xhr.responseXML.getElementsByTagName("PLANT");
for (i = 0; i < input.length; i++) {
Common = input[i].getElementsByTagName("COMMON")[0].firstChild.textContent;
var Zone = input[i].getElementsByTagName("ZONE")[0].firstChild.textContent;
var Light = input[i].getElementsByTagName("LIGHT")[0].firstChild.textContent;
var Price = input[i].getElementsByTagName("PRICE")[0].firstChild.textContent;
if (plants == this.innerHTML) {
document.getElementById("inarea").innerHTML =
"<h1>" + Common + "</h1>" + "<br />" + "<br />" +
"Zone: " + Zone + "<br />" +
"Light: " + Light + "<br />" +
"Price: " + Price;
}
}
}
}
you could try using addEventListener method instead and see whether it works?
plants.forEach(function(plant){
plant.addEventListener("onmouseover", HoverChoice);
});
or going with the original loop you made it would be
for (i=0; i < plants.length; i++)
{
plants[i].addEventListener("onmouseover", HoverChoice);
}
I'm not anything professional, a common problem I used to encounter in these kinds of event listening functions was that calling a global function sometimes fails but making the function on the spot inside the event listener would work like addEventListener("onmouseover" , function() { return 0; });

displaying multiple arrays using javascript

these are my arrays
var CarType=["RM","BM","GM"];
var CarName=["Red Mustang","Black Mustang","Green Mustang"]
how would I create a simple function that when a button is pushed an alert would pop up that displays something like this:
RM = Red Mustang
BM = Black Mustang
GM = Green Mustang
Here's a working solution. Hope it helps!
function myFunction() {
var CarType=["RM","BM","GM"];
var CarName=["Red Mustang","Black Mustang","Green Mustang"];
var result = "";
for(var i in CarType){
result += [CarType[i] + " = " + CarName[i]] + "\n";
}
alert(result)
}
<button onclick="myFunction()">Click me</button>
I haven't tested this, but it should go something like this.
Your arrays must have same size for this to work and sorted
function display(carType, carName) {
var text = "";
for (i=0; i < carType.length; i++) {
text += carType[i] + " = " + carName[i] + "\n";
}
alert(text);
}
var CarType=["RM","BM","GM"];
var CarName=["Red Mustang","Black Mustang","Green Mustang"];
display(CarType, CarName);

Uncaught ReferenceError: variable is not defined on onclick function Javascript

Today , i have been read all the topic about this but couldn't come up with a solution that's why i am opening this topic.
This is my function which creates the view and i am trying to have a onclick function which should directs to other javascript function where i change the textbox value.
<script type="text/javascript">
$('#submitbtnamazon')
.click(function(evt) {
var x = document.getElementById("term").value;
if (x == null || x == "" || x == "Enter Search Term") {
alert("Please, Enter The Search Term");
return false;
}
listItems = $('#trackList').find('ul').remove();
var searchTerm = $("#term").val();
var url = "clientid=Shazam&field-keywords="
+ searchTerm
+ "&type=TRACK&pagenumber=1&ie=UTF8";
jsRoutes.controllers.AmazonSearchController.amazonSearch(url)
.ajax({
success : function(xml) {
$('#trackList')
.append('<ul data-role="listview"></ul>');
listItems = $('#trackList').find('ul');
html = ''
tracks = xml.getElementsByTagName("track");
for(var i = 0; i < tracks.length; i++) {
var track = tracks[i];
var titles = track.getElementsByTagName("title");
var artists = track.getElementsByTagName("creator");
var albums = track.getElementsByTagName("album");
var images = track.getElementsByTagName("image");
var metaNodes = track.getElementsByTagName("meta");
//trackId ="not found";
trackIds = [];
for (var x = 0; x < metaNodes.length; x++) {
var name = metaNodes[x]
.getAttribute("rel");
if (name == "http://www.amazon.com/dmusic/ASIN") {
trackId = metaNodes[x].textContent;
trackIds.push(trackId);
}
}
for (var j = 0; j < titles.length; j++) {
var trackId=trackIds[j];
html += '<div class="span3">'
html += '<img src="' + images[j].childNodes[0].nodeValue + '"/>';
html += '<h6><a href="#" onclick="someFunction('
+trackId
+ ')">'
+trackId
+ '</a></h6>';
html += '<p><Strong>From Album:</strong>'
+ albums[j].childNodes[0].nodeValue
+ '</p>';
html += '<p><Strong>Artist Name:</strong>'
+ artists[j].childNodes[0].nodeValue
+ '</p>';
html += '<p><Strong>Title:</strong>'
+ titles[j].childNodes[0].nodeValue
+ '</p>';
/*html += '<p><Strong>Created:</strong>'
+ releaseDate
+ '</p>';*/
html += '</div>'
}
}
//listItems.append( html );
$("#track").html(html);
$("#track").dialog({
height : 'auto',
width : 'auto',
title : "Search Results"
});
// Need to refresh list after AJAX call
$('#trackList ul').listview(
"refresh");
}
});
});
</script>
This is my other function where i change the textbox value. it works actually with other values e.g. when i give hardcoded string value. I can see the value in the console but for some reason it gives me the error like :
here the string starts with B is AsinId where i take from amazon. I am definitely in need of help because i am totally stucked.
Uncaught ReferenceError: B00BMQRILU is not defined 62594001:1 onclick
<script type="text/javascript">
function someFunction(var1) {
tracktextbox = document.getElementsByName("trackId");
for (var i = 0; i < tracktextbox.length; i++) {
tracktextbox[i].value = var1;
}
$('#track').dialog('close');
}
</script>
The problem is '<h6><a href="#" onclick="someFunction('+trackId+ ')">', from the error it is clear that trackId is a string value, so you need to enclose it within "" or ''. So try
'<h6><a href="#" onclick="someFunction(\'' + trackId + '\')">'

Categories