Javascript pass var - javascript

I'm having a little problem. I'm new in JS and I can't figure it out.
I'm trying to get a list of friends from Facebook. To do that I'm using the user posts and I want to show only the duplicates. My first answer is how to show all the friends from a loop and get only the duplicates (I want only one or two objects) and second is how to pass a var from a function to another function because I want to POST all the infos to a php file.
This is what I did:
function getInfo() {
FB.api(
'/me',
'GET',
{fields: 'first_name'},
function(response) {
friends();
var myname = response.first_name;
$.post(
"file.php",
{ myname:myname,friendsname:friendsname },
function(data) { $("body").append(data); }
);
}
With this function I'm getting my first name.
function friends() {
FB.api(
'/me/posts?fields=likes{id,name}',
{limit:50},
function(response) {
if (response.data) {
$.each(response.data,function(index, posts) {
var posturi = posts.likes;
$.each(posturi.data, function(useri, lista) {
var friendsname = lista.name;
});
});
}
}
);
}
And this is the list with my friends. If I check console.log(friendsname) it gives me all the friends with duplicates. But if I write an innerHTML in that $.each it returns me only 1 object. And how can I pass friendsname from friends() to getInfo() so I can post to that .php file?

That's because you're overwriting the value of innerHTML in every loop of $.each.
Try this:
var posturi = posts.likes;
var names = posturi.data.map(function(item) { return item.name; }).join(', ');
names will contain a comma separated list of names.

Related

How Displlay elements from API query , or put them in array

Hello i want to display results from https://developer.edamam.com/edamam-docs-recipe-api this api or to put them into array
vm.search = function(){
var req2 = {
method: "GET",
url:"https://api.edamam.com/search?q="+vm.searchText+"&app_id=myID&app_key=myKey"
}
$http(req2).then(
function(resp){
console.log(resp);
vm.recepti = resp.data.Search;
console.log(vm.recepti);
}, function(resp){
vm.message = 'error';
});
};
i dont quite understand this particular api, or how do i display all recepies (names, images and other parameters that it has) from query result that users inputs in field with vm.searchText text box thanks for help in advance
vm.recepti is an emtpy array ,
when i go to query link i get this now how do i access properties based on this?
Try to do something like this:
vm.recepti = resp.data.hits;

Get object from JSON with jQuery

I'm trying to query a JSON file in my own server using $.getJSON and then cycling inside the objects. No problem so far, then i have an ID which is the name of the object i want to return, but can't seem to get it right:
var id = 301;
var url = "path/to/file.json";
$.getJSON( url, function( json ) {
var items = [];
items = json;
for (var i = 0; i < items.length; i++) {
var item = items[i];
console.log(item);
}
});
This prints the following in the console:
Now let's say i want return only the object == to id so then i can refer to it like item.banos, item.dorms etc.
My first approach was something like
console.log(json.Object.key('301'));
Which didn't work
Any help would be very much appreciated.
It seems like your response is wrapped in an array with one element.
You can access object properties dynamically via square brackets:
var id = 301;
var url = "path/to/file.json";
$.getJSON(url, function(json) {
console.log(json[0][id].banos);
});
As you have the name of the property in the object you want to retrieve you can use bracket notation. you can also simplify your code because of this:
var id = 301;
//$.getJSON("path/to/file.json", function(json) {
// response data from AJAX request:
var json = {
'301': {
banos: 2
},
'302': {
banos: 3
},
'303': {
banos: 4
},
'304': {
banos: 5
},
};
var item = json[id];
console.log(item);
//});
$.each(items,function(n,value){
if(n==301)
alert(value);
});

Issue accessing variable outside of function scope [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I'm pulling data from an XML feed. That is all working correctly but I need productIDs available outside the function.
// Get feed data
$.get('example-feed.xml', function (data) {
var $xml = $(data);
// Collect array of product IDs
var productIDs = [];
// extract ids from xml
$xml.find("item").each(function() {
var $this = $(this)
item = {
id: $this.find("id").text()
}
// get the id
var itemID = item.id;
// push ids to array
productIDs.push(itemID);
});
console.log(productIDs); // Works as expected
});
console.log(productIDs); // Undefined, also as expected
How can I adjust my function to work like that?
example = function(){
var productIDs = "my content ids"
return {'productIDs': productIDs}
}
var retrive = example();
console.log(retrive.productIDs);
There are multiple ways you can do this, but the best thing here is to use promises, because JQuery's get is usually asynchronous function and you have to wait for it's completion to get product ids
You may do it like this
function fetchThings () {
return new Promise(function (yes, no) {
$.get('example-feed.xml', function (data) {
// some code here
console.log(productIDs); // Works as expected
yes(productIDs);
});
});
}
fetchThings().then(function (productIDs) {
// do stuff with prodcut ids here
});
The other way to do it would be making your $.get call synchronous, so replace it by
var productIDs;
$.ajax({url: 'example-feed.xml', type: "GET", async: false, success: function (data) {
// process productIDs here
}});
// use productIDs here
Update:
Here is a snippet of async ajax, click run to check
var postIDs;
$.ajax({
url: 'http://jsonplaceholder.typicode.com/posts',
method: 'GET',
async: false,
success: function(posts) {
postIDs = posts.map(function (p) { return p.id; });
}
});
document.write(JSON.stringify(postIDs));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

insert the friends photos in a database in array

function getUserFriends(a) {
var id=a;
FB.api('/me/friends?fields=picture', function (response) {
//console.log('Got friends: ', id);
var x = y = 0;
var photos=[];
for (var i=0;i < response.data.length;i++) {
photos = response.data[i].picture.data.url;
$.post("insert_photo.php", {
"pic": photos,
"id":id
}, function (data) {
});
}
}
I am using a Facebook API to call my friends friends profile pic and using a post inserting into the db , suppose if i have 500 friends , it will send the post request 500 times , now i want to store it in the array and then the post request . is it possible , if yes please tell me how
I am not sure if I understood you, but if you want to do only one POST call, you could move the $.post() outside of the for loop. And then send all the photos array as json.
For example:
function getUserFriends(a) {
var id=a;
FB.api('/me/friends?fields=picture', function (response) {
//console.log('Got friends: ', id);
var x = y = 0;
// Storing all photo urls in array
var photos=[];
for (var i=0;i < response.data.length;i++) {
photos.push(response.data[i].picture.data.url);
}
// Send photos as JSON
$.post("insert_photo.php", {
"pics": photos,
"id":id
}, function (data) {}
);
}
This will send all the photos in a single POST call. You will have to update the insert_photo.php script to iterate over the "pics" param. Something like:
<?php
[...]
foreach (json_decode($_POST['pics']) as $pic) {
[...]
// You can use $pic here
[...]
}
[...]
Getting Friends
v2.0 onwards, getting the list of friends with /me/friends has been removed. So, the method you are using will be removed in a few months.
But there is another option now to get the friends (basically the taggable friends) with end point /me/taggable_friends; but this needs to be approved first. (Check out the complete discussion)
Save profile pictures
If you want to save the urls in an array and then make the post requests, you can do that too-
FB.api('/me/taggable_friends', function (response) {
var x = y = 0;
var photos=[];
for (var i=0;i < response.data.length;i++) {
var user={};
user.photo = response.data[i].picture.data.url;
user.id = response.data[i].id;
photos.push(user);
}
// at this point all the friends data have been saved in the array
for(var i=0; i<photos.length;i++){
$.post("insert_photo.php", {
"pic": photos[i].photo,
"id":photos[i].id
}, function (data) {
// done
});
}
});
Or the cleaner way-
Send the photos array to the php script and let php script loop through it and save to the db-
$.post("insert_photo.php", {
"data": JSON.stringify(photos)
}, function (data) {
// done
});

Create Json list with objects with a string and bool value

I want to create a list that consists of x number of objects that contains a name and a bool value
I want to create and send the list using ajax when this happens
This is in my Init
$('.si-accordion').click(function () {
$(this).siblings('.accordion_tab').toggleClass('IsExpanded');
SendSIInstance();
});
Here is the method it calls
function SendSIInstance() {
$('.si-accordion').hasClass('IsExpanded')
{
var NameValue = $('.si-accordion').text();
alert($('.si-accordion').text());
}
}
In my example I have 5 tabs (Which has the class si-accordion)
When I click them I toggle the class IsExpanded
I then want to create a list with objects like:
a String: text of si-accordion
A bool: if it has the class IsExpanded (if its there its true, else false)
The list with these 5 objects should then be send using AJAX so I can work with it.
You could do:
function SendSIInstance() {
var arrayToSend = [];
$('.si-accordion').each(function() {
var expanded = $(this).hasClass('IsExpanded');
var text = $(this).text();
var obj = {
expanded: expanded,
text: text
};
arrayToSend.push(obj);
});
//Send arrayToSend through ajax
$.ajax({
url: "yoururls",
data: arrayToSend,
success: function() {
// code to invoke after ajax call returns
}
});
}
Not sure if I understand your question, but try this...
var list = [$('.si-accordion').text(), $('.si-accordion').hasClass('IsExpanded') ...];
var xmlRequest = $.ajax({
url: "target.php",
data: list,
success: function() {
// code to invoke after ajax call returns
}
});

Categories

Resources