Displaying information from a JSON on map using wrong method? - javascript

I'm working through a project to show information from a third party api on a map.
I'm not very experienced figuring out what the console is telling me so I'm a little stuck on the error I'm getting. I've declared all the variables outside of the function so result is defined and all of these functions are aspects of a foursquare venue.
Uncaught TypeError: Cannot read property 'hasOwnProperty' of undefined
$.ajax({
url:'https://api.foursquare.com/v2/venues/search',
dataType: 'json',
data: 'limit=1' +
'&ll='+ placeItem.lat() +','+ placeItem.lng() +
'&client_id='+ CLIENT_ID +
'&client_secret='+ CLIENT_SECRET +
'&v=20140806' +
'&m=foursquare',
async: true,
success: function (data) {
result = data.response.venue;
contact = result.hasOwnProperty('contact') ? result.contact : '';
if (contact.hasOwnProperty('formattedPhone')) {
placeItem.phone(contact.formattedPhone || '');
}
location = result.hasOwnProperty('location') ? result.location : '';
if (location.hasOwnProperty('address')) {
placeItem.address(location.address || '');
}
bestPhoto = result.hasOwnProperty('bestPhoto') ? result.bestPhoto : '';
if (bestPhoto.hasOwnProperty('prefix')) {
placeItem.photoPrefix(bestPhoto.prefix || '');
}
if (bestPhoto.hasOwnProperty('suffix')) {
placeItem.photoSuffix(bestPhoto.suffix || '');
}
description = result.hasOwnProperty('description') ? result.description : '';
placeItem.description(description || '');
rating = result.hasOwnProperty('rating') ? result.rating : '';
placeItem.rating(rating || 'none');
url = result.hasOwnProperty('url') ? result.url : '';
placeItem.url(url || '');
placeItem.canonicalUrl(result.canonicalUrl);
// Infowindow code is in the success function so that the error message
// Content of the infowindow
contentString = '<div id="iWindow"><h4>' + placeItem.name() + '</h4><div id="pic"><img src="' +
placeItem.photoPrefix() + '110x110' + placeItem.photoSuffix() +
'" alt="Image Location"></div><p>Information from Foursquare:</p><p>' +
placeItem.phone() + '</p><p>' + placeItem.address() + '</p><p>' +
placeItem.description() + '</p><p>Rating: ' + placeItem.rating() +
'</p><p><a href=' + placeItem.url() + '>' + placeItem.url() +
'</a></p><p><a target="_blank" href=' + placeItem.canonicalUrl() +
'>Foursquare Page</a></p><p><a target="_blank" href=https://www.google.com/maps/dir/Current+Location/' +
placeItem.lat() + ',' + placeItem.lng() + '>Directions</a></p></div>';
// Add infowindows
google.maps.event.addListener(placeItem.marker, 'click', function () {
infowindow.open(map, this);
// Bounce animation
placeItem.marker.setAnimation(google.maps.Animation.BOUNCE);
setTimeout(function () {
placeItem.marker.setAnimation(null);
}, 800);
infowindow.setContent(contentString);
});
},
// Alert the user on error.
error: function (e) {
infowindow.setContent('<h5>Foursquare data is unavailable.</h5>');
document.getElementById("error").innerHTML = "<h4>Foursquare data is unavailable. Please try refreshing.</h4>";
}
});

Not sure what data the call you are making is supposed to return but the error you are getting indicates that you did not get the data you were expecting.
result = data.response.venue;
"venue" is not a defined property of data.response so when you try and access result.hasOwnProperty('contact') it has no idea what to return since result is not defined.

Related

when parsing json data throwing error

I am adding Json data to html div and parsing.it is working fine in local.but it is throwing error when we are running file from server .the error is "unexpected token o".
var data = $.parseJSON($("#json-data").html());
//console.log(data);
var now = new Date();
var events = [];
if (data != undefined && data.results.assets.length > 0) {
var dayevents = [];
$.each(data.results.assets, function(i, entry) {
var d = entry.metadata.EventDate;
$('#calender-list').append('<div class="events-list-main"><div class="events-list"><div class="event-title">' + entry.metadata.EventName + '</div><div class="event-addr">' + (entry.metadata.EventDate) + '-' + (entry.metadata.EventEndDate). + ' ' + (entry.metadata.EventEndDate). + '<br/>' + entry.metadata.EventAddress + '</div><div class="event-desc">' + entry.metadata.EventDesc + '</div>SEE EVENT WEBSITE<em class="icon-go"></em></div></div>');
});
}
fiddle
There are .+ at (entry.metadata.EventEndDate). +.
They should be something like (entry.metadata.EventEndDate) + '<br/>'
fiddle

