I'm trying to add both Facebook and Twitter share counters together, however all my efforts have failed.
<script>
tweets = 0;
function getTwitterCount(url){
$.getJSON('http://urls.api.twitter.com/1/urls/count.json?url=' + url + '&callback=?', function(data){
tweets = data.count;
$('#twitterCount').html(tweets);
return true;
});
}
var urlBase='http://abcdfav4.com/About/KickStarterCampaign/Rewards/ThePeaceSensation.html';
getTwitterCount(urlBase);
$.ajax({
type: 'GET',
url: 'https://graph.facebook.com/http://abcdfav4.com/About/KickStarterCampaign/Rewards/ThePeaceSensation.html',
success: function(data) {
showCount(data);
}
});
var fbshares = 0;
function showCount(responseText) {
// Save the parsed JSON
var json = responseText;
// Check if the response contains a 'shares' property
// If it doesn't, we can just exit this function
if (!json.hasOwnProperty('shares'))
return;
// A shares property and value must exist, update
// the span element with the share count
fbshares = json.shares;
$('#fb-share-count').html(fbshares);
}
var TotalShares = tweets + fbshares;
$('#total-share-count').html(TotalShares);
</script>
I could really do with some outside insight as I've been working crazy to get this website up and running ASAP and I'm probably overlooking the most obvious of things...
Console Log Reads:
Uncaught ReferenceError: fbshares is not defined
sdk.js:64 Invalid App Id: Must be a number or numeric string representing the application id.
card.html?v=2:79 Uncaught ReferenceError: I18n is not defined
sdk.js:64 FB.getLoginStatus() called before calling FB.init().
However despite this message, the Facebook and Twitter counters are working 100%, I just cannot get them to add together.
Best Regards,
Tim
Here's a solution:
var tweets;
function getTwitterCount(url) {
$.getJSON('http://urls.api.twitter.com/1/urls/count.json?url=' + url + '&callback=?', function(data) {
tweets = data.count;
$('#twitterCount').html(tweets);
showTotal();
});
}
var urlBase = 'http://abcdfav4.com/About/KickStarterCampaign/Rewards/ThePeaceSensation.html';
getTwitterCount(urlBase);
$.ajax({
type: 'GET',
url: 'https://graph.facebook.com/http://abcdfav4.com/About/KickStarterCampaign/Rewards/ThePeaceSensation.html',
success: showCount
});
var fbshares;
function showCount(responseText) {
// Save the parsed JSON
var json = responseText;
// Check if the response contains a 'shares' property
// If it doesn't, we can just exit this function
if (!json.hasOwnProperty('shares'))
return;
// A shares property and value must exist, update
// the span element with the share count
fbshares = json.shares;
$('#fb-share-count').html(fbshares);
showTotal();
}
function showTotal() {
if (tweets !== undefined && fbshares !== undefined)
$('#total-share-count').html(tweets + fbshares);
}
Basically showTotal attempts to sum the two values after each callback. When both values are defined, it will place the sum into the HTML.
Related
Hi I am trying to retrieve some data from webservice using AngularJS $http get.
I have the following code snippet:
In the servicesjs:
.factory('BoothDesignatedCoordsService', ['$http', function ($http) {
var factory = {};
factory.getBoothDesignatedCoords = function (strBoothName, intFloorPlanID) {
var sendToWS;
var boothDesignatedCoords
var JSONObj = {
BoothName: strBoothName,
FloorPlanID: intFloorPlanID
};
sendToWS = JSON.stringify(JSONObj)
var urlBase = 'http://localhost:4951/wsIPS.asmx/fnGetBoothDesignatedCoords?objJSONRequest=' + sendToWS;
return $http.get(urlBase)
}
return factory;
}])
In the controllerjs:
var boothDesignatedCoords = BoothDesignatedCoordsService.getBoothDesignatedCoords(strListShortListedBooth[i], 3).success(function (response, data, status) {
console.log("successfully send booth name and floor plan id to ws");
console.log("data " + data + " , status : " + status);
console.log("data " + data);
boothDesignatedCoords = data;
for (var c = 0; c < boothDesignatedCoords.length; c += 2) {
}
The $http get is successful as I am able to print "successfully send booth name and floor plan id to ws" in the browser console log.
When I tried to print console.log("data " + data), it gives me some values of an integer array. That is exactly what I want. But in the controller I tried to assign data to the variable boothDesignatedCoords, the program does not run the for loop. Am I missing some code?
EDIT:
I tried to trace the code ( trace the variable called "data" in the controllerjs) and it says "data is not defined"
You appear to be confused about the methods available on the $http promise and their arguments. Try this
BoothDesignatedCoordsService.getBoothDesignatedCoords(strListShortListedBooth[i], 3)
.then(function(response) {
var data = response.data
var status = response.status
console.log('data', data) // note, no string concatenation
// and so on...
})
FYI, the success and error methods have been deprecated for some time and removed from v1.6.0 onwards. Don't use them.
I also highly recommend passing query parameters via the params config object
var urlBase = 'http://localhost:4951/wsIPS.asmx/fnGetBoothDesignatedCoords'
return $http.get(urlBase, {
params: { objJSONRequest: sendToWS }
})
This will ensure the key and value are correctly encoded.
Hello I have the following code in a Content Editor Web Part, which retrieves the current user's name and displays it in a message box :
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
function getUser() {
var userid = _spPageContextInfo.userId;
//alert(userid);
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
var requestHeaders = { "accept": "application/json;odata=verbose" };
$.ajax({
url: requestUri,
contentType: "application/json;odata=verbose",
headers: requestHeaders,
success: onSuccess,
error: onError
});
function onSuccess(data, request) {
var loginName = data.d.Title;
alert(loginName);
}
function onError(error) {
alert("Error on retrieving current user.");
}
}
$(document).ready(function() {
getUser();
});
</script>
I was also able to display the email with alert(data.d.Email);.
However, when I try calling data.d.Groups (as per the documentation - which shows that a Groups property exists), I see a message box with [object Object].
How can I retrieve the individual items from this (what I am assuming is a) collection?
I have tried :
var group = data.d.Groups[0];
alert(group);
But this just comes up with undefined.
Am I wrong in thinking that this object will contain my Department?
Either way, is there a way of iterating through these objects, or have I done it correctly but on an empty array?
Thank you
Attempt at Logging the groups
function onSuccess(data, request) {
var loginName = data.d.Title;
console.log(loginName);
var groups = data.d.Groups;
console.log(groups);
}
I can't see either of the above logs in the F12 console window... (Internet Explorer)
Attempt 2 - Logging Successful
Using the code below, I was able to achieve the same results as before, but this time the console.log() calls actually worked (still have no idea why the previous ones didn't):
ExecuteOrDelayUntilScriptLoaded(init,'sp.js');
var currentUser;
function init(){
this.clientContext = new SP.ClientContext.get_current();
this.oWeb = clientContext.get_web();
currentUser = this.oWeb.get_currentUser();
this.clientContext.load(currentUser);
this.clientContext.executeQueryAsync(Function.createDelegate(this,this.onQuerySucceeded), Function.createDelegate(this,this.onQueryFailed));
}
function onQuerySucceeded() {
var groups = currentUser.get_groups();
alert(groups);
console.log(groups);
var name = currentUser.get_loginName();
alert(name);
console.log(name);
var id = currentUser.get_id();
alert(name);
var title = currentUser.get_title();
alert(title);
var email = currentUser.get_email();
alert(email);
}
function onQueryFailed(sender, args) {
alert('Request failed. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}
After calling console.log(groups);, the following appeared in the F12 console :
"data.d.Groups" is the Object, When you pass this into .html(data.d.Groups) you will get it as [object Object] only because object will convert as the string Just loop the object and you will get the key and value
for (key in data.d.Groups){
alert("key: " + key + "value :" + data.d.Groups[key]);
}
I was able to find a rather ugly solution to this, but it does work.
First, we need to call some .js files in preperation:
<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.0.min.js"></script>
<script src="/_layouts/15/SP.Runtime.js"></script>
<script src="/_layouts/15/SP.js"></script>
<script src="/_layouts/15/SP.UserProfiles.js"></script>
Then, inside a <script language="javascript" type="text/javascript"> tag, we declare some global variables and 2 main functions...
var currentUser;
var currentUserName;
var property = "Department";
1. GetCurrentUserProperty(property):
This function actually only gets the current user for us and, if successful will call loadUserData (which actually gets the property we defined earlier for the given user:
// This function first gets the current user's firstname.lastname username (e.g. Joe.Bloggs).
// If this is successful, it calls the loadUserData function, which will retrieve the user's
// property which was defined in the global "property" variable.
function GetCurrentUserProperty(){
this.clientContext = new SP.ClientContext.get_current();
this.oWeb = clientContext.get_web();
currentUser = this.oWeb.get_currentUser();
this.clientContext.load(currentUser);
this.clientContext.executeQueryAsync(onQueryUserSuccess, onQueryUserFail);
}
function onQueryUserSuccess() {
// If the query is successful, extract the first.last username and then call loadUserData
window.currentUserName= currentUser.get_loginName().split("\\")[1];
loadUserData(window.currentUserName);
}
function onQueryUserFail(sender, args) {
alert('Failed to retrieve user name');
}
2. loadUserData
This function takes the given user.name and will get the property that is stored in property for that user. Here, in the success function, I am just outputting the result to an alert window:
function loadUserData(userName){
//Get Current Context
var clientContext = new SP.ClientContext.get_current();
//Get Instance of People Manager Class
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
//Property to fetch from the User Profile
var strDepartment = window.property;
//If you are on On-Premise:
var targetUser = "BARDOM1\\" + userName;
//Create new instance of UserProfileProperty
departmentProperty = peopleManager.getUserProfilePropertyFor(targetUser, strDepartment)
//Execute the Query. (No load method necessary)
clientContext.executeQueryAsync(onSuccess, onFail);
}
function onSuccess() {
var messageText = window.property + " is " + departmentProperty .get_value();
alert(messageText);
}
function onFail(sender, args) {
alert("Error: " + args.get_message());
}
Finally, to actually run this process, we need to call GetCurrentUserProperty();. I put all of this code into a file called testproperty.js and saved it in SiteAssets. Then, on the page where we want the code to run, add a Content Editor Web Part and in edit -> path the call is ../../SiteAssets/testproperty.js. This will run once the page load - hope this helps anyone else who may be stuck on this!
It is obvious that "result" is coming back as null from the query. If that is the case, why is it calling the "success" routine? I know that the course I am searching for does exist.
Any ideas?
var query = new Parse.Query("Courses");
var CourseObj = new Parse.Object("Courses");
query.equalTo("courseIdFromIOS", request.params.courseIdFromIOS);
query.first({
success: function (result) {
CourseObj = result;
response.success("course lookup good for: " + CourseObj.get("courseName"));
},
error: function () {
response.error("course lookup failed");
}
});
A query always enters success loop if we are able to connect to Parse servers and searched through all the rows even if our query was unsuccessful since there is no error code corresponding to unsuccessful query .Once check this guide and also error codes section.
https://www.parse.com/docs/js/guide#handling-errors
So in your case result is undefined
var query = new Parse.Query("MyClass");
var tmp = new Parse.Object("MyClass");
query.equalTo("username", "This does not exist in table");
query.first({
success: function (result) {
tmp = result;
alert("hii");
alert("course lookup good for: " + tmp.get("name"));
},
error: function () {
alert("helloooo");
}
});
Even in the above code it is entering success loop
I can't seem to figure out this problem where the below code works when the "for loop" is disabled, and the attributes "locations" and "startAddress" are just simple strings. But if they are not, I am getting a "this is undefined" error when the ajax post request is submitted. Do you have any ideas why would this be? Any leads would be appreciated.
// create an event handler for the save route button
$("#saveRouteButton").click(function(){
var saveRouteName = $("#saveRouteNameField").val();
if (!saveRouteName) {
alert("Please supply a proper name to be submitted to the database");
} else {
var routeLength = directionsDisplay.getDirections().routes[0].legs.length;
var returnRoute = {
alias: null,
locations : [], // make this a string - it works!
startAddresses : [], // make this a string - it works!
};
// disable this loop - it works!
for (var i = 0; i < routeLength; i++){
returnRoute.locations[i] = directionsDisplay.getDirections().routes[0].legs[i].start_location
returnRoute.startAddresses[i] = directionsDisplay.getDirections().routes[0].legs[i].start_address
};
route_info = returnRoute;
route_info.alias = saveRouteName;
//test to see if the variables are set, they are!
alert(route_info.alias);
alert(route_info.locations);
alert($.isPlainObject(route_info))
$.ajax({
url: "save_route/",
type: "POST",
data : route_info,
success: function(data){
if (data != "None") {
$("#savedRoutesList").append('<li class="savedRoutesListItem">'
+ data + '</li>');
}
else {alert("You need to enter a route name");}
}
});
}
return false;
});
the error originates from the : google maps main js - line 13
Thanks!
Just check the route Length value,whether it is giving correct value or not?
I have a series of ajax calls that fill columns on a page.
var doneDefers = function(defer) {
// leftColDefer is another deferred that sets some header info
$.when(defer, leftColDefer).done(function(req1, req2){
var data = req1[0],
head = req2[0];
// spit this data out to elements on the page
});
};
for(i=0;i<window.ids.length;i++){
defer[i] = $.ajax({
url: 'api/get_runs_stats.php',
type: 'GET',
dataType: 'json',
data: {
run_id: window.ids[i]
}
});
doneDefers(defer[i]);
}
This works fine. If an ajax call fails, nothing is spit out and all is right with the world.
Now I want to do some calculations based on all the data that got spit out.
$.when.apply(null, defer)
.done(function() {
var args = Array.prototype.slice.call(arguments);
calcDeltas();
})
.fail(function() {
var args = Array.prototype.slice.call(arguments);
console.log('in list fail');
});
The done function works fine none of the ajax calls fail. If one of them fail, I go into the fail function and I don't have access to any of the return data from the other runs. The arguments array only has the failed call's data.
I would like to do my calculations on the data sets that passed. How can I get to the data from the good calls when one of them fails?
I'm not sure this is the simplest solution but it stands a chance of working.
var ajax_always_promises = [],//to be populated with promises that (barring uncaught error) are guaranteed to be resolved.
data_arr = [],//an array to be (sparsely) populated with asynchronously delivered json data.
error_arr = [];//an array to be (sparsely) populated with ajax error messages.
$.each(window.ids, function(i, id) {
var dfrd = $.Deferred();
var p = $.ajax({
url: 'api/get_runs_stats.php',
type: 'GET',
dataType: 'json',
data: {
run_id: window.ids[i]
}
}).done(function(json_data) {
data_arr[i] = json_data;//intentionally not `data_arr.push(json_data);`
}).fail(function(jqXHR, textStatus, errorThrown) {
error_arr[i] = textStatus;//intentionally not `error_arr.push(textStatus);`
}).always(dfrd.resolve);
ajax_always_promises[i] = dfrd.promise();
doneDefers(p);
});
$.when.apply(null, ajax_always_promises).done(function() {
//The data in the (sparsely) populated arrays `data_arr` and `error_arr` is available to be used.
var i, id, success_count=0, error_count=0;
for(i=0; i<Math.max(data_arr.length,error_arr.length); i++) {
//Here, the index i corresponds to the original index of window.ids ...
//...that's the advantage of sparsely populating the arrays.
id = window.ids[i];
if(data_arr[i]) {
//Here, do whatever is required with `data_arr[i]`, and `id` if needed.
success_count++;
}
else if(error_arr[i]) {
//Here, do whatever is required with `error_arr[i]`, and `id` if needed.
error_count++;
}
}
console.log("Success:errors: " + success_count + ':' + error_count);
});
Untested - may well need debugging