Pull string value out of JSON object - asp.net

I have a web service that returns me a JSON object that contains the string "Hello World". How do I pull this string out of the object?
data = [object Object]
Thanks
Nick

You have to know how is your object, what members the object have.
You could try something like
for(var e in data)
alert(e + ' : ' + data[e]);

You can either use eval:
var foo = eval('(' + data + ')');
But that is potentially dangerous, especially if you don't trust what is being sent from the server. Thus, the best way (and most secure way) to extract data from a JSON object is by using Crockford's JSON library:
var foo = JSON.parse(data);
Btw, if you're using jQuery to query ASP.Net Web Services, be careful of the the d. issue (which is used as a container object). Thus to extract the returned object, you have to do:
var foo = JSON.parse(data);
if (foo) {
//Foo is not null
foo = f.d;
}
More information about this here: http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/

If you are using jQuery's post function you might follow this example found here.
$.post("test.php", { func: "getNameAndTime" },
function (data) {
alert(data.name); // John
console.log(data.time); // 2pm
}, "json");
In your case, I would suspect that you would call data.data.

Related

Fullcalendar, Resources as function don't work

I'm working with Fullcalendar and I'm trying to get resources as function
resources: function(callback){
var manageEvent = new ManageEvent();
var request = manageEvent.getEmployees();
request.always(function (param) {
//location.reload();
var list = [];
var emp;
for (var elem in param) {
emp = param[elem];
list.push({
'id': emp['cp_collaboratore'],
'title': emp['cognome_col']
});
}
var t = JSON.stringify(list);
callback(t);
});
request.catch(function (param) {
alert('errore');
});
},
I checked the variable 't' through log and it shows the following result:
[{"id":"1","title":"name_1"},{"id":"2","title":"name_2"},{"id":"3","title":"name_3"},{"id":"5","title":"name_4"},{"id":"9","title":"name_5"}]
but it don't works and shows the following error message:
Uncaught TypeError: resourceInputs.map is not a function
at ResourceManager.setResources
You just need to write
callback(list);
t in your code is a string, because you converted your list array into a string using JSON.stringify(). But fullCalendar expects an actual array, not a string. It can't run functions or read individual properties from a string.
You can remove the line var t = JSON.stringify(list); completely, it's not needed.
Generally the only reason you'd use stringify() is if you wanted to log the value to your console for debugging, or convert the array into JSON if you wanted to send it somewhere else using AJAX. It makes no sense to pass arrays and objects around inside JavaScript as serialised strings, when you can just use the objects themselves.

Parse json into a series of documents in a collection using a for or foreach loop best? [meteor]

I have a Meteor app that pulls data in from an external api. For simplicity sake we'll say something like...
var foo = Meteor.http.call("GET", "api-endpoint-url-here");
And inserts the data into a collection...
Bar = new Mongo.Collection("bar");
Bar.insert({
Results: foo
});
The json array (e.g. foo) includes a number of individual records each of which has it's own id number and corresponding data. I'm presently using JSON.parse to establish my array and then looping through the array to create individual documents using _.each
var fooParsed = JSON.parse(foo.content)
var fooArray = fooParsed.results;
_.each(fooArray, function(records) {
Bar.insert ({
record: record
});
});
For now it's crude but that aside - I've heard using forEach is preferred for performance. Is that the general consensus and any thoughts on how to streamline this and implement such a loop in this instance?
in case it's helpful to someone else in the future - here's where this netted out
fooArray.forEach(function(item) {
Bar.insert({
_id: item.id,
description: description,
});
});

What is the equivalent of firebaseRef.push() with angularfire?