sometimes ajax works & sometime not & click on row function is also not working

can we write two ajax success function on same page because sometimes its work sometime not
doajaxpost function is to load data in 2nd dropdown list when 1st dropdown list onchange function call by using ajax
and searching function is to load data in table by using ajax
but it sometime get execute properly sometimes not showing any result
function doAjaxPost(instituteId) {
alert(instituteId);
// get the form values
/* var name = $('#name').val();
var education = $('#education').val(); */
$.ajax({
type : "POST",
url : "/paymentGateway/merchant",
dataType : "json",
data : "institutionId=" + instituteId,
success : function(data) {
// we have the response
alert(data + "hiee");
var $merchantId = $('#merchant');
$merchantId.find('option').remove();
$("#merchant").append("<option value='ALL'>ALL</option>");
$.each(data, function(key, value) {
$('<option>').val(value.merchantId).text(value.merchantId)
.appendTo($merchantId);
});
},
error : function(e) {
alert('Error: ' + e);
}
});
}
function searching() {
// get the form values
var institutionId = $('#instiuteId').val();
var merchantId = $('#merchant').val();
var userType = $('#userType').val();
var userStatus = $('#userStatus').val();
var userId = $('#userId').val();
alert("insti=" + institutionId + "mecrhant=" + merchantId + "usertyep="
+ userType + "users=" + userStatus + "userid=" + userId);
$.ajax({
type : "POST",
url : "/paymentGateway/searching",
dataType : "json",
data : {
institutionId : institutionId,
merchantId : merchantId,
userId : userId,
userStatus : userStatus,
userType : userType
},
success : function(data) {
// we have the response
alert(data);
/* var $merchantId = $('#dynamictable');
$merchantId.find('table').remove();
$('#dynamictable').append('<table></table>');
var table = $('#dynamictable').children(); */
$("#tablenew tbody tr:has(td)").remove();
$.each(data, function(key, value) {
/* alert(value.institutionId); */
$('#tablenew tbody:last').append(
"<tr><td>" + value.userId + "</td><td>"
+ value.firstName + "</td><td>"
+ value.userStatus + "</td><td>"
+ value.userType + "</td><td>"
+ value.userAddedBy + "</td><td>"
+ value.userRegisteredDateTime
+ "</td><td>" + value.recordLastUpdatedBy
+ "</td><td>" + value.recordLastUpdatedTime
+ "</td></tr>");
});
},
error : function(e) {
alert('Error: ' + e);
}
});
}
It could be a caching issue, try to setup
$.ajaxSetup({ cache: false });
See
How to prevent a jQuery Ajax request from caching in Internet Explorer?
I got the same problem. You'll have to use the class instead of ID to make it work. Use $(".merchant") to replace $("#merchant"), and update 'merchant' to be a class.

ContextMenuItem context function is not executing

