I am having a very weird problem. Using $http my response is not getting marshalled correctly into map/object. The data is a map of lists. The issue is that the element 100110150000000751 has a value from the raw data in the first log "1 group data[". but after its converted to json it has the value of an empty array. You can see the image of the "after conversion" log. This all works fine in chrome with debugger open but not if debugger is closed. The method is so simple and there is little to no room for race conditions or anything. I created a little desktop html file with all the same libraries and just calling a function without $http and it works without issue. Angular 1.4.5 Any help is much appreciated.
transformResponse: function(groupMapResponse){
console.log("1 group data ["+groupMapResponse+"]");
var asdfdsafsad = (typeof groupMapResponse === 'string')?JSON.parse(groupMapResponse):groupMapResponse;
console.log("after conversion:",asdfdsafsad);
return asdfdsafsad;
}
The console log is:
1 group data [{"1000110150000002801":["1000110020000007753"],"1000110150000002855":["1000110020000009470"],"1000110150000004452":["1000110020000007895"],"1000110150000004362":["1000110020000006355"],"1000110150000004361":["1000110020000010309"],"1000110150000000751":["1000110020000007950"],"1000110150000004412":["1000110020000006353"]}]
Turns out the issue was not in marshalling at all. The object was already linked to a bound object and was later altered but the log message was updated with the bound value. Anyway...
Related
I am trying to learn working with API calls and responses and I needed a basic value that comes from api response but I wasn't able to get it work. So here is my problem;
(function worker() {
$.get('URL', function(data) {
$('#numbers').html(data); });
})();
I use this code and this works perfectly fine, and writes the API response to my HTML page. Also the API calls return the value in this format;
{
"success":"true",
"field1": {"number1":"number1_val","number2":"number2_val"},
"field2": {"number11":"number11_val","number22":"number22_val"}
}
Now, I tried to write the values from API response and I was successfull for writing the "success" value like this;
$('#success_val').html(data.success);
It printed true value to my HTML website in given #success_val field. However, when I tried to write the field1, or the first value of field1, I wasn't successful. I tried
$('#numbers').html(data.field1); => No success, empty page
$('nu#mbers').html(data.field1[0]); => No success, empty page
So, at this point, what I need to store & use is the "number11" value from field 2. I have read and searched for over an hour and found out that this api return is not a valid "array" return, instead it is called "field" (I might be wrong), but I couldn't find any info about how can I get the "number11" data from this api response.
$('#numbers').html(data.field1); => No success, empty page
Does data.field1 exist for sure? or spelling check.
you can get keys by Object.keys(data).
If exist data, it return ["success", "filed2", "field2"].
In the same way, you already know key, like number11,
data.field2.number11 or data["field2"]["number11"] return value.
If you don't know key, data["filed2"][Object.keys(data)[0]] return value
Thanks to https://stackoverflow.com/users/10366589/sh-k I have solved the problem in given way;
As I wasn't able to print output from field2 to HTML, I have checked keys at field2 with this code;
alert(Object.keys(data.field2));
and it returned
number11,number22
since I only needed number11 from that API response, I did the following;
var.storednumber = Object.keys(data.field2);
var.storednumber = storednumber[0];
$('#numbers').html(storednumber);
and I was able to get the number I wanted printed on the screen without any problem :)
There could be a better solution or fix for the issue I am having, but for now, this has solved. I guess the problem lies on the API response type as it doesn't return an array formatted data.
I created a small sample application using VueJs and created a C# REST API to store and retrieve data in a SQL Server back end.
For testing, I created a simple web page with a form to create a "note". The note is stored by the following function, 'saveData()':
saveData()
{
let promiseStack = [];
var jsondata = JSON.stringify(this.note);
promiseStack.push(this.$http.post('REST_API/note', jsondata));
Promise.all(promiseStack).then(data =>
{
this.$http.get('REST_API/note');
this.$router.push({ name: 'viewnotes', params: { id: data[0].body.id }})
}, error =>
{
console.log(error);
});
}
I tried to use a promise to wait until the 'store' operation in the backend is complete, and issue a GET request to retrieve all notes once the promise is fulfilled.
However, the get request inside the promise doesn't return any data. If I issue the get request manually later one, I retrieve the data that was stored previously.
So I had look into the C# REST API. There are currently two functions: createNote(...), getAllNotes(...). I used a StreamWriter to log to the filesystem when these functions are called, using milisecond precision. What I see is that 'createNote' is called after 'getAllNotes'. So I suspect that the API is working correctly, but something with the way I'm using promises seems to be awfully wrong.
Maybe somebody has a hint?
UPDATE
I know that the GET request doesn't return any data by using the developer toolbar in Chromium. The response is empty
The developer toolbar in the network tab shows that the requests are submitted in the correct order, so the "POST" request is issued first
It seems I found the problem. I had a 'href' tag in my 'Save' link, which triggered an early routing. The intended 'POST' and 'GET' were fired correctly, but there was another 'GET' inbetween somewhere because of the 'href' tag in the link, even though it was empty.
I removed the tag, now it works as intended.
I'm using ParseJS to try and get the data from a user (from another object) and no matter what I try it doesn't seem to be working, i thought it would be as simple as doing:
var message = results[i].get('Messager').get('username');
To keep in mind:
var message = results[i].get('Messager'); // gives me message object perfectly fine
var message = results[i].get('Messager').id; // gives me user id perfectly fine
Since without .get('username') it works fine i'm unsure why it's not working. I've used the console to inspect that object and the data i want is stored normally inside the object, even when i do:
console.log(results[i].get('Messager'));
and then save as a temp variable inside the Chrome console then use:
temp1.get('username');
It works fine, this is really bothering me because i dislike the workaround.
What am i doing wrong? Why is doing .get('Messager').get('username'); not working?
There are no spelling/capital mistakes in what I'm doing
Here is an image with the .message object when i do console.log(results[i].get('Messager');
After further testing I found that the 'Messaging' object works but 'Messager' object doesn't work? The objects look the exact same..
So I'm trying to go through one Firebase database to find entries in the database matching a criteria. Therefore I'm using the deferred object of jQuery to handle the database calls.
Once I get a return value from this first database I want to get the user info from a second database for each of those values in the first db. Then the results are added to a JSON array
so its:
<search for value, find one>
<<<search other db for oher info>>>
<continue search for outer value>
But this only returns one value - although everything else is running fine (and the console logs all the info correct).
Here's the code:
function find(searchLocation, profileID) {
var requestUserData = {
data: []
};
var def = $.Deferred();
//This will be executed as long as there are elements in the database that match the criteria and that haven't been loaded yet (so it's a simple loop)
Ref.orderByChild("location").equalTo(searchLocation).on("child_added", function(snapshot) {
def.ressolve(snapshot.val().ID);
});
return def.promise();
};
I hope you guys have any ideas on what to do or how I could solve this. Thanks in advance!
Edit: upon further testing I discovered that this problem already exists in the outer loop - so only the first value is being returned. I think this is related to the posission of the resolve() method but I didn't find a posibility on how to change this behaviour.
Firebase is a real-time database. The events stream as changes occur at the server. You're attempting to take this real-time model and force it into CRUD strategy and do a GET operation on the data. A better solution would be to simply update the values in real-time as they are modified.
See AngularFire, ReactFire, or BackboneFire for an example of how you can do this with your favorite bindings framework.
To directly answer the question, if you want to retrieve a static snapshot of the data, you want to use once() callback with a value event, not a real-time stream from child_added:
Ref.orderByChild("location").equalTo(searchLocation).once("value", function(snapshot) {
def.resolve(snapshot.val());
});
I'm attaching response data to the target of a jquery plugin when a preload option is set. It all seems to work a charm except the data I set is inaccessible. When I log $(elm).data(); I can see that the object was returned with the appropriate data set to the appropriate key. But when I try console.log($(elm).data('key')); I get undefined. I also get undefined when I try var elmData = $(elm).data(); console.dir(elmData.key);. So I'm logging the object on one line, seeing it in the console, trying to access a property I just confirmed exists and getting undefined.
Here is my function:
this.preloadData = function(folders)
{
var getString;
for(var folder in folders ){
getString = 'folder='+folders[folder]+'&uri='+uri+'&thumbSide='+options.thumbSide;
$.get(options.handler, getString,
function(response, serverStat, xhr)
{
$self.data(folder, response);
});
}//for
var $selfData = $self.data();
console.log($selfData);//Object{ editorial : "data", testingdata : 'some meaningless words'}
console.log($self.data());//Object{ editorial : "data", testingdata : 'some meaningless words'}
console.log($self.data.editorial);//undefined
console.dir($self.data('editorial'));//undefined
console.log($selfData['editorial']);//undefined
console.log($selfData.editorial);//undefined
$self.data('testingdata', 'some meaningless words');
console.log($self.data());//Object{ editorial : "data", testingdata : 'some meaningless words'}
console.log($self.data('testingdata'));//'some meaningless words'
}
I know the namespacing is too simple, I just tried to cut out as many factors as I could to try and understand why this isn't working. I'm developing in chrome but I've tried it in firefox also and get the same.
-----------------------------EDIT------------------------------------------
I understand what the problem is now. The console reflects all changes to an object that get made regardless of if they were made when the object was logged. So when I logged the object the property didn't exist yet because the response had yet to come back from the server, but the log still shows the property as existing because at some later point in the script execution it DID exist. Because primitive values aren't logged in the same way, the call to log the property shows up as undefined because it WAS undefined. If I refer to the property some seconds later, say on a click event it is defined(which is how I intended it to work anyway). I just got really caught up in debugging this function before I actually implemented it.
Can you do this?
$self.data['editorial']
try
console.log($self.data.editorial);