Passing a parameter correctly - javascript

I have a function which loops through a list of json objects. It actually works, but it gives me this error: "Uncaught TypeError: Cannot read property 'values' of undefined" pointing to this line:
var resValues = result.values;
My code is:
function onLinkedInLoad() {
IN.Event.on(IN, "auth", onLinkedInAuth);
}
function onLinkedInAuth() {
var cpnyID = 2414183; //LinkedIn's testDevCo
IN.API.Raw("/companies/" + cpnyID + "/updates?event-type=status-update&start=0&count=10&format=json")
.result(displayUpdates);
}
function displayUpdates(result) {
var resValues = result.values;
for (var i in resValues) {
var share = resValues[i].updateContent.companyStatusUpdate.share;
console.log(share);
}
}
What do I need to change in order to fix this error?
The json looks something like this:
{
"values": [{
"updateContent": {
"companyStatusUpdate": {
"share": {
"content": {
"description": "Test description",
"eyebrowUrl": "http://linkd.in/…",
"shortenedUrl": "http://linkd.in/…",
"submittedImageUrl": "http://m.c.lnkd.licdn.com/…",
"submittedUrl": "http://linkd.in/…",
"thumbnailUrl": "https://media.licdn.com/…",
"title": "Best Advice: Take Jobs Others Don't Want"
}
}
}
}
}]
}
Thanks a lot in advance.

Turns out that this errors appeared because I was listing displayupdates further up in the head section where the api key is entered: I removed it so I only have:
<script type="text/javascript" src="https://platform.linkedin.com/in.js">
api_key: xxxxxxxxxxxxxxxx
**onLoad: onLinkedInLoad, onLinkedInAuth**
authorize: true
</script>

Related

Using Tabletop.js, trying to fetch data from array

Problem
Trying to fetch data from this array, which currently contains two objects. I'm using Tabletop.js to fetch the data from a public Google Spreadsheet, getting an error in the console that says ReferenceError: object is not defined
Console
[Object, Object]/*
*/0: Object
citation1url: "http://brandonsun.com"
citation2url: ""
citation3url: ""
datesaid: "2/20/2015"
explanation: ""
politicianname: "First Name, Last Name"
rowNumber: 1
statement: "This is my statement"
validity: "True, False, Unconfirmed"
*1: Object
citation1url: "http://andrewnguyen.ca"
citation2url: ""
citation3url: ""
datesaid: "2/20/2015"
explanation: ""
politicianname: "Andrew Nguyen"
rowNumber: 2
statement: "I work as a newsroom developer"
validity: "TRUE"
scripts.js
$(function() {
window.onload = function() { init() };
var public_spreadsheet_url = "https://docs.google.com/spreadsheets/d/1glFIExkcuDvhyu5GPMaOesB2SlJNJrSPdBZQxxzMMc4/pubhtml";
function init() {
Tabletop.init( { key: public_spreadsheet_url,
callback: showInfo,
simpleSheet: true } )
}
function showInfo(data, tabletop) {
// alert("Successfully processed!")
console.log(data);
}
});
I don't think you've defined data in that 2nd function showInfo.
I think the best way is to make a variable for your tabletop model, like
var tabletop = Tabletop.init( { key: public_spreadsheet_url, callback: function(data, tabletop) { console.log(data) }, simpleSheet: true });
Then you can call it:
$("#myDiv").html(tabletop.data()[1].Statement);

jQuery not generating my JSON

I am trying to generate a JSON document from a form. The output I want would look something like this:
{
"name": "joe-pc",
"device_type": "server",
"os": "windows",
"info": [
{
"net_info": [
{
"ip": "192.168.0.5",
"name": "eth0"
},
{
"ip": "192.168.0.28",
"name": "eth1"
}
]
},
{
"OS_info": [
{
"name": "windows"
},
{
"build": "123.1.3"
}
]
},
{
"whatever_info": [
{}
]
}
]
}
What I'm getting is:
{"info":[{}]}
Code Snips:
$('#top_three_next').click(function (e) {
var json_obj = new Object();
json_obj.name = $('#name').val(); //manditory
json_obj.device_type = $('#device_type').val(); //manditory
json_obj.os = $('#os').val(); //not a manditory field
// is this not available outside the function?
// even if I declare json_obj as a global var?
});
Full code:
http://jsfiddle.net/jdell64/Tu9bB/ (start at line 93 in the js pane).
First of all your code on jsfiddle looks a bit messy :)
I see
var json_obj = new Object();
declaration on line 95. This Line is not needed at all. Because you already defined empty json_obj at the beginning of your JS. And this declaration overheads global variable & uses local variable from callback scope & all data filled in it is missing after callback ends. If you remove that line you'll get the following structure at the end.
{"name":"1","device_type":"2","os":"3","info":[{}]}
EDITED:
Also lines 191-192 is totally unclear for me:
infoList.push(infoDocs);
json_obj.info = infoList;
Both infoDocs & infoList variables is not defined in event handler function, but they also not defined globally!

Custom Mode for Ace.js causes error "Uncaught TypeError: Cannot set property 'lastIndex' of undefined"