I want my context menu item to be visible only if the clicked node is a link i.e. and href is either a magnet link or a torrent link. But item is visible for all the links because context function is not executing, can anybody help why context function is not executing?
Here is the code:
exports.main = function() {
var cm = require("sdk/context-menu");
var contextCode = ' self.on("context", function (node) { '+
' while(node.nodeName!="A") { node = node.parentNode; } '+
' var pat_magnet = /^magnet:/i; ' +
' var pat_torrent = /.torrent$/i; ' +
' if(pat_torrent.test(node.href) || pat_magnet.test(node.href)) { return true; } '+
' else { return false; } '+
' }); ';
var clickCode = ' self.on("click", function(node,data){ '+
' while(node.nodeName!="A") { node = node.parentNode; } '+
' var pat_hash = /[0-9abcdef]{32,40}/i; ' +
' var result = node.href.match(pat_hash); '+
' var hash = "" '
' if(result != null) { hash=result[0]; } '+
' var xhr = new XMLHttpRequest(); '+
' if(hash != "") { '+
' var apiCall = "https://www.furk.net/api/dl/add?api_key=*************&info_hash="+hash; '+
' } '+
' else{ '+
' var apiCall = "https://www.furk.net/api/dl/add?api_key=*************&url="+encodeURI(node.href); '+
' } '+
' xhr.open("GET",apiCall,true); '+
' xhr.onreadystatechange = function(){ if(xhr.readyState = 4) { if (xhr.response.status = "ok") { alert("Torrent added to Furk."); } else { alert("Torrent could not be added to Furk."); } } } '+
' xhr.send(null); '+
' });';
cm.Item({
label: "Add to Furk",
context: cm.SelectorContext("a[href]"),
contentScript: contextCode + clickCode
});
};
Please always post self-containied examples that can be directly tried in the future.
Now back to your problem: The content script actually has a syntax error.
The following line:
' var pat_torrent = /.torrent$/i ' +
lacks a semicolon, and should be:
' var pat_torrent = /.torrent$/i; ' +
The reason automatic semicolon insertion (ASI) does not work here is: The "code" is actually a string that has no newlines in it whatsoever. If there were newlines, then ASI would have worked.
Anway, another reason not to have complex content script inline. Have a look at contentScriptFile.
This error is actually logged, but the presentation sucks. In the Browser Console:
[20:57:51.707] [object Error] (expandable)
In terminal:
console.error: context-magnet:
Message: SyntaxError: missing ; before statement
Here is a fixed, reproducible sample:
var cm = require("sdk/context-menu");
var contextCode = ' self.on("context", function (node) { '+
' while(node.nodeName!="A") { node = node.parentNode; } '+
' var pat_magnet = /^magnet:/i; ' +
' var pat_torrent = /.torrent$/i; ' +
' if(pat_torrent.test(node.href) || pat_magnet.test(node.href)) { return true; } '+
' else { return false; } '+
' }); ';
cm.Item({
label: "magnet test",
context: cm.SelectorContext("a[href]"),
contentScript: contextCode
});
Edit ' var hash = "" ' has the same problem, and there are might be other such errors that I missed skimming this new code.
As I already said, please use contentScriptFile and not contentScript for long-ish scripts.
Another edit
Here is a builder using contentScriptFile, where I also fixed a couple of other errors, the most important of which are:
Use permissions so that the XHR will work.
Correctly set up the XHR to use responseType and overrideMimeType().
Use onload/onerror instead of onreadystatechange.

Uncaught TypeError: Cannot set property '0' of undefined

