insert the friends photos in a database in array - javascript

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
});

Related

Multiple lookups to get a wordpress blog json's feed

I am trying to get the json for a wordpress blog - but it appears it requires multiple lookups on each news element to get the image.
The json array comes back from the server, but then provides a url to do a lookup for each image. I started to write a function to get the blog json and merge it into one array object - but I am unsure now how to proceed.
here is a jsfiddle
http://jsfiddle.net/emodsbjz/2/
buildBlogObj(data){
let imageBlogArrayUrl = [];
let blogJson = [];
for (var i = 0; i < data.length; i++) {
console.log(data[i]);
let obj = {
"label" : data[i].title.rendered,
"body" : data[i].content.rendered,
"image" : "placeholder.jpg"
}//placeholder image
imageBlogArrayUrl.push(data[i]["_links"]["wp:featuredmedia"][0]["href"]);
blogJson.push(obj);
}
blogJson = blogJson.slice(0, 4);//latest 4
this.setState({ blogs: blogJson });
console.log("blogJson", blogJson);
console.log("imageBlogArrayUrl", imageBlogArrayUrl);
let imageBlogArray = [];
for (var i = 0; i < imageBlogArrayUrl.length; i++) {
this.props.fetchBlogImage(imageBlogArrayUrl[i], function(resp){
imageBlogArray.push(resp.data.source_url)
})
}
console.log("imageBlogArray", imageBlogArray);
//let that = this;
//blogJson[i]["image"] = resp.data.source_url;
//that.setState({ blogs: blogJson });
//that.setState({ blogJson[i]["image"]: resp.data.source_url });
}
componentDidMount(){
let that = this;
this.props.fetchBlog(function(resp){
that.buildBlogObj(resp.data);
});
}
In case you want to get the featured image URL for each blog post, you can append the ?_embed at the end of the REST API endpoint to get the URL of each image along with the rest of the data:
https://www.bizzfizz.co.uk/wp-json/wp/v2/posts?_embed
The featured image URL can be found in the _embedded['wp:featuredmedia'][0].source_url object path.

JavaScript: How can Get the json.file that it was post to my code?

Imagine if I want to wait to get JSON file If they post to me. I can get it. if it's not I waite for it. I want to get it and store it and parse it to work on it.
(I need to receive the request )How I can have JSON file I can get it to take what I need then post my HTTP response to the agent that sends me file that file.
my JSON file name is : flow_demo_1
var device_array = { device_id : [["7547092d-e03e-5148-a54f-8276a85d7f70","cpp_node_192-168-56-1:6111"]] };
var from_file_array = [
{ device_id_from_file: "7547092d-e03e-5148-a54f-8276a85d7f70" },
{ device_id_from_file: "93e71ba7-fb56-5592-a5f6-d855203dd7ae" },
{ device_id_from_file: "93e71ba7-fb56-5592-a5f6-d855203dd7ae" },
{ device_id_from_file: "fe21abdf-706f-5c7b-adb8-2507e145e820" },
];
var val = device_array['device_id'][0][0];
for (var i= 0; i < from_file_array.length; i++) {
if(from_file_array[i].device_id_from_file === val){
console.log("device ids are matches");
};
};
try this,you just want the which file data is matched right?
from_file_array.filter(each=>each.device_id_from_file===device_array.device_id[0][0])
it will give the matched device_id_from_file;if not you will get empty array

Javascript pass var

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.

Fill array through ajax request