I'm creating a web application that will require users to be able to write code in my custom scripting language that is currently in development. I've used Cloud9's Ace editor in projects before. Since I'm used to Ace and know quite a bit about how to implement it, I decided it'd be a perfect fit to fulfill my needs for my script editor. However, in order to use a custom scripting language, I needed to create a custom Mode for Ace to use. Here is my mode, which is stored in a file in the ace_editor directory (same directory as ace.js is in):
ace.define('ace/mode/customscript', function (require, exports, module) {
var oop = require("ace/lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("ace/tokenizer").Tokenizer;
this.HighlightRules = require("ace/mode/customscript_highlight_rules").CustomScriptHighlightRules;
var Mode = function () {
this.$tokenizer = new Tokenizer(new HighlightRules().getRules());
};
oop.inherits(Mode, TextMode);
exports.Mode = Mode;
});
ace.define('ace/mode/customscript_highlight_rules', function (require, exports, module) {
var oop = require("ace/lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
/*var keywords = [
"null",
"new",
"task",
"end",
"if",
"else",
"elseif",
"and",
"or",
"not",
"then",
"for",
"loop",
"while",
"times",
"print",
"use",
"use_csharp",
"extend",
"as",
"return",
"continue",
"my"
];
var keywordsRegex = "";
for (var i = 0; i < keywords.length; i++) {
keywordsRegex = keywordsRegex + keywords[i] + "|";
}
keywordsRegex = keywordsRegex.substr(0, keywordsRegex.length - 1);*/
var CustomScriptHighlightRules = function () {
this.createKeywordMapper({
"variable.language": "this",
"keyword":
"new task end if else elseif and or not then for loop while times print use use_csharp extend as return continue my",
"constant.language":
"true false null"
}, "text", true, " ");
this.$rules = {
"no_regex": [
{
token: "comment",
regex: "(->)(.|[\r\n])*(<-)"
},
{
token: "comment",
regex: "--([^\n].*)"
},
{
token: "string",
regex: "(\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\")"
},
{
token: "numbers",
regex: "(\d)?[.]*(\d)*"
},
{
token: "booleans",
regex: "true|false"
}
]
};
};
oop.inherits(CustomScriptHighlightRules, TextHighlightRules);
exports.CustomScriptHighlightRules = CustomScriptHighlightRules;
});
And here is the code I'm using to test the editor:
<!DOCTYPE html>
<html>
<head>
<title>CustomScript Editor</title>
</head>
<body>
<div id="syntax_editor" style="width: 100%; height: 100%">task idk()
alert("hi")
end</div>
<script type="text/javascript">
$().ready(function () {
var editor = ace.edit("syntax_editor");
editor.setTheme("ace/theme/twilight");
editor.getSession().setMode("ace/mode/customscript");
editor.getSession().setUseWrapMode(false);
editor.getSession().setUseSoftTabs(true);
editor.getSession().setTabSize(4);
editor.setShowPrintMargin(false);
editor.setFadeFoldWidgets(false);
document.getElementById("syntax_editor").style.fontSize = 20 + 'px';
});
</script>
</body>
</html>
The problem is that I'm getting an error from Ace when I load the page that reads:
Uncaught TypeError: cannot set property 'lastIndex' of undefined
I am using Ace's latest src_noconflict library from GitHub. What am I doing wrong in my custom mode?
This is because "start" state is missing in your CustomScriptHighlightRules
change
this.$rules = {
"no_regex": [
to
this.$rules = {
"start": [

Function doesn't display data from JSON

In my webapp I have a page where I use getJSON to get data from server. Firebug shows that it get's JSON from server just the way it is supposed to, but no data is shown. What could be the problem? Here is what my code looks like:
$('#detailsPage').live('pageshow', function(event) {
var id = getUrlVars()["id"];
$.getJSON(serviceURL + 'getemployee.php?id='+id+'&callback=?', displayEmployee);
});
function displayEmployee(data) {
var employee = data.item;
$('#employeePic').attr('src', 'pics/' + employee.PIC);
$('#fullName').text(employee.NAME);
$('#employeeTitle').text(employee.TITLE);
$('#lisatieto').text(employee.INFO);
if (employee.puhelin_nro) {
$('#actionList').append('<li><h3>Soita puhelimeen</h3></li>');
$('#actionList').append('<li><h3>SMS</h3></li>');
}
$('#actionList').listview('refresh');
}
Console shows
employee is undefined
[Break On This Error]
$('#employeePic').attr('src', 'pics/' + employee.PIC);
This is the JSON response:
jQuery164008509381752724021_1336981793995({
"key": [
{
"PIC": "Tuntematon",
"NAME": "0",
"TITLE": "0",
"INFO": "0"
}
]
})
You need to use this
var employee = data.key[0];

Mustache templating - presenting JSON collection

I am attempting to present a JSON collection, which is retrieved asynchronously and using FireBug I can see this ultimately looks like:
[{"Id":"00000010"},{"Id":"00000002"},{"Id":"00000003"}]
This does not work, but if I declare a collection as:
[{ "Id": "00000004" }, { "Id": "00000005" }, { "Id": "00000006"}]
This works, and then using FireBug I can see this is slightly different:
[Object { Id="00000004"}, Object { Id="00000005"}, Object { Id="00000006"}]
Why does it make a difference when retrieving the data synchronously and declaring a collection? What are my options for getting this to work.
Thanks.
UPDATE
I am also using sammy.js, here is the JavaScript:
var app = $.sammy('div[role="main"]', function () {
this.use('Mustache', 'html');
this.get('#/', function (context) {
this.load('/data')
.then(function (response) {
context.blah = 'blah';
context.data = response;
var data2 = [{ "Id": "00000004" }, { "Id": "00000005" }, { "Id": "00000006"}];
context.data2 = data2;
var templateUrl = '#Url.Content("~/Templates/template.html")';
context.partial(templateUrl);
});
});
});
$(function () {
app.run('#/');
});
Here is the template:
<h1>{{blah}}</h1>
<ul>
{{#data}}
<li>{{Id}}</li>
{{/data}}
</ul>
<ul>
{{#data2}}
<li>{{Id}}</li>
{{/data2}}
</ul>
Okay, I figured this one out!
context.data = response;
becomes
context.data = JSON.parse(response);

Categories

Resources