I am using Facebooks Javascript API to import to my website the albums and photos of a Facebook page.
My javascript code looks like this :
<script>
var albumPhotos = new Array();
var albumThumbnails = new Array();
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : '5698434687426', // App ID from the app dashboard
channelUrl : 'channel.html', // Channel file for x-domain comms
status : true, // Check Facebook Login status
xfbml : true // Look for social plugins on the page
});
// Additional initialization code such as adding Event Listeners goes here
FB.api('1607099163/albums', function(response) {
if(!response || response.error) {
// render error
alert("Noo!!");
} else {
// render photos
for(var i=0; i<response.data.length; i++){
(function (i) {
var albumName = response.data[i].name;
var albumCover = response.data[i].cover_photo;
var albumId = response.data[i].id;
var numberOfPhotos = response.data[i].count
FB.api(albumId + "/photos", function(response) {
if(!response || response.error) {
// render error
alert("Noo!!");
} else {
for(var k=0; k<numberOfPhotos; k++){
albumThumbnails[i][k] = response.data[k].picture;
albumPhotos[i][k] = response.data[k].source;
}
}
});
console.log(albumName);
FB.api( albumCover, function(response) {
if(!response || response.error) {
// render error
alert("Noo!!");
} else {
// render photos
$(".albums").append('<li>'+
'<a href="#Gallery' + i + '"' + 'data-transition="slidedown">'+
'<img src= "' + response.picture + '" />'+
'<h2>' + albumName + '</h2>'+
'<p>' + "Number of Photos: " + numberOfPhotos +'</p>'+
'</a>'+
'</li>')
.listview('refresh');
$("#home").after('<div data-role="page" data-add-back-btn="true" id=Gallery'+ i +
' class="gallery-page"> ' +
' <div data-role="header"></div> ' + ' <div data-role="content"> ' +
' <ul class="gallery"></ul> ' + ' </div> ' +
' </div> ');
}
});
})(i);
} //end of for loop
}
});
};
As you can see in the beginning i use the API to get information about the albums of the specific page : FB.api('169070991963/albums', function(response) {...}
Everything works as expected and i can get information as albumNames , albumCovers , albumIds etc .
Now for every album that i import , i want to have an array where i will save all of its pictures and thumbnails. For this reason i make another API call , FB.api(albumId + "/photos", function(response) {} .
I process the response like this :
for(var k=0; k<numberOfPhotos; k++){
albumThumbnails[i][k] = response.data[k].picture;
albumPhotos[i][k] = response.data[k].source;
}
At this point though i get the error : Uncaught TypeError: Cannot set property '0' of undefined
I cant understand what is undefined though... Any idea on this ?
*By the way the next API call that i make FB.api( albumCover, function(response) {..} to get the cover photos of the albums and create a jquery mobile listView , works too.
EDIT
The answer provided below solved the 2-dimensional table problem.
However now the error is : Uncaught TypeError: Cannot read property 'picture' of undefined
EDIT2
I am experiencing the same issue later in the code so i am making this EDIT. The code now looks as suggested like this :
<script>
var albumPhotos = new Array();
var albumThumbnails = new Array();
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : '564984346887426', // App ID from the app dashboard
channelUrl : 'channel.html', // Channel file for x-domain comms
status : true, // Check Facebook Login status
xfbml : true // Look for social plugins on the page
});
// Additional initialization code such as adding Event Listeners goes here
FB.api('169070991963/albums', function(response) {
if(!response || response.error) {
// render error
alert("Noo!!");
} else {
// render photos
for(var i=0; i<response.data.length; i++){
(function (i) {
var albumName = response.data[i].name;
var albumCover = response.data[i].cover_photo;
var albumId = response.data[i].id;
var numberOfPhotos = response.data[i].count;
FB.api(albumId + "/photos", function(response) {
if(!response || response.error) {
// render error
alert("Noo!!");
} else {
for(var k=0; k<response.data.length; k++){
albumThumbnails[i] = albumThumbnails[i]||{};
albumThumbnails[i][k] = response.data[k].picture;
albumPhotos[i] = albumPhotos[i] || {};
albumPhotos[i][k] = response.data[k].source;
}
}
});
console.log(albumName);
FB.api( albumCover, function(response) {
if(!response || response.error) {
// render error
alert("Noo!!");
} else {
// render photos
$(".albums").append('<li>'+
'<a href="#Gallery' + i + '"' + 'data-transition="slidedown">'+
'<img src= "' + response.picture + '" />'+
'<h2>' + albumName + '</h2>'+
'<p>' + "Number of Photos: " + numberOfPhotos +'</p>'+
'</a>'+
'</li>')
.listview('refresh');
$("#home").after('<div data-role="page" data-add-back-btn="true" id=Gallery'+ i +
' class="gallery-page"> ' +
' <div data-role="header"><h1>Gallery</h1></div> ' + ' <div data-role="content"> ' +
' <ul class="gallery"></ul> ' + ' </div> ' +
' </div> ');
for(var x=0; x < albumPhotos[i].length; x++)
$('#Gallery' + i + ' .gallery').append('<li><img src="' + albumThumbnails[i][x] + '" /></li>');
}
});
})(i);
} //end of for loop
console.log(albumPhotos);
console.log(albumThumbnails);
}
});
};
I added this piece of code as you see :
for(var x=0; x < albumPhotos[i].length; x++)
$('#Gallery' + i + ' .gallery').append('<li><img src="' + albumThumbnails[i][x] + '" /></li>');
Every row in the 2dimensional table albumPhotos is an album and every column is a photo inside this album. With the for loop above i tried to create a list of Galleries that every Gallery has an album with all its photos.
Again i get the error :
Uncaught TypeError: Cannot read property '0' of undefined
Uncaught TypeError: Cannot read property '1' of undefined
Uncaught TypeError: Cannot read property '2' of undefined
Uncaught TypeError: Cannot read property '3' of undefined
.
.
.
Why do i get this now?
You have albumThumbnails and albumPhotos as empty arrays, and in the loop you are trying to add values into the array.
let us take the case where i = 0 your array albumThumbnails has a length of 0 that means albumThumbnails[0] is undefined, then you are trying to set albumThumbnails[0][0] which is giving the error.
The solution here is to first create an empty object at the index i if required then set its property
Looks like you are trying to create the object here
for(var k=0; k<numberOfPhotos && k < response.data.length; k++){
albumThumbnails[i] = albumThumbnails[i]||{};
albumThumbnails[i][k] = response.data[k].picture;
albumPhotos[i] = albumPhotos[i] || {};
albumPhotos[i][k] = response.data[k].source;
}

