Insert correct arrays doesn't work - javascript

Well, now i am getting "has to be an array", before it had to be a string.
Can someone help me out of this problem? Check comments.
function publishPhoto() {
var tags = []; var x,y=0;
if ( harBilled == 0 ) {
if ( profilSendt==0) {
var c =0;
//Get the online friends from array!
for ( i=0;i<globalTags.length;i++){
if ( c < 49 ){ //max 50 tags!
tags.push({"tag_uid": ""+globalTags[i]+"",
"x" : ""+(Math.floor(Math.random() * 309) + 1)+"",
"y" : ""+(Math.floor(Math.random() * 309) + 1)+""
});
}
c = c+1;
}
var newJson = new String(array2json(tags));
newJson = newJson.toString();
FB.api('me/photos', 'post', {
message: txt2send,
status: 'success',
url: 'http://meedies.com/0bcf1f22_smush_400x400.jpeg',
}, function (response) {
if (!response || response.error) {
harBilled=0;
alert(var_dump(response.error));
} else {
var fi = response.id;
alert("Now this!");
FB.api(fi + '/tags?tags='+tags, 'POST', function(response){
alert(var_dump(response));
});
harBilled=1;
//getPages()
}
})
profilSendt=1;
}
}
I am trying to insert multiple ids to be tagged on a picture. Can something help me though this correctly

Sounds like you're filling the wrong type of data into the tags array.
Try this...
var tags = [
{"tag_uid": 91839404, "x": 250,"y": 350},
{"tag_uid": 91839401, "x": 220,"y": 340}
];
Edit
Just insert the objects itself and not an array with one single object.
tags.push({"tag_uid": 91839404, "x": 250,"y": 350});

This is the Facebook definition:
PHOTO_ID/tags?tags=[{"id":"1234", "X":1, "y":2}, {"id":"12345", "x":1, "y":2}]
I've just tried to do that with json_encode. The result was:
[{"id":"1","x":"1","y":"2"},{"id":"2","x":"1","y":"2"}]

To post your variable tags, use
console.log(tags);
Doesn't work on old IE browsers.

It's still an array. If the api requires it as string, you'll have to encode it. Like I said, json encoding would return exactly the same "visual" result, except - it would be a string, not an array.
[{"tag_uid": 587908880,"x" : 17,"y" : 251},{"tag_uid": 664099777,"x" : 166,"y" : 197},{"tag_uid": 824600788,"x" : 275,"y" : 89},{"tag_uid": 1012286173,"x" : 247,"y" : 225},{"tag_uid": 1027953684,"x" : 81,"y" : 25},{"tag_uid": 1049653245,"x" : 169,"y" : 2},{"tag_uid": 1089472771,"x" : 236,"y" : 125},{"tag_uid": 1157692807,"x" : 75,"y" : 70},{"tag_uid": 1183641328,"x" : 307,"y" : 254},{"tag_uid": 1206853982,"x" : 154,"y" : 254},{"tag_uid": 1279891790,"x" : 54,"y" : 5},{"tag_uid": 1379771663,"x" : 206,"y" : 280},{"tag_uid": 1446366514,"x" : 37,"y" : 168},{"tag_uid": 1599969496,"x" : 26,"y" : 226},{"tag_uid": 1645141964,"x" : 250,"y" : 23},{"tag_uid": 100000830101385,"x" : 5,"y" : 110},{"tag_uid": 100003711738950,"x" : 174,"y" : 294},{"tag_uid": 100003908889022,"x" : 249,"y" : 38}]
Once the string is formated, you may send it this way:
PHOTO_ID/tags?tags=[{"id":"1234"}, {"id":"12345"}]

Here, you're converting your array to json (I'll assume it's converted correctly)
var newJson = new String(array2json(tags));
newJson = newJson.toString();
But here, you're still using the array
FB.api(fi + '/tags?tags='+tags
I think i've found your problem:
The x and y coordinates that you're using, should be as percentage offset from the left(x) and top(y). Allowed values are 0 - 100. As of your posts below, I see that some of the coordinates exceed the 100 limit. You should probably recalculate your coordinates as relative offsets. But for first, try it with some test data, to see if it works.
Also, see documentation.
Try this, a tell me, how it's gone.

Related

How to add an object as a data attribute

Using the api I was able to retrieve the info i needed trough the following endpoints and create the following object.
var lego = {
"name" : item.name,
"followers" : item.follower_count,
"created" : item.created_at,
"updated" : item.updated_at
}
<datagrid id = "topicGrid" data='[{}]'>
<datagrid-column head="Topic" content-key="name"></datagrid-column>
<datagrid-column head="Followers" content-key="followers"></datagrid-column>
<datagrid-column-time head="Created" content-key="created" format="date"></datagrid-column-time>
<datagrid-column-time head="Updated" content-key="updated" format="date"></datagrid-column-time>
</datagrid>
I would like to somehow append the "lego" object in the new data attribute ?
Now i tried something like
setAttribute("data", lego); but my knowledge here is limited.
Any help is apreciated. Thank you.
Update:
I tried passing the object as a string but I only get the last element of the object. Kind of like it's looping trough the whole object and stopping at the last one.
$('datagrid').attr('data', JSON.stringify(lego));
My solution
$.get( "..." ).done(function( data ) {
var legoArr = []
$.each(data.topics, function(index,item) {
var lego = {
"name" : item.name,
"followers" : item.follower_count,
"created" : item.created_at,
"updated" : item.updated_at
};
legoArr.push(lego);
});
$('datagrid').attr('data', JSON.stringify(legoArr));
});

Compare exact result in Javascript/Jquery

I'm just about creating a website, where im iterating through a list of items in a JSON file. It looks like this:
"prices" : [
{
"market_hash_name" : "★ Bayonet",
"price" : 141.04,
"created_at" : 1455877920
},
{
"market_hash_name" : "AWP | Pit Viper (Minimal Wear)",
"price" : "1.83",
"created_at" : 1455878005
}
.
.
. and so on
Now, i'm sucessfull in searching and picking the "price" by the "market_hash_name" with a $ajax and a $each function in combination by jquery. Here it is:
$.ajax({url: "../json/priceapi.json", success: function(result){ // Get JSON File
$.each(result.prices, function(i, v) {
if (v.market_hash_name == market_hash_name) { ... // Parse JSON Data
Everything works fine, the code seems to be alright, but the problem is, that there, anywhere in this huge JSON File is a exact same second "market_hash_name" but with a additional text part. An exmaple:
{
"market_hash_name" : "Souvenir AWP | Pit Viper (Minimal Wear)",
"price" : "102.18", // Additional text "Souvenir"
"created_at" : 1455878414
},
Due this "double tag" the $each function tells me, that there are two results, for one key. I only want to have the exact result. Do you have any ideas how to do that? Is there a way to do something like this?
$.each(result.prices, function(i, v) {
if (v.market_hash_name - "Souvenir" == market_hash_name) { ...
Thanks to briosheje! https://jsfiddle.net/briosheje/f68wfet6/1/ works nice! Takes a bit, but i works :)
var res = {
"prices": []
};
$.each(json.prices, function(i, e) {
var exists = false;
$.each(res.prices, function (c, f){
console.log(f.market_hash_name + " <> " + e.market_hash_name);
console.log(f.market_hash_name == e.market_hash_name);
if (("Souvenir " + f.market_hash_name) == e.market_hash_name) {
exists = true;
}
});
!exists && res.prices.push(e);
});
console.log(res);

Getting data from dynamic mongodb embedded object node.js

I have a mongoDB structure that looks like this:
values : { [
oneValue : {
number: '20'
unit: 'g'
}
differentValue : {
number : '30'
unit : 'g'
}
]}
I am using node js this is what I do:
doc.values.forEach(function(err, idx) {
var object = doc.values[idx];
}
And what ends up happening is I can get an object that looks like this:
object = oneValue : {
number: '20'
unit: 'g'
}
But node does not recognize it as a JSON because when I try to do JSON.parse(object) it doesn't know how to handle it.
I want to be able to get at the number field dynamically. So I don't want to say doc.values[idx].oneValue because this is a pretend case and in the real case oneValue could be one of 1000 different things. Does anyone know how I can access the 'number' field with this structure?
figured it out...
after
var object = docs.values[idx]
do this:
var objAsJson = JSON.stringify(object);
JSON.parse(objAsJson, function(k, v) {
console.log(k + " " + v);
});
That will print out all the data in the embedded object and you don't have to know the name.

jQuery how to use $.getJSON or $.ajax with Google Maps (and without jQuery)

Newb having trouble with simple task of querying Google Maps for the distance between two cities.
Really, a first learning attempt to get JSON data and make use of it.
I googled a ton, and read many related answers here on SO, first. (Though I eventually found the main answer here.)
I pasted all the code, along with comments about what I was thinking, hoping that someone could explain what I was missing, in beginner terms.
The main problem is that I'm getting the data with one of the two methods I tried ($.ajax, but not $.getJSON, though I thought both would work), see Console Output at the very end of the code, but I couldn't figure out how to actually grab/use the data. Specifically, in the multi-nested object/array combo, I was trying to get the "text" in "distance" in "legs" in "routes" in the "responseText" that was returned.
[edit:] Ok, I finally found an existing SO question, that was [enough to figure it out] (How can I get the object in JSON using jquery or javascript)
In hindsight, I should have just kept looking through even more existing answers.
I'm not sure whether to leave, delete or erase, but I'll edit a bit and leave for now, because there are still parts of the question that are confusing, including:
How to use $.getJSON, in the code below -- shouldn't that work, too?
How to know exactly what part of the overall JSON object to use as the argument in the $.parseJSON() method;
Why you still have to use $.parseJSON if you can see your object outputted, and it looks like the object/array combination already. See comments, below.
<!DOCTYPE html>
<html>
<head>
<title>City Distances</title>
<script src="js/jquery.min.js"></script>
</head>
<body>
<input type="text" id="city1" value="Atlanta"><br/>
<input type="text" id="city2" value="Orlando"><br/>
<button type="submit" id="btn">Submit</button>
<script>
var city1 = document.getElementById('city1');
var city2 = document.getElementById('city2');
var btn = document.getElementById('btn');
var valCities = [];
function getCities () {
valCities[0] = city1.value;
valCities[1] = city2.value;
var gMap = "http://maps.googleapis.com/maps/api/directions/json?origin=" + valCities[0] + "&destination=" + valCities[1] + "&sensor=false";
// I'm confused about what $.getJSON is supposed to get.
// Here's why I was trying to get the JSON data. I never saw how this would work; no idea.
var b = $.getJSON(gMap);
// Is the data I'm looking for in here, somewhere?
// I thought there'd be something like the c['responseText'], below.
// (I numbered each element (g), b/c I thought I could access with [#] bracket notation).
var g = 0;
for (var i in b) {
console.log("$.getJSON: <" + g + "> [" + i + "]: " + b[i]);
g += 1;
};
// jQuery method (I found more examples that used this method, so I tried this, too.)
// I'm confused by the example showing the argument 'json' being passed in, b/c I didn't
// use it.
// But c['responseText'] seemed to have the "distance" data I needed.
var c = $.ajax({
type: "GET",
url: gMap,
dataType: "json",
success: function(json) {
// I'm trying to see what was gotten. Added counter for the elements; I
// thought maybe I could access with bracket notation using the number of
// the element.
// The relevant output is listed, below, in comment at end of script.
console.log("\n $.ajax success: \n")
var h = 0;
for (var j in c) {
console.log("$.ajax: <" + h + "> c[" + j + "]: " + c[j]);
h += 1;
}
** This is what finally worked **
// nested objects and arrays...
var d = c['responseText'];
var jsonObject = $.parseJSON(d);
var theDistance = jsonObject.routes[0].legs[0].distance.text;
console.log("*** theDistance: " + theDistance + "\n\n ***");
Or was it that I should use .map like this?
Anyway, here's the the rest, mostly just for the console.log output at the end:
// **And if this works, and prints out all the data:
var d = c['responseText']; // (from above)
console.log("ddd: " + d);
/* This is what it prints to the console:
ddd: {
"routes" : [
{
"bounds" : {
"northeast" : {
"lat" : 33.74932270,
"lng" : -81.37924350
},
"southwest" : {
"lat" : 28.47414120,
"lng" : -84.40452560
}
},
"copyrights" : "Map data ©2013 Google",
"legs" : [
{
"distance" : {
"text" : "442 mi",
"value" : 710661
},
*/
// **Then why doesn't this work? (It says routes is undefined.)
console.log(d.routes[0].legs[0].distance.text);
}
});
}
// Event handler for the little form (which already has the two demo cities, pre-populated.
btn.addEventListener("click", getCities, false);
/*
** OUTPUT **
This is the relevant JSON data returned from Google from the console.log, above.
[Console output:]
. . .
$.ajax: <18> c[responseText]: {
"routes" : [
{
"bounds" : {
"northeast" : {
"lat" : 33.74932270,
"lng" : -81.37924350
},
"southwest" : {
"lat" : 28.47414120,
"lng" : -84.40452560
}
},
"copyrights" : "Map data ©2013 Google",
"legs" : [
{
"distance" : {
** --- This is what I was trying to get --- **
**"text" : "442 mi",**
"value" : 710661
},
"duration" : {
"text" : "6 hours 13 mins",
"value" : 22360
},
"end_address" : "Orlando, FL, USA",
"end_location" : {
"lat" : 28.53831440,
"lng" : -81.37924350
},
"start_address" : "Atlanta, GA, USA",
"start_location" : {
"lat" : 33.74883970,
"lng" : -84.38750639999999
*/
</script>
</body>
</html>

How to read JSON(server response) in Javascript?

I am sending some request on a server and it's reply me this:
{"COLUMNS":["REGISTRATION_DT","USERNAME","PASSWORD","FNAME","LNAME","EMAIL","MOBILE","FACEBOOK_ID"],"DATA":[["March, 17 2012 16:18:00","someuser",somepass,"somename","somesur","someemail",sometel,"someid"]]}
I tried a lot but nothing seems to working for me!
var xml2 = this.responseData;
var xml3 = xml2.getElementsByTagName("data");
Ti.API.log(xml3.FNAME);
For this code I get "null".
Any help would be appreciated!
If you're trying to use JSON format, your problem is that the data within the [...] also needs to be in pairs, and grouped in {...} like here.
For instance,
{
"sales": [
{ "firstname" : "John", "lastname" : "Brown" },
{ "firstname" : "Marc", "lastname" : "Johnson" }
] // end of sales array
}
So you might have:
{"COLUMNS": [
{"REGISTRATION_DT" : "19901212", "USERNAME" : "kudos", "PASSWORD" : "tx91!#1", ... },
{"REGISTRATION_DT" : "19940709", "USERNAME" : "jenny", "PASSWORD" : "fxuf#2", ... },
{"REGISTRATION_DT" : "20070110", "USERNAME" : "benji12", "PASSWORD" : "rabbit19", ... }
]
}
If the server is sending you something which you refer to as res, you can just do this to parse it in your Javascript:
var o=JSON.parse(res);
You can then cycle through each instance within columns like follows:
for (var i=0;i<o.COLUMNS.length;i++)
{
var date = o.COLUMNS[i].REGISTRATION_DT; ....
}
see that link. READ JSON RESPONSE
It's perfect.
JSON objects work just like any normal javascript objects or dictionaries
// You can do it this way
var data = this.responseData["DATA"]
// Or this way
var data = this.responseData.DATA
In your case, COLUMNS and data are both arrays, so it looks like you're trying to get the element from data that corresponds to the "FNAME" element in COLUMNS?
var columns = this.responseData["COLUMNS"];
var data = this.responseData["DATA"][0];
for(var i=0; i<columns.length; i++){
if(columns[i] == "FNAME"){
Ti.API.log(data[i]);
}
}
EDIT: If you can't change the data on the server end, you can make your own object client side. This also helps if you have to refer to multiple columns (which you probably do).
var columns = this.responseData["COLUMNS"];
var data = this.responseData["DATA"][0];
var realData = {};
for(var i=0; i<columns.length; i++){
realData[columns[i]] = data[i];
}
// Now you can access properties directly by name.
Ti.API.log(data.FNAME);
More edit:
My answers only consider the first row in DATA, because I misread originally. I'll leave it up to you to figure out how to process the others.
If you got here trying to find out how to read from [Response object] (as I did) -
this what can help:
- if you use fetch don't forget about res.json() before logging in console
fetch(`http://localhost:3000/data/${hour}`, {
method: 'get'
})
.then(res => {
return res.json()
})
.then((response) => {
console.log('res: ' + JSON.stringify(response))
})
Testing out your code in http://jsonlint.com/, it says that your server's response is not a valid JSON string.
Additionally, I recommend checking out jQuery.parseJSON http://api.jquery.com/jQuery.parseJSON/
Just use JSON.parse(serverResponse)

Categories

Resources