i have a little script which fetches the likes and tweets count about a url via jquery. Now it works great, but when a certain page has 0 like/shares, then jquery returns 'undefined' because the 'shares' part is not shown in the output.
$(document).ready(function() {
url = "http://awebsitehere.com/";
beforecounter = " <b>";
aftercounter = "</b>";
// Get Number of Facebook Shares
$.getJSON('http://graph.facebook.com/'+url+'&callback=?',
function(data) {
$('#facebook').append(beforecounter + data.shares + aftercounter);
});
// Get Number of Tweet Count
$.getJSON('http://urls.api.twitter.com/1/urls/count.json?url='+url+'&callback=?',
function(data) {
$('#twitter').append(beforecounter + data.count + aftercounter);
});
})
How would I have to edit this script to display 0 instead of undefined when facebook has got 0 shares/likes for a certain url?
try this:
$('#facebook').append(beforecounter + (data.shares || 0) + aftercounter);
and likewise for the twitter value.
At first you have to create a username of your page(see under your page name #username. Just click it...)
Then goto https://developers.facebook.com/tools/explorer/ and get an access token key
Then script something like that
function facebookLikesCount(access_token, pageusername)
{
var url = "https://graph.facebook.com/"+pageusername+"?fields=likes&access_token="+access_token+"";
$.getJSON(url,function(json){
alert(json.likes);
});
}
facebookLikesCount('your accesstoken', 'pageusername');
its work for me.
Related
I want to pass a checked value (upon hitting the submit button) to the .js function. The .js function should then take that checked value and query data from a sqlite db and AWS to populate the current webpage.
Here is what I think is happening in the posted code below. After checking a single box and hitting submit, the checked value is being passed to function getQuestionData(). Within getQuestionData(), an endpoint is created using the passed value then function appendInnerHTML is called to populate the page with queried data.
The error I get is
unreachable code after return statement[Learn More]
applied to the 4th line from the bottom ---- q.append('img').
I also noticed that whichever box is checked, my local URL changes. For example, if the box with Coordinate Geometry is checked, the url changes to
http://127.0.0.1:5000/?topic=Coordinate+Geometry
I had some help setting this up so I'm not 100% clear on the fundamentals, if that wasn't already obvious..
CODE
HTML
<form id="checkboxes">
<input type="submit" id="submitTopic" onsubmit="getQuestionData(this.value)">
</form>
.js
function getQuestionData() {
sampleValue = $('input[id=submitTopic]:checked').val()
//document.getElementById("submitTopic").value;
document.getElementById("question").innerHTML = ""
document.getElementById("solve").innerHTML = ""
var endPointQuestionData = '/api/v1/questions/' + sampleValue
Plotly.d3.json(endPointQuestionData, function(error, response) {
if (error) return console.warn(error);
appendInnerHMTL(response)
});
};
//populates webpage with data from sqlite db
function appendInnerHMTL(response) {
d3.select("#solve")
.append('h2')
.text("Solve.")
for (var i = 0; i < response.length; i++){
q = d3.select("#question")
d = q.append('div')
.append('strong')
.text(response[i]['id'])
d.append('div')
button = d.append('input')
.attr('class','button')
.attr('type','button')
.attr('value','Show Answer')
.attr('onclick','showAnswer('+ i + ')')
shownAnswer = d.append('div')
.attr('class','shownAnswer')
.text(response[i]['ans'])
document.getElementsByClassName('shownAnswer')[i].style.display='none';
//appends image from Amazon AWS to each id
q.append('img')
.attr('src', 'https://s3-us-west-1.amazonaws.com/actmath/' + response[i]['date'] + '/' + response[i]['id'] + '.JPG')
//retrieve .jpg file if .JPG file not found
.attr('onerror', 'this.oneerror=null;this.src=\"https://s3-us-west-1.amazonaws.com/actmath/' + response[i]['date'] + '/' + response[i]['id'] + '.jpg\";')
}
};
I have a Tag in tag manager that feeds me back the data of fields that have been showing as invalid when a user tries to submit a form but its missing or has invalid fields.
This is done using the following code:
// Get user Agent
var Uagent = navigator.userAgent;
// Validation Errors Check
document.getElementById("btnSubmit").onclick = function() {
errorLoop();
}
function errorLoop() {
var runner = document.getElementsByClassName("invalid"),
formEmail = document.getElementById('email').value,
dataL = [];
dataLayer.push({'formEmail' : formEmail});
if (runner) {
for (var i = 0; i < runner.length; i++) {
var errName = runner[i].getAttribute("name"),
errId = runner[i]
.getAttribute("id");
dataL.push("Field: " + errName + " - ID: " + errId);
} //End for
dataL.toString();
var vadout = dataL + " Device: " + Uagent;
console.log(dataL);
dataLayer.push({
'formEmail' : formEmail,
'validationError': vadout,
'event' : 'errorpush'
});
} //End if
} //End errorLoop
So whats basically happening here is on a submit we are checking the form to see if any of the fields have the class invalid & if it does then it add's the name & Id of the fields to an array then prints then prints the array into a data layer.
The tag itself is triggered using a custom event called errorpush.
The issue is that this works only about 80% of the time we still get alot of people get validation errors but the validation errors don't seem to make it to the datalayer and back to google analytics.
I'm considering adding a settimeout delay to the datalayer push which I will go away and try but wanted to see if anyone knows of anything right off the bat which could be causing this problem.
Your runner is declared as empty array if there are no elements with class name "invalid". But your if statement is only checking for declaration thus:
if(runner){
}
will always be true but there are no "invalid" elements. Consequently dataL.push("Field: " + errName + " - ID: " + errId);will never execute in your for loop but dataLayer.push will, and so you will get errorpush event without any errors.
To solve this, I would suggest to rewrite your if statement:
if(runner.length > 0){
}
I hope this solves your problem.
I have one page with a json table pulling in information from the json api. This works fine. Now my issue is, On the far right column i'm wanting a link to another page of mine, This link will be a unique link. At the moment, As you can see by the code, i can get it to link to the html page 12345, But all the rows link through to this. Which does not help Ha!
I'm ideally wanting the first button to link to 1.html then second button to link to 2.html and so on and so forth.
Here is the code i have so far.
for(var i =0;i < json.results.collection1.length;i++) {
var title = json.results.collection1[i].Name.text;
var venue = json.results.collection1[i].Venue.text;
var date = json.results.collection2[i].Date;
var button = "<button class='redirect-button' data-url='12345.html'>Link</button>";
$("#apple").append("<tbody><tr><td>"+title+"</td><td>"+venue+"</td><td>"+date+"</td><td>"+button+"</td></tr></tbody>");
$("#apple").find(".redirect-button").click(function(){
location.href = $(this).attr("data-url");
});
}
},
Obviously all help would be greatly appreciated. Thanks Sam
Just to explain the comment above
The link you're creating is a <button> but really it's just a string.
So by concatenating the URL part of the string based on something (like your i index in your loop) you can change it to anything you want.
so for example :
var button = "<button class='redirect-button' data-url='" + i + " .html'>Link</button>";
this gives an element that looks like :
<button class='redirect-button' data-url='0.html'>Link</button>
would give you 0.html, 1.html, etc (change the data-url='" + i + " .html' to data-url='" + (i+1) + " .html' and you get 1.html, 2.html, 3.html...)
or if you can change the API to give you a proper link in the return you can make it a bit more readable with:
var button = "<button class='redirect-button' data-url='" + json.results.collection2[i].LinkUrl + " .html'>Link</button>";
results in :
<button class='redirect-button' data-url='abcd.html'>Link</button>
assuming the return is called LinkURL and it's value is 'abcd'
Finally you append this string to the $("#apple") element and then the click event is added that looks for the data-url value and changes the current browser location to that new value.
I am new to javascript, i am trying to make a small site with two HTML pages (A and B) and a global js file.
So lets say i have selected certain items in page A, the list-preview on Page A gets updated.
But if i want to see the list in detail i have to go to page B.
Page A and B bith use the same .js file, the selected items are saved in a array.
How do i make sure the selected items still stay in the array, and the array doesn't get flushed when i go from page A to page B ?
what i thought of was ...
var selectedProductsName = new Array();
in OwnJS.js
the adding items to the preview list works.
i'm only struggling to keep the array unflushed when i go to page B from page A.
HTML5 introduces a new thing called localStorage. It's basically some kind of storage that is persistent between all pages of your website as well as between user sessions. It can be accessed as a simple key/value store:
var selectedProductsName = localStorage.getItem("selectedProductsName");
And to set:
localStorage.setItem("selectedProductsName", []);
Here's an article about getting started with localStorage, if you want to be able to do more things like checking browser compatibility for localStorage and watching the storage event, among others.
You could use the HTML5 local storage. It lets you tell the browser to save data on the user's machine. (There's also session storage, valid only for the current session.)
Save (in Apply.html)
IN.API.Profile("me")
.fields(["id", "firstName", "lastName", "pictureUrl","headline","industry","location:(name)","positions:(title)","emailAddress"])
.result(function(result) {
profile = result.values[0];
// save all keys to local storage
for (f in profile) localStorage[f] = fields[f];
// more stuff ...
});
to Retrieve (in personal_Info.html)
// retrieve first name from local storage
var firstName = localStorage["firstName"];
if (firstName !== undefined) {
$("#textfield1").attr(value, firstName);
}
Source Page
The Source Page has an HTML Button with a jQuery Click event handler. When the Button is clicked, the values of the Name TextBox and the Technology DropDownList is set as QueryString Parameter and then the page is redirected to the Destination page (Page2.htm).
<input type="button" id="btnQueryString" value="Send" />
<script type="text/javascript">
$(function () {
$("#btnQueryString").bind("click", function () {
var url = "Page2.htm?name=" + encodeURIComponent($("#txtName").val()) + "&technology=" + encodeURIComponent($("#ddlTechnolgy").val());
window.location.href = url;
});
});
</script>
Destination Page
On the Destination page (Page2.htm), inside the jQuery Page Load event handler the URL of the page is first checked to determine whether it has some QueryString Parameters being received, this is done by checking the window.location.search property. If it has some QueryString Parameters then loop is executed and each QueryString Key and Value Pair is inserted in an Array and finally the values are displayed on the page using the HTML span.
<script type="text/javascript">
var queryString = new Array();
$(function () {
if (queryString.length == 0) {
if (window.location.search.split('?').length > 1) {
var params = window.location.search.split('?')[1].split('&');
for (var i = 0; i < params.length; i++) {
var key = params[i].split('=')[0];
var value = decodeURIComponent(params[i].split('=')[1]);
queryString[key] = value;
}
}
}
if (queryString["name"] != null && queryString["technology"] != null) {
var data = "<u>Values from QueryString</u><br /><br />";
data += "<b>Name:</b> " + queryString["name"] + " <b>Technology:</b> " + queryString["technology"];
$("#lblData").html(data);
}
});
</script>
I'm desiging a dynamic dropdown form that will help my customers choose the right product for them and was looking to test the function to output the final results. When I add the JS function to take the info from the last dropdown and use it to build the results list the whole script seems to break. My console in Chrome spits out Uncaught SyntaxError: Unexpected string (pointing to the third to last line of the broken JS) although its nearly identical to my other functions except for some changed variables.
Basically, I use JS to pull info from dropdowns which sends that data using GET to a PHP script. The script then uses that data to query an SQL DB to dynamically build a list of options for the next dropdown. After the last dropdown of the form the JS would parse the PHP script to receive some data (a table eventually) and update a DIV with that data. This is where the script breaks. Adding that last JS function breaks the script while removing it keeps it working.
You can test the working script here and the broken script here.
Here's the working JS:
$(function(){
$("#type").change(function() {
var tval = document.getElementById('type').value;
$("#source").load(encodeURI("findbackend.php?type=" + tval));
});
$("#source").change(function() {
sval = document.getElementById('source').value;
$("#range").load(encodeURI("findbackend.php?source=" + sval));
});
$("#range").change(function() {
rval = document.getElementById('range').value;
$("#setpoint").load(encodeURI("findbackend.php?range=" + rval));
});
$("#setpoint").change(function() {
stval = document.getElementById('setpoint').value;
$("#dig_num").load(encodeURI("findbackend.php?range=" + rval + "&setpoint=" + stval));
});
});
And here's the broken JS:
$(function(){
$("#type").change(function() {
var tval = document.getElementById('type').value;
$("#source").load(encodeURI("findbackend.php?type=" + tval));
});
$("#source").change(function() {
sval = document.getElementById('source').value;
$("#range").load(encodeURI("findbackend.php?source=" + sval));
});
$("#range").change(function() {
rval = document.getElementById('range').value;
$("#setpoint").load(encodeURI("findbackend.php?range=" + rval));
});
$("#setpoint").change(function() {
stval = document.getElementById('setpoint').value;
$("#dig_num").load(encodeURI("findbackend.php?range=" + rval + "&setpoint=" + stval));
});
$("#dig_num").change(function() {
dnum = document.getElementById('dig_num').value;
$("#findresults").load(encodeURI("findbackend.php?range=" + rval + "&setpoint=" + stval "&dig_num=" + dnum));
});
});
I've looked it over a hundred times and can't figure out what's breaking the script.
If you'd like to see the PHP or anything just let me know.
Thanks in advance for any help.
Again, you can view the working script here and the broken script here.
You forgot to add a "+" sign after stval.
$("#findresults").load(encodeURI("findbackend.php?range=" + rval + "&setpoint=" + stval + "&dig_num=" + dnum));