Extension stopped working with Google Chrome manifest v2

I am developing an extension for Google Chrome that was working perfectly, but now stopped working with version 2 of the manifest.
It is giving me the following error:
Uncaught SyntaxError: Unexpected end of input
popup.js:
chrome.tabs.getSelected(null, function (aba) {
link = aba.url;
titulo = aba.title;
document.getElementById('mensagem').value = link;
});
function GrabIFrameURL(feedDescription) {
var regex = new RegExp("iframe(?:.*?)src='(.*?)'", 'g');
var matches = regex.exec(feedDescription);
var url = '';
if (matches.length == 2) {
url = matches[1];
}
var quebra = url.split("/");
return quebra[4];
}
$(document).ready(function () {
if (localStorage.nome == '' || localStorage.nome == null || localStorage.email == '' || localStorage.email == null) {
jQuery('#formulario').hide();
jQuery('#erros').html('Configure seus dados aqui');
}
jQuery("#resposta").ajaxStart(function () {
jQuery(this).html("<img src='img/loading.gif'> <b>Sugestão sendo enviada, aguarde...</b>");
});
jQuery('#submit').click(function () {
var nome = localStorage.nome;
var email = localStorage.email;
var mensagem = titulo + "\n\n<br><br>" + link;
jQuery('#formulario').hide();
jQuery.post('http://blabloo.com.br/naosalvo/mail.php', {
nome: nome,
email: email,
mensagem: mensagem
},
function (data, ajaxStart) {
jQuery('#resposta').html(data);
console.log(data);
});
return false;
});
//Listagem de posts
var bkg = chrome.extension.getBackgroundPage();
jQuery('#close').click(function () {
window.close();
});
jQuery('#markeall').click(function () {
bkg.lidoAll();
$('.naolido').attr('class', 'lido');
});
jQuery.each(bkg.getFeed(), function (id, item) {
if (item.naolido == '1')
lidoClass = 'naolido';
else
lidoClass = 'lido';
var thumb = GrabIFrameURL(item.description);
$('#feed').append('<li><a id="' + item.id + '" href="' + item.link + '" class="' + lidoClass + '"><img src="' + $.jYoutube(thumb, 'small') + '" class="' + lidoClass + '"/>' + item.title + '</a></li>');
});
$('.naolido').click(function (e) {
e.preventDefault();
klicked = $(this).attr('id');
console.log(klicked);
bkg.setLido(klicked);
$(this).attr('class', 'lido');
openLink($(this).attr('href'));
});
$('.lido').click(function (e) {
openLink($(this).attr('href'));
});
var openLink = function (link) {
chrome.tabs.create({
'url': link,
'selected': true
});
window.close();
}
});
I think the problem is in this part of popup.js:
jQuery.each(bkg.getFeed(), function (id, item) {
if (item.naolido == '1')
lidoClass = 'naolido';
else
lidoClass = 'lido';
var thumb = GrabIFrameURL(item.description);
$('#feed').append('<li><a id="' + item.id + '" href="' + item.link + '" class="' + lidoClass + '"><img src="' + $.jYoutube(thumb, 'small') + '" class="' + lidoClass + '"/>' + item.title + '</a></li>');
});
You problem is actually in background.js on lines 12 and 20, you set localStorage.items to '' initially but then try to run a JSON.parse() on it later, but it's not JSON data so JSON.parse returns Unexpected end of input. And, JSON.parse isn't a function you define but a native browser function so, it shows the error as being on "line 1".
Try defining it as an empty array initially and then "pushing" to it as you are now.

Categories