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);
Related
<script>
$.getJSON('chartState',{
stateCode : $(this).val(),
ajax : 'true'
},
function(data) {
alert("state data"+data);
});
</script>
I have the value in data and want to show in javascript given below.
The fields data is given want to push my state data there.
<script>
var salesChartData = {
datasets: [{
data: ["here i want my data"]
}]
};
</script>
Both are written in diffrent script
datasets is an array with an object on index 0. So to define or redeclare the data property in there the syntax is
salesChartData.datasets[0].data = data;
Use it in your callback function:
function(data) {
salesChartData.datasets[0].data = data;
});
Not sure if I understand correctly, is this what you need?
var salesChartData = {
datasets: [
{
data : {}
}
]
};
$.getJSON('chartState',{
stateCode : $(this).val(),
ajax : 'true'
},
function(data) {
salesChartData.datasets[0].data = data;
});
Just set the data after receiving it
if you need to show the ajax result in a variable salesChartData, you can try this
salesChartData.datasets[0].data[0] = "new data"
salesChartData is a JSON object with key datasets contains an array of JSON objects.
So if salesChartData is declared globally, then you can replace in the success of the ajax
Here below, it done using web storage. This is used to access from different file.
// File 1
var salesChartData = {
datasets: [{
data: ["here i want my data"]
}]
};
localStorage.setItem("salesChart", JSON.stringify(salesChartData));
//-----------------------------------------------------------------------
// File 2
var salesChartData = JSON.parse(localStorage.getItem("salesChart"));
// ajax call
$.getJSON('chartState', {
stateCode: $(this).val(),
ajax: 'true'
},
function (data) {
alert("state data" + data);
salesChartData.datasets[0].data[0] = data // "new data"
});
Hope this will work.
Thank You
I have done with my self
$.getJSON('chartState',{
stateCode : $(this).val(),
ajax : 'true'
},
function(data) {
var chr=data;
var a=chr[0];var b=chr[1];var c=chr[2];var d=chr[3];
var e=chr[4];var f=chr[5];var g=chr[6];
After that I have sended one by one data
var salesChartData = {
datasets: [
{
data : [g,f,e,d,c,b,a]
}
]
};
As you mention that both parts of the script are in different tags you can solve the problem with a global, this is not recommended. The better solution would be to refactor the structure and not have multiple script tags. But if you have no control over this then you should do something like this:
<script>
// No var used to make it global
chart_state_data = false;
$.getJSON('chartState',{
stateCode : $(this).val(),
ajax : 'true'
},
function(data) {
// the data is set to this variable on callback
chart_state_data = data
});
</script>
And:
<script>
// chart_state_data contains data retrieved from ajax call or false
var salesChartData = {
datasets: [{
data: chart_state_data
}]
};
</script>
I'm having trouble binding my JavaScript kendo ui grid to model data from an action method. All the examples i see are mostly MVC wrappers and the JavaScript examples are all different and none seem to work for me.
Here is where i'm at below.
I did a generic test with static data that works.
var dataSource_Test = new kendo.data.DataSource({
data: [{ LeagueDetailGroupId: "15", GroupName: "Best Team 5"}]
});
Here is the datasource object im trying to create with the controller action:
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "#Url.Action("LeagueDetailGroup_Read", "Configuration")?_leagueTypeId=" + leagueTypeId,
// i have tried all kinds of variants here, and not sure what to put
// my action method is returning json using kendo's DataSourceResult method
//contentType: "application/json",
type: "POST"
//dataType: "odata"
},
schema: {
data: "Data", // seen this in examples, dunno what it does
total: "Total", // seen this in examples, dunno what it does
model: {
id: "LeagueDetailGroupId",
fields: {
LeagueDetailGroupId: { editable: false, nullable: true },
GroupName: { validation: { required: true } }
}
}
},
// i seen this is an example from telerik but dont understand the use case for it
parameterMap: function (data, operation) {
// this prints no data before i even start so its a moot point configuring it from products to my stuff at this moment
// but not sure what todo here of if i need this anyways
console.log(data);
if (operation != "read") {
// post the products so the ASP.NET DefaultModelBinder will understand them
var result = {};
for (var i = 0; i < data.models.length; i++) {
var product = data.models[i];
for (var member in product) {
result["products[" + i + "]." + member] = product[member];
}
}
return result;
} else {
return JSON.stringify(data)
}
}
}
});
Here is the grid which works ok with the generic static datasouce object.
var grid = $("#leagueEdit_ldg_grid").kendoGrid({
dataSource: dataSource,
sortable: true,
pageable: true,
autobind: false,
//detailInit: leagueEdit_ldg_detailInit,
dataBound: function () {
this.expandRow(this.tbody.find("tr.k-master-row").first());
},
columns: [
{
field: "LeagueDetailGroupId",
title: "Group Id",
width: "110px"
},
{
field: "GroupName",
title: "Group Name",
width: "110px"
}
]
});
Delayed read, autobind set to false.
dataSource.read();
Here is my simplified Controller action. It runs and gets data, and works fine for my MVC wrapper grids.
[Route("LeagueDetailGroup_Read/{_leagueTypeId:int}")]
public ActionResult LeagueDetailGroup_Read([DataSourceRequest]DataSourceRequest request, int _leagueTypeId = -1)
{
DataSourceResult result =
_unitOfWork.FSMDataRepositories.LeagueDetailGroupRepository.Get(
ld => ld.LeagueTypeId == _leagueTypeId
)
.ToDataSourceResult(request,
ld => new LeagueDetailGroupViewModel
{
LeagueDetailGroupId = ld.LeagueDetailGroupId,
LeagueTypeId = ld.LeagueTypeId,
GroupName = ld.GroupName,
DateCreated = ld.DateCreated,
DateLastChanged = ld.DateLastChanged
}
);
// data looks fine here
return Json(result, JsonRequestBehavior.AllowGet);
}
Currently i'm getting this error:
Uncaught TypeError: e.slice is not a function
at init.success (kendo.all.js:6704)
at success (kendo.all.js:6637)
at Object.n.success (kendo.all.js:5616)
at i (jquery-3.1.1.min.js:2)
at Object.fireWith [as resolveWith] (jquery-3.1.1.min.js:2)
at A (jquery-3.1.1.min.js:4)
at XMLHttpRequest.<anonymous> (jquery-3.1.1.min.js:4)
It's hard to know without testing but let me know how this works.
Change your controller so that you are just returning a json string.
Also, try removing your schema and the parameter map, and set your dataType to json:
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "#Url.Action("LeagueDetailGroup_Read", "Configuration")?_leagueTypeId=" + leagueTypeId,
dataType: "json"
}
}
});
For the grid I find simple json data does not usually need a schema/model defined. Kendo is super annoying and hard to debug. Let me know how it goes.
In my experience, an e.slice error happens when you have a record that has a null value in it somewhere. The kendo grid is not really smart enough to deal with this so you either have to make sure your datasource returns empty strings instead of nulls for string fields, or put a client template on the columns that translates a null into an empty string. It's possible that the kendo todatasourceresult made the problem come to light. Note that that is usually the last step before returning your dataset since it can modify the entity queries to give paging, so that you never query more than a single page of data (for ajax grids).
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>
Below is the structure of JSON which I use to query an API
"order_items": [
{
"menu_item_id": "VD1PIEBIIG",
"menu_item_name": "Create Your Own",
"modifiers": [
{
"modifier_id": "6HEK9TXSBQ",
"modifier_name": "Shrimp"
}
],
"quantity": "1",
"total": 15.99,
"variant_id": "TXDOR7S83E",
"variant_name": "X-Lg 18\""
}
]
Now I want to call this API from an HTML page using Javascript(Using HTML elements like forms and drop down menus etc). I want to create a Javascript object with proper structure and then convert it to JSON using "stringify" function. But I am not able to create the Javascript object. Can anyone help with this?
Like i want to have the following structure
obj.order_items[0].menu_item_id="VD1PIEBIIG";
obj.order_items[0].menu_item_name="Create Your Own";
obj.order_items[0].modifiers[0].modifier_id="6HEK9TXSBQ";
and so on.
var jsonToSend = { "order_items": [ ] };
// then for each order item
var orderItem = { "menu_item_id": <whatever>,
"menu_item_name": <whatever>,
"quantity": <whatever>,
"total": <whatever>,
"variant_id": <whatever>,
"variant_name": <whatever>,
"modifiers": []
};
// then for each modifier
var modifier = { "modifier_id": <whatever>, "modifier_name": <whatever> };
orderItem.modifiers.push(modifier);
jsonToSend.order_items.push(orderItem);
JSON.stringify(jsonToSend);
Well there are a couple of ways to do this.
Manually create the Json object to send from the HTML elements:
$.ajax({
type: "POST",
url: "some.php",
data: new {"order_items": [
{
"total": $('total').Val(),
"variant_id": $('variant_id').Val(),
"variant_name": $('variant_name').Val()
}
]})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
You could use a great framework like KnockoutJs, this will keep your JSON object up to date with your form, so that you don't have to do it manually. When you are ready you just submit your original json back to the server.
See this basic example on JsFiddle
var ClickCounterViewModel = function() {
this.numberOfClicks = ko.observable(0);
this.registerClick = function() {
this.numberOfClicks(this.numberOfClicks() + 1);
};
this.resetClicks = function() {
this.numberOfClicks(0);
};
this.hasClickedTooManyTimes = ko.computed(function() {
return this.numberOfClicks() >= 3;
}, this);
};
ko.applyBindings(new ClickCounterViewModel());
You can use any number of plugins to Serialize the form, but the problem is getting the JSON structure just right.
See SerializeArray
$( "form" ).submit(function( event ) {
console.log( $( this ).serializeArray() );
event.preventDefault();
});
I am trying to use twitter bootstrap to get the manufacturers from my DB.
Because twitter bootstrap typeahead does not support ajax calls I am using this fork:
https://gist.github.com/1866577
In that page there is this comment that mentions how to do exactly what I want to do. The problem is when I run my code I keep on getting:
Uncaught TypeError: Cannot call method 'toLowerCase' of undefined
I googled around and came tried changing my jquery file to both using the minified and non minified as well as the one hosted on google code and I kept getting the same error.
My code currently is as follows:
$('#manufacturer').typeahead({
source: function(typeahead, query){
$.ajax({
url: window.location.origin+"/bows/get_manufacturers.json",
type: "POST",
data: "",
dataType: "JSON",
async: false,
success: function(results){
var manufacturers = new Array;
$.map(results.data.manufacturers, function(data, item){
var group;
group = {
manufacturer_id: data.Manufacturer.id,
manufacturer: data.Manufacturer.manufacturer
};
manufacturers.push(group);
});
typeahead.process(manufacturers);
}
});
},
property: 'name',
items:11,
onselect: function (obj) {
}
});
on the url field I added the
window.location.origin
to avoid any problems as already discussed on another question
Also before I was using $.each() and then decided to use $.map() as recomended Tomislav Markovski in a similar question
Anyone has any idea why I keep getting this problem?!
Thank you
Typeahead expect a list of string as source
$('#manufacturer').typeahead({
source : ["item 1", "item 2", "item 3", "item 4"]
})
In your case you want to use it with a list of objects. This way you'll have to make some changes to make it works
This should works :
$('#manufacturer').typeahead({
source: function(typeahead, query){
$.ajax({
url: window.location.origin+"/bows/get_manufacturers.json",
type: "POST",
data: "",
dataType: "JSON",
async: false,
success: function(results){
var manufacturers = new Array;
$.map(results.data.manufacturers, function(data){
var group;
group = {
manufacturer_id: data.Manufacturer.id,
manufacturer: data.Manufacturer.manufacturer,
toString: function () {
return JSON.stringify(this);
},
toLowerCase: function () {
return this.manufacturer.toLowerCase();
},
indexOf: function (string) {
return String.prototype.indexOf.apply(this.manufacturer, arguments);
},
replace: function (string) {
return String.prototype.replace.apply(this.manufacturer, arguments);
}
};
manufacturers.push(group);
});
typeahead.process(manufacturers);
}
});
},
property: 'manufacturer',
items:11,
onselect: function (obj) {
var obj = JSON.parse(obj);
// You still can use the manufacturer_id here
console.log(obj.manufacturer_id);
return obj.manufacturer;
}
});
In my case, I was getting this exact error, and it turned out that the version of Bootstrap I was using (2.0.4) did not support passing in a function to the source setting.
Upgrading to Bootstrap 2.1.1 fixed the problem.
UPDATED / REVISED LOOK AT THE ISSUE: The error you mentioned "Cannot call method 'toLowerCase' of undefined" occurred to me when I used the original Typeahead extension in bootstrap that does not support AJAX. (as you have found) Are you sure that the original typeahead extension isn't loading, instead of your revised one?
I have been sucessfully using this Gist of typeahead that is a slight variation on the one you mention. Once I switched to that Gist and confirmed that the input data was good (testing that the input was a string array in an JS object, the issue went away.
Hope this helps
Original answer:
The reason the error occurs is because the value passed into the typeahead matcher function is undefined. That is just a side effect to the real issue which occurs somewhere between your input and that matcher function. I suspect the 'manufacturers' array has a problem. Test it first to verify you have a valid array.
// It appears your array constructor is missing ()
// try the following in your binding code:
var manufacturers = new Array();
Here is what I am using to bind the input to typeahead. I confirmed that it works with your modified typeahead fork.
My HTML:
<!-- Load bootstrap styles -->
<link href="bootstrap.css" rel="stylesheet" type="text/css" />
...
<input type="text" class="typeahead" name="Category" id="Category" maxlength="100" value="" />
...
<!-- and load jQuery and bootstrap with modified typeahead AJAX code -->
<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="bootstrap-modified-typeahead.js" type="text/javascript"></script>
My binding JavaScript code:
// Matches the desired text input ID in the HTML
var $TypeaheadInput = $("#Category");
// Modify this path to your JSON source URL
// this source should return a JSON string array like the following:
// string[] result = {"test", "test2", "test3", "test4"}
var JsonProviderUrl = "../CategorySearch";
// Bind the input to the typeahead extension
$TypeaheadInput.typeahead({
source: function (typeahead, query) {
return $.post(JsonProviderUrl, { query: query }, function (data) {
return typeahead.process(data);
});
}
});
In my case I had null values in my source array causing this error.
Contrived example:
source : ["item 1", "item 2", null, "item 4"]
Your manufacturer objects don't have a "name" property, you should change
property: 'name',
to
property: 'manufacturer',
Have you tried using mapping variables like example below, you need to use this when you got more then one property in your object;
source: function (query, process) {
states = [];
map = {};
var data = [
{"stateCode": "CA", "stateName": "California"},
{"stateCode": "AZ", "stateName": "Arizona"},
{"stateCode": "NY", "stateName": "New York"},
{"stateCode": "NV", "stateName": "Nevada"},
{"stateCode": "OH", "stateName": "Ohio"}
];
$.each(data, function (i, state) {
map[state.stateName] = state;
states.push(state.stateName);
});
process(states);
}
I stumbled upon this issue a while ago. I advice you to recheck configuration where you are including typeahead libraries (via main.js, app.js or config.js).
Otherwise, you can overwrite the latest Bootstrap version to your application library.
Try this code:
String.prototype.hashCode = function(){
var hash = 0;
if (this.length == 0) return hash;
for (i = 0; i < this.length; i++) {
char = this.charCodeAt(i);
hash = ((hash<<5)-hash)+char;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
};
var map_manufacter, result_manufacters;
$('#manufacturer').typeahead({
source: function(typeahead, query){
$.ajax({
url: window.location.origin+"/bows/get_manufacturers.json",
type: "POST",
data: "",
dataType: "JSON",
async: false,
success: function(results){
result_manufacter = [], map_manufacters = {};
$.each(results.data.manufacturers, function(item, data){
map_manufacters[data.Manufacturer.manufacturer.hashCode()] = data;
result_manufacters.push(data.Manufacter.manufacter);
});
typeahead.process(result_manufacters);
}
});
},
property: 'name',
items:11,
onselect: function (obj) {
var hc = obj.hashCode();
console.log(map_manufacter[hc]);
}
});
I solved this problem only updating the file bootstrap3-typeahead.min.js to the file in https://github.com/bassjobsen/Bootstrap-3-Typeahead/blob/master/bootstrap3-typeahead.min.js
I think most people can solve this way.