Send an app request dialog to specific array of id's - javascript

I;m trying to send a request dialog to my friends on facebook but to a few selected ones, i have created an array and i need to send invitation only to the id's on that array, i have this code built but it's not working.
It looks like it stops all my page's performance
//function to load friends
function loadFriends()
{
//get array of friends
FB.api('/me/friends?fields=name,first_name,gender', function(response) {
console.log(response);
var divContainer=$('.facebook-friends');
var testdiv = document.getElementById("test");
for(var i=0; i<response.data.length; i++){
if(response.data[i].gender == 'male'){
testdiv.innerHTML += response.data[i].first_name + response.data[i].id + '<br />';
}
}
var arr = []; // Creates an empty array literal.
for(var i=0; i<response.data.length; i++){
arr.push(response.data[i].id);
}
newInvite(arr); // Call your function and pass the friends array
});
}
function newInvite(arr){
FB.ui({ method: 'apprequests',
message: 'Penelope for WAS',
filters: ['app_non_users'],
to:arr.join(',')
});
}

You should use comma separated list as to parameter, not an array.
FB.ui({
method: 'apprequests',
message: 'Penelope for WAS',
filters: ['app_non_users'],
to:arr.join(',')
});
Your code is also have mistake while dealing with JavaScript variable scope.
newInvite is a function which missing arr variable definition (and arr not in global scope, you should pass it to newInvite so it'll be available to your function internals.
function newInvite(arr){
FB.ui({
method: 'apprequests',
message: 'Penelope for WAS',
filters: ['app_non_users'],
to:arr.join(',')
});
)
And for sure you should pass array of friends ids to the function:
FB.api('/me/friends', {fields:'name,first_name,gender'}, function(response) {
var arr = []; // Creates an empty array literal.
for(var i=0; i<response.data.length; i++){
arr.push(response.data[i].id);
}
newInvite(arr); // Call your function and pass the friends array
});

Related

search a class name in multiple pages and get the urls with that class with javascript

I'm trying to search in an array of urls if there is a class name in any of the pages and get a new array with the urls that have thas class name.
This is what I have:
var urls = ["https://www.url.com/withclass","https://www.url.com/withoutclass"];
var classToFind=document.getElementsByClassName('empty');
var results = [];
function findClassURL(url, classempty){
jQuery.ajax({
url: url,
dataType: 'text',
type: 'GET',
complete: function(classname){
if(typeof classempty === 'function')
classempty.apply(this, [classname.all]);
}
});
}
for(var i = 0; i < urlsToSearch.length; i++) {
findClassURL(results.push(urlsToSearch[i]), function() {
if(all){
console.log(results + ' ok');
}
else {
console.log(urlsToSearch + ' has products');
}
});
}
Right now this gets me an 404 error.
Please help me to know if there is any other way of doing this
Thanks
Before your for loop, I'd define an empty array to hold your results in (the urls that have the className in them. Like so:
let results = [];
Then, if a given url has the className, you add the url to the results array like so:
results.push(urlsToSearch[i]
Then at the end of your function, return the results like so:
return results;

Get Pointer Id only , using Parse

this returns an object. I just want to get the id. I will use it for a query
var q= new Parse.Query("Comments");
q.find({
success: function (results) {
for (var i=0; i< results.length;i++) {
console.log(results[i].get("user_id"));
}
});
i actually found it out by exploring, i've used to access just the id
results[i].get("user_id").id

Retrieve list items from multiple lists with urls stored in an array

How do i get list items from different lists in SharePoint using javascript. Given that all my list are stored in an array. And I need to loop through the array and execute similar functions on each list.
function initializePage() {
listcollections.forEach(function (value, index) { // listcollections is the array that contains the list url for different lists
var listtitle = value.listTitle;
var siteUrl = value.siteURL;
getItemsWithCaml(siteUrl, listtitle,
function (camlItems) {
var listItemEnumerator = camlItems.getEnumerator();
while (listItemEnumerator.moveNext()) {
var EventsItem = new Events();
var listItem = listItemEnumerator.get_current();
EventsItem.eventTitle = listItem.get_item('Title');
EventsItem.eventDate = listItem.get_item('EventDate');
EventsItem.eventId = listItem.get_id();
EventsItem.eventSite = siteUrl;
EventsItem.eventList = listtitle;
EventsCollection.push(EventsItem);
}
},
function (sender, args) {
alert('An error occurred while retrieving list items:' + args.get_message());
});
})
};
function getItemsWithCaml(siteUrl, listtitle, header, success, error)
{
var hostWebContext = new SP.ClientContext(siteUrl);
var list = hostWebContext.get_web().get_lists().getByTitle(listtitle);
var caml = new SP.CamlQuery();
//Create the CAML that will return only items expiring today or later
caml.set_viewXml("<View><Query><Where><Geq><FieldRef Name=\'Expires\'/><Value Type=\'DateTime\'><Today /></Value></Geq></Where> </Query></View>");
var camlItems = list.getItems(caml);
hostWebContext.load(camlItems);
hostWebContext.executeQueryAsync(
function () {
success(camlItems);
},
error
);
};
//need to execute certain functions to format each list item
// I am not able to retrieve all list items in a single variable to be able to display data from all lists together
In the example below, I create a JavaScript object named ListDataCollection that contain a property Lists that is an array of objects.
Each of those contain a Url property whit the url of the lists I want to get the content.
Then I loop trough the array of objects and call the Sharepoint REST api for each Url.
Each time a call is complete :
I create a Data property on the current object with the data received
by the ajax call to the REST api.
I also update the current object Completed property to true.
Then I call a function named ifAllCompleted that check if all ajax calls are ended.
When all data is received, I log the word Completed on the browser console.
At this point, you have an array of objects. Each object contains the data of one Sharepoint list.
For example :
ListDataCollection.Lists[0].Data.d.results[0].Title
will contain the value of the Title Column of the first element in the first list.
If you want, you can merge all data in one array using the concat function in JavaScript.
Look at the 4 lines of code following the word Completed.
Hope this can help!
<script>
var ListDataCollection = {
Lists:[{
Url:"http://Url.Of.Your.Site.Collection/_api/web/lists/getbytitle('List1')/Items",
Completed:false
},{
Url:"http://Url.Of.Your.Site.Collection/_api/web/lists/getbytitle('List2')/Items",
Completed:false
},{
Url:"http://Url.Of.Your.Site.Collection/_api/web/lists/getbytitle('List3')/Items",
Completed:false
}]
};
function ifAllCompleted() {
for (var i=0;i<ListDataCollection.Lists.length;i++) {
if (!ListDataCollection.Lists[i].Completed) {
return false;
}
}
console.log('Completed');
var arrayOfAllData = ListDataCollection.Lists[0].Data.d.results;
arrayOfAllData = arrayOfAllData.concat(ListDataCollection.Lists[1].Data.d.results);
arrayOfAllData = arrayOfAllData.concat(ListDataCollection.Lists[2].Data.d.results);
console.log('Total elements : ' + arrayOfAllData.length);
}
$(document).ready(function(){
for (var x=0;x<ListDataCollection.Lists.length;x++) {
$.ajax({
url:ListDataCollection.Lists[x].Url,
indexValue:x,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data, status, xhr) {
ListDataCollection.Lists[this.indexValue].Data = data;
ListDataCollection.Lists[this.indexValue].Completed = true;
ifAllCompleted();
},
error: function (xhr, status, error) {
console.log('error');
}
});
}
});
</script>

Make array jquery/js

I want to make an array like this. (on alert it gives object)
var playlist = [{"title":"Kalimba","mp3":"http://www.jplayer.org/audio/mp3/TSP-01-Cro_magnon_man.mp3"}];
From:
var playlist = [];
$.ajax({
url: 'url.php',
data: {
album_name: album_name
},
type: 'POST',
success: function( data ) {
var data_array = JSON.parse(data);
for( var i=0; i<data_array.length; i++ ) {
var value = data_array[i].split('::');
playlist.push('{"title":"Kalimba","mp3":"http://www.jplayer.org/audio/mp3/TSP-01-Cro_magnon_man.mp3"},'); // putting the same thing just for testing.
}
alert(playlist);
}
});
Now the new array playlist didn't seem to be working for me. i guess there is something wrong the way i am creating an array like above.
you need to push object instead of object string:
playlist.push({"title":"Kalimba","mp3":"http://www.jplayer.org/audio/mp3/TSP-01-Cro_magnon_man.mp3"});
//------------^---remove the single quote.
Try this one
var playlist =[{"title":"Kalimba","mp3":"http://www.jplayer.org/audio/mp3/TSP-01-Cro_magnon_man.mp3"}];
alert(JSON.stringify(playlist));
Use jQuery.map() for making array.
playlist = $.map(data_array, function(val, i){
splitArr = val.split('::')
return {
'title':splitArr[0],
'mp3':splitArr[1]
}
})
As #Jai said you need to push an object: playlist.push({"title":"Kalimba","mp3":"http://www.jplayer.org/audio/mp3/TSP-01-Cro_magnon_man.mp3"});
Arrays in JavaScript are objects.
You'd be better using the console to log or debug your javascript.
In this fiddle you can see
that the array is created and the object pushed to it but its
still logged as an object.
And since you are using jQuery it has a method isArray() to determine if
something is an array or not.
or you can try like this
var playlist = [];
$.ajax({
url: 'url.php',
data: {
album_name: album_name
},
type: 'POST',
success: function( data ) {
var data_array = JSON.parse(data);
for( var i=0; i<data_array.length; i++ ) {
var value = data_array[i].split('::');
var ArrObj = '{"title":"Kalimba","mp3":"http://www.jplayer.org/audio/mp3/TSP-01-Cro_magnon_man.mp3"},';
playlist.push(ArrObj);
}
alert(playlist);
}
});

Cant access Javascript multidimensional array

I have seen many of these questions on here but none seem to solve my problem. I have a multidimensional (nested) array which I am populating through query. I wish to send the final array over AJAX jQuery:
(function() {
var orderDetails = [];
orderDetails['retailer'] = [];
orderDetails['order'] = [];
db.transaction(function(qry){
qry.executeSql("SELECT * FROM retailers WHERE pending = '1' ", [], function(tx, results){
len = results.rows.length; //if rows.length, means retailer is pending so add details to array. If no length, means retailer exists
for (var i=0; i<len; i++){
console.log('start '+i+' loop in retailers qry');
orderDetails['retailer'][i] = [];
orderDetails['retailer'][i]['localID'] = results.rows.item(i).ID;
orderDetails['retailer'][i]['retailerName'] = results.rows.item(i).retailerName;
orderDetails['retailer'][i]['address'] = results.rows.item(i).address;
orderDetails['retailer'][i]['postcode'] = results.rows.item(i).postcode;
console.log('finish '+i+' loop in retailers qry');
}
}, function(err){console.log(err)})
}
This is how I am populating the array, and here is the AJAX request:
function(){
console.log('start orders qry success callback');
//alert(orderDetails['retailer'][0]['localID']);
var st = JSON.stringify(orderDetails['retailer']);
console.log(st);
$.ajax({//send retailer to server, bring back the ID of the retailer as it is on the server so we can insert it into the order
type: "POST",
cache: false,
//async: false,
url: "https://www.......processOrder.php",
data: { orderType: 'saved', orderDetails: st},
dataType: "json",
success: function(result){
}
})
});
When I log the above just before the ajax request, it returns [[],[],[],[],[],[],[],[],[],[],[]] so I know something is working, I just thought the whole contents of the object would be visible on the server side.
Also I have wrapped the whole thing in an anonymous function because I think this helps the array variable scope.
Change this orderDetails['retailer'][i] = []; to this orderDetails['retailer'][i] = {};
And if your item is not a function you want to call with parameter i, access it like this: results.rows.item[i].ID

Categories