I need to gather some data from the database through AJAX and place it in an array. Unfortunatly I'm unable to archieve this for some reason.
AJAX sends data to retrieve specific data. This data is as follows:
[{"comment_id":154,"comment_text":"Moduleboeken PHP","date_updated":"2015-06-01 10:34:47"},{"comment_id":155,"comment_text":"Moduleboeken JAVA","date_updated":"2015-06-01 10:34:54"}]
[{"comment_id":149,"comment_text":"Werksfeer","date_updated":"2015-06-01 10:33:57"}]
[{"comment_id":152,"comment_text":"Begeleiding Elleke Jagersma","date_updated":"2015-06-01 10:34:27"}]
[{"comment_id":260,"comment_text":"Studievoortgang JAVA","date_updated":"2015-06-01 13:01:15"}]
[{"comment_id":153,"comment_text":"Faciliteiten","date_updated":"2015-06-01 10:34:39"}]
The function to gather this data:
function sendRetrieveAjax(url, data) {
return new Promise(function(resolve, reject) {
$.ajax({
url: url, type: 'post', data: data,
success: function(data) {
resolve(data);
},
error: function(request, status, error) {
reject([{request: request, status: status, error: error}]);
}
});
});
}
Main code runs through 5 DOM elements, gathers an ID from them and uses this in the AJAX send and retrieve function. If this is succesfull it places it in an array.
var elements = $('.note_block');
var dataCollection = new Array();
for(i = 0; i < elements.length; i++) {
var element = $(elements[i]);
var data = {
commenttype_id : element.children('#commenttype_id').val(),
week_id : $('#week_id').val()
}
sendRetrieveAjax('../functions/getcomments.php', data).then(function(data) {
console.log(data);
dataCollection[i] = data;
});
}
console.log(dataCollection);
The array unfortunatly is empty, while the console shows the correct data.
Can someone enlighten me?
You have two problems
You need to bound the value of i to the sendRetrieveAjax
You need to print the value of dataCollection after filling it (note the use of promise)
To solve the first problem you need to use IIFE (Immediately-Invoked Function Expression)
for(i = 0; i < elements.length; i++) {
var element = $(elements[i]);
var data = {
commenttype_id : element.children('#commenttype_id').val(),
week_id : $('#week_id').val()
}
(function(_i) {
sendRetrieveAjax('../functions/getcomments.php', data).then(function(data) {
console.log(data);
dataCollection[_i] = data;
});
})(i);
}
And to solve the second problem, you can use an array or promises to keep all request's promises in it, and execute them either sequential or parallel
var requests = []
;
for(i = 0; i < elements.length; i++) {
var element = $(elements[i]);
var data = {
commenttype_id : element.children('#commenttype_id').val(),
week_id : $('#week_id').val()
}
// No need to store the URL, just store the data
requests.push(data);
}
requests = requests.map(function(data) {
return sendRetrieveAjax('../functions/getcomments.php', data);
});
Promise.all(requests).done(function(responses) {
console.log(responses);
dataCollection = responses;
}, function(err) {
});
You need to map each individual response to correct array index. The most optimal solution in this case would be to use $.when to provide an array of promises and the get centralized response object with ordered response data objects.
I also simplified sendRetrieveAjax as $.ajax already returns promise object:
function sendRetrieveAjax(url, data) {
return $.ajax({
url: url,
type: 'post',
data: data
});
}
var promises = $('.note_block').map(function(i) {
return sendRetrieveAjax('../functions/getcomments.php', {
commenttype_id: $(this).children('.commenttype_id').val(),
week_id: $('#week_id').val()
});
}).get();
$.when.apply(null, promises).then(function() {
var dataCollection = $.map(arguments, function(data) {
return data[0];
});
console.log('Data Collection', dataCollection);
});
Another thing, don't duplicated ids, use .commenttype_id classes instead.
Here is a demo: http://plnkr.co/edit/r9NnlxIQjUhNvTYwfLy7?p=preview

How get parametrs from json?

Full code:
$.post('test.php', {
id: id
},function (data) {
console.log(data);
var Server = data.response.server;
var Photo = data.response.photo;
console.log(Server);
console.log(Photo);
});
in data i get json:
{
"server":9458,
"photo":
"[{\"photo\":\"0d6a293fad:x\",\"sizes\":
[[\"s\",\"9458927\",\"1cb7\",\"PX_xDNKIyYY\",75,64],
[\"m\",\"9458927\",\"1cb8\",\"GvDZr0Mg5zs\",130,111],
[\"x\",\"9458927\",\"1cb9\",\"sRb1abTcecY\",420,360],
[\"o\",\"9458927\",\"1cba\",\"J0WLr9heJ64\",130,111],
[\"p\",\"9458927\",\"1cbb\",\"yb3kCdI-Mlw\",200,171],
[\"q\",\"9458927\",\"1cbc\",\"XiS0fMy-QqI\",320,274],
[\"r\",\"9458927\",\"1cbd\",\"pU4VFIPRU0k\",420,360]],
\"kid\":\"7bf1820e725a4a9baea4db56472d76b4\"}]",
"hash":"f030356e0d096078dfe11b706289b80a"
}
I would like get parametrs server and photo[photo]
for this i use:
var Server = data.server;
var Photo = data.photo;
console.log(Server);
console.log(Photo);
but in concole i get undefined
Than i use code:
var Server = data.response.server;
var Photo = data.response.photo;
console.log(Server);
console.log(Photo);
But now in console i see:
Uncaught TypeError: Cannot read property 'server' of undefined
Why i get errors and how get parametrs?
P.S.: All code php and jquery find here
Just set proper data type json, the default one is string.
And your data is directly under data variable!
$.post('test.php', {
id: id
},function (data) {
console.log(data);
var Server = data.server;
var Photo = data.photo;
console.log(Server);
console.log(Photo);
}, 'json');
Another solution is setting proper header in you PHP response:
Content-Type text/javascript; charset=UTF-8
then jQuery Intelligent Guess, will set proper data type itself.
You can use parseJSON method, exposed by jQuery. This enables you to map the properties to a type, of sorts, such as:
var results = jQuery.parseJSON(jsonData);
for (int i = 0; i < results.length; i++) {
alert(results[i].name + ":" + results[i].date);
}
You may need to tweak the inputs and exact use of the outputs in accordance with your data and requirements.
getJSON() will parse the JSON for you after fetching, so from then on, you are working with a simple Javascript array ([] marks an array in JSON).
You can get all the values in an array using a for loop:
$.getJSON("url_with_json_here", function(data){
for (var i=0, len=data.length; i < len; i++) {
console.log(data[i]);
}
});
Another example:
Parse a JSON string.
var obj = jQuery.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" )
;

Categories

Resources