Jquery $.get() manipulating data resulting from query in javascript - javascript

I have a $.get() statement, which returns this (result from a console.log()):
{"desc":"asdasda","dateD":"2012-08-31","dateE":"2012-09- 01","image":"fasdasdasd","categorie":"3"}
Now when I try, in Javascript, to manipulate the array, everything holds an undefined or null value:
var image = data.image;
desc = data.desc;
dateD = data.dateD;
dateF = data.dateE;
image = data.image;
categorie = data.categorie;
Note: the DateF= data.dateE is not a mistake.
Note2: Those statements are all held within the function (data){} function contained in the $.get().
All those assignments return undefined. What am I doing wrong? I have read and re-read the official jQuery doc, without success.

Make sure you set the dataType of the return to json.
If you don't do this, the result data may be a string and you will need to use JSON.parse(data) to turn it into a usable object.
For example:
$.get(url, getData, function(data){
//your fn...
}, 'json');

Related

How to reach JSON data inside parenthesis

I have a JSON response like this:
google.friendconnect.container["renderOpenSocialGadget"](
{
height: 200,
url: "http://username.github.io/",
"view-params": {"style":"light","url":"https://www.facebook.com/username","height":"258"},
"prefs": {"style":"light","url":"https://www.facebook.com/username","height":"258"}
}, skin);
I want to reach the values such as height, url, view-params but couldn't.
I tried this but it didn't worked:
console.log(google.friendconnect.container["renderOpenSocialGadget"].url);
The expression google.friendconnect.container["renderOpenSocialGadget"]( is equivalent to google.friendconnect.container.renderOpenSocialGadget(
Given that, we see that this is a method of an object, getting a JSON object and an additional parameter (skin) as parameters.
As the object is somehow "anonymous" parsed directly in to the function call, you can't access it anymore, once the function has consumed it.
Check, if google.friendconnect.container has getter methods (they usually have ...) by console.log(google.friendconnect.container).
EDIT
Just an Idea: you might catch the call and pass it over:
google.friendconnect.container["MyrenderOpenSocialGadget"] =
google.friendconnect.container["renderOpenSocialGadget"];
google.friendconnect.container["renderOpenSocialGadget"] = function(obj, skin) {
// do what you want with obj
console.log(obj.url);
//call original
google.friendconnect.container["MyrenderOpenSocialGadget"](obj, skin);
});

FindMany overwritten doesn't work. Ember-data

In my project, if I ask my server for the records with id 1,2,3 like this (without spaces):
url?sites=id1 %2C id2 %2C id3
It will return a json file with the records for this ids.
So for this case I think I can have then cached if I manage to use findMany and make the RestAdapter make the call to the server in this way.
I have found the next, but it doesnt work, it continues calling:
GET topologymins/1,2
Adapter:
App.ApplicationAdapter = DS.RESTAdapter.extend({
findMany: function(store, type, ids) {
Ember.Logger.log("INSIDE THE findMany"); // NOT SHOWED
var url = type.url;
url = url.fmt(ids.join(','));
jQuery.getJSON(url, function(data) {
// data is an Array of Hashes in the same order as the original
// Array of IDs. If your server returns a root, simply do something
// like:
// store.loadMany(type, ids, data.people)
//store.loadMany(type, ids, data);
});
}
});
App.Topologymin.reopenClass({
url: '/something?ids=%#'
});
My call:
this.store.find('topologymin',[1, 2]);
Isn't this just because you're missing a return?
Oh... sorry your findMany isn't written correctly, I don't htink... it's missing a return... but that isn't actually what's wrong - it's not even calling the findMany because store.find() can't be passed an array of ids... you want this, I think: store.find('topologymin', { ids: [1,2] });
However, I think you'll have another problem in that findMany should have a return value in it... if you look at the default implementation, you'll see what I mean... it needs to return a promise, and you're not returning anything.

cannot access property of JSON object when dynamically built but can when statically built

I've been at this for an hour and I need help. This is kind of baffling me. Consider this explicit setup of an object in my code:
WORKING CASE:
var terms={};
terms[0]={};
terms[1]={"label":"bag","cell_src":"images/bag.jpg","clue_type":"audio","clue_src":"/audio/bus.wav"};
terms[2]={"label":"crayon","cell_src":"images/crayon.jpg","clue_type":"audio","clue_src":"/audio/car.wav"};
terms[3]={"label":"pen","cell_src":"images/pen.jpg","clue_type":"audio","clue_src":"/audio/car.wav"};
terms[4]={"label":"pencil","cell_src":"images/pencil.jpg","clue_src":"/audio/boat.wav"};
terms[5]={"label":"pencil_case","cell_src":"images/pencil_case.jpg","clue_src":"/audio/train.wav"};
terms[6]={"label":"rubber","cell_src":"images/rubber.jpg","clue_src":"/audio/taxi.wav"};
terms[7]={"label":"ruler","cell_src":"images/ruler.jpg","clue_src":"/audio/plane.wav"};
terms[8]={"label":"sharpener","cell_src":"images/sharpener.jpg","clue_src":"/audio/taxi.wav"};
window.terms= terms;
window.terms= terms; // for using globaly
if I do a console.log(window.terms[1]); I get "bag". Thats what I want.
NOT WORKING CASE
If instead of explicitly defining the values of term{}, I read in the contents from a json file and assign them to each enumerated index like this:
var terms={};
terms[0]={};
$.getJSON('content.json', function(data){
$.each(data,function(i){
//terms[i]={"label":"bag","cell_src":"images/bag.jpg","clue_type":"audio","clue_src":"/audio/bus.wav"};
terms[i+1]={"label":data[i].headword,"cell_src":data[i].image,"clue_type":"audio","clue_src":data[i].audio};
});
window.terms=terms;
});
if I do a console.log(window.terms[1]); I get an error "Uncaught TypeError: Cannot read property '1' of undefined" Note that I have an alternate attempt commented out where I eliminate the possibility that theres something weird going on with the values I am trying to pull in and I explicitly assign the same static value to all the indexes. That produces the same error.
Any ideas how this could be??
$.getJSON does not block when performing an AJAX call. You have to keep the callback chain a live.
I think you want to define terms as an array of objects. Currently you have it defined as an object with properties 1, 2, 3, etc. Syntax like var terms = {} means terms is an object and when you assign terms[1] = {"label": "bag"} you're saying "the property named 1 of object terms is {"label": "bag"}. Just change your terms declaration to this:
var terms = [];
Also, if you want to see the label property of one of the objects the log statement would looks like this:
console.log(terms[2].label);
The $.getJSON() function is just a shorthand for a call to $.ajax() to load a JSON file. Since the AJAX call is asynchronous, the execution of $.getJSON() completes, and any code after it is executed, before the data has been loaded and stored in your variable.
If you want to work with terms do so inside the success callback function that you're passing to $.getJSON().
If your code looks like this:
var terms={};
terms[0]={};
$.getJSON('content.json', function(data){
$.each(data,function(i){
//terms[i]={"label":"bag","cell_src":"images/bag.jpg","clue_type":"audio","clue_src":"/audio/bus.wav"};
terms[i+1]={"label":data[i].headword,"cell_src":data[i].image,"clue_type":"audio","clue_src":data[i].audio};
});
window.terms=terms;
});
// use window.terms here
Then it won't work, because the // use window.terms here part executes before the AJAX call has finished. You'll need to move that to a separate function and call that from the success callback:
function workWithTerms() {
// use window.terms here
}
var terms={};
terms[0]={};
$.getJSON('content.json', function(data){
$.each(data,function(i){
//terms[i]={"label":"bag","cell_src":"images/bag.jpg","clue_type":"audio","clue_src":"/audio/bus.wav"};
terms[i+1]={"label":data[i].headword,"cell_src":data[i].image,"clue_type":"audio","clue_src":data[i].audio};
});
window.terms=terms;
workWithTerms();
});

JQuery Ajax Get Customization

Using one of the many options defined at http://api.jquery.com/jQuery.ajax/ (or anywhere else) can I map the incoming data to a specific data type rather than the default generic object that is usually returned?
My usual method is to "convert" the generated object by grabbing each property and placing it into the constructor for the new object that I really want to use. Then, I just forget about the old object. I would imagine that there is a much more efficient way to do this.
I came up with/found a few ideas such as simply adding methods to each of the returned objects. It works well, but I just have to know if there is an even more efficient method.
So you're saying that you have code like the following:
function Pirate(name, hasParrot)
{
this.name = name;
this.hasParrot = hasParrot;
}
and the server is sending this JSON data:
{
name: "Blackbeard",
hasParrot: true
}
which jQuery is converting to a plain object, right?
If that's the case, you can use a custom datatype to parse the server's data directly into a Pirate object, like so:
// First define the converter:
jQuery.ajaxSetup({
converters: {
"json pirate": function(obj) {
if(!obj.name || typeof obj.hasParrot === "undefined")
{
throw "Not a valid Pirate object!";
}
else
{
return new Pirate(obj.name, obj.hasParrot);
}
}
}
}
// Then use it!
$.ajax("http://example.com/getPirate", {
data: {id: 20},
dataType: "pirate",
success: function(pirate){
console.log(pirate instanceof Pirate); // Should be true
}
});
Edit: If you really want to skip the step of converting to JSON, you could could replace "json pirate" above with "text pirate" and write your own parser for the raw text returned by the ajax call.

jFeed problem: modifying global variable from success function

I am using jFeed to parse an RSS feed and I would like to modify an outside variable (or array) from the function executed upon "success". This is a simple version of the code:
var testVariable = "Original";
jQuery.getFeed({
url: rssFeed,
success: function(feed) {
testVariable = "New Value";
}
});
When I output "testVariable", it still has the original value "Original". Is something wrong with my code?
The purpose of this is to apply the same logic to an array instead of a variable, so I can load the feed's contents into a global Javascript array.
Any help will be greatly appreciated.

Categories