In the following non-angularfire pseudo-code I would expect to have firebase generate a key for the new data being pushed in.
var ref = Firebase(...);
var newref = ref.push({"blah":"blah"});
var autoKey = newref.name();
I try to do the same thing through angularfire with a bound model but it just gives me errors about the object not having a push() method, similar to this question. He got it working when the data type was an array.
How do I get the nice behaviour I've seen in regular Firebase (non-angularFire) with automatic keys for objects?
If you want to use an Object and have auto-generated keys, use the add method on a angularFireCollection. For example:
function ExampleController($scope, angularFireCollection) {
var url = 'https://angularFireExample.firebaseio-demo.com/';
$scope.examples = angularFireCollection(url);
$scope.addExample = function(ex) {
$scope.examples.add(ex);
};
}

How to parse url with Meteor

I'm using Meteor with another CMS, and am creating a url with the variables I need to run Meteor (ex. http://site.com?a=flash&b=hash). How to I make those variables usable, and get Meteor to ignore it as a location? When I load the url like that, my app doesn't load correctly, presumably because it thinks I'm requesting a different location.
Using iron router, if there is a query string or hash fragment in the url, you can access those using the query and hash properties of the this.params object.
// given the url: "/post/5?q=s#hashFrag"
Router.route('/post/:_id', function () {
var id = this.params._id;
var query = this.params.query;
// query.q -> "s"
var hash = this.params.hash; // "hashFrag"
});
Use of the querystring in Meteor should have no effect unless you're using eg. Meteor Router to invoke different methods depending on the current URL.
If you want to parse the querystring, just parse it by hand with eg. (in coffeescript)
querystring: ->
qs = {}
for pair in window.location.search.replace("?", "").split "&"
[k, v] = pair.split("=")
qs[k] = v
qs
Which will return an object like:
{ "a": "flash", "b": "hash" }

backbone.js collection not responding to .each

I have what should be very simple. I create a new collection, and I want to pass it to a render and add the collection models to the page.
get_results: function(){
$.getJson(this.url,function(response){
this.search_results = new Kitchon.Collections.searchList(response);
console.log(this.search_results);
this.search_results.each(this.render_match);
}
},
render_match: function(model){
console.log(model)
},
This returns an error
Uncaught TypeError: undefined is not a function
my collection has an ordinary structure
_byCid: Object
_byId: Object
_onModelEvent: function () { [native code] }
_removeReference: function () { [native code] }
length: 7
models: Array[7]
__proto__: o
I've tried LOTS of things, but one thing that stuck out was maybe I had to pass
this.search_results.models.each(this.render_match); as that is the actual array, but if I do that I get a Uncaught typeError: Object [object Object],[object Object],...
you lose the execution context when callback function for each method is called
use _.bind(this.render_match, this) when passing callback to make sure that render_match has the right context
and you were getting error because you didn't wrap the callback function for getJson method neither. You have to use underscore bind method there as well.
You should read a bit about javascript this and how to tame it - try here http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/
Correct code should look more or less like this...
get_results: function(){
$.getJSON(this.url, _.bind(function(response){
this.search_results = new Kitchon.Collections.searchList(response);
console.log(this.search_results);
this.search_results.each(_.bind(this.render_match, this));
}, this));
},
render_match: function(model){
console.log(model)
},
Though from what I seee - I assume the code you've shown here is either a model or collection - is handling rendering the view - you shouldn't do that! Models and Collections are only to store and parse data - all rendering and controlling application flow should be done in the View(Controllers) with help of the Router.
$.getJson changes the this reference. Many methods in jquery do that, so the value of this.render_match is null. You pass null to each and it fails.
To solve that, create a reference to this (like var _this = this;) before $.getJson and use it instead of this. Code should be like below:
get_results: function(){
var _this = this;
$.getJson(this.url,function(response){
_this.search_results = new Kitchon.Collections.searchList(response);
console.log(_this.search_results);
_this.search_results.each(_this.render_match);
}
},
render_match: function(model){
console.log(model)
},
Just taking a stab here (I don't know anything about Backbone.js), but isn't this what you are looking for:
$.each(this.search_results, function(index, value) {
alert(index + ': ' + value);
});
Good Luck!

Resources