Search facebook pages using javascript - javascript

I have an HTML application to search Facebook pages using pure JavaScript, no other libraries and no back-end.Most of the APIs that deal with searching and reading "pages" do not require user authorization, and they support JSONP (through the "callback" parameter).
My HTML code, index.html
<!doctype html>
<head>
<title>FaceBook Page Search API</title>
<script type="text/javascript" src='js/app.js'></script>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div class="container">
<div class="form-search">
<h3>Search FaceBook Pages</h3>
<p class="form-search-row"><input id="searchPages" type="text" placeholder="Enter name">
<button class="btn btn-medium btn-success" onclick="getData()" type="submit">Search</button>
</p>
</div>
</div>
<div class="offset1 pull-center page-results">
</div>
</body>
</html>
and app.js,
var getData = function(){
var my_JSON_object = {};
var http_request = new XMLHttpRequest();
var str, queryInput = document.getElementById("searchPages");
var searchFormRow = document.getElementsByClassName('form-search-row')[0];
var image=document.createElement('img');
if(!queryInput.value){
return;
}
str = encodeURIComponent(queryInput.value);
image.setAttribute('src', 'img/ajax-loader.gif');
image.setAttribute('width', '30px');
searchFormRow.appendChild(image);
var url = "https://graph.facebook.com/search?type=page&q="+ str;
http_request.open("GET", url, true);
http_request.onreadystatechange = function () {
var done = 4, ok = 200;
if (http_request.readyState == done && http_request.status == ok) {
my_JSON_object = JSON.parse(http_request.responseText);
displayResults(my_JSON_object);
image.parentNode.removeChild(image);
}
};
http_request.send(null);
};
var displayResults = function(pages){
var resultDiv = document.getElementsByClassName('page-results')[0];
if(pages.data.length){
resultDiv.innerHTML = "";
}
else{
resultDiv.innerHTML = "No results found";
}
for(var i=0; i<pages.data.length; i++)
{
var name = pages.data[i].name, category = pages.data[i].category, id= pages.data[i].id;
var page = document.createElement("div");
var pname = document.createElement("p");
var findmore = document.createElement("a");
var pcategory = document.createElement("p");
pname.innerHTML = name;
findmore.innerHTML = " find out more";
findmore.href= "detail.html?id="+id;
findmore.target = "_blank";
pname.appendChild(findmore);
pcategory.innerHTML = "Category: " + category;
pcategory.setAttribute('class',"small-font");
page.setAttribute('class','span2 pageDiv');
page.appendChild(pname);
page.appendChild(pcategory);
resultDiv.appendChild(page);
console.log(pages.data[i].name);
}
};
var getPageDeatil = function(){
var query = window.location.search.substring(1);
var vars = query.split("=");
getDetailsAjax(vars[1]);
};
var getDetailsAjax = function(pageId){
var my_JSON_object = {};
var http_request = new XMLHttpRequest();
var str = encodeURIComponent(pageId);
var url = "https://graph.facebook.com/"+ str;
http_request.open("GET", url, true);
http_request.onreadystatechange = function () {
var done = 4, ok = 200;
if (http_request.readyState == done && http_request.status == ok) {
my_JSON_object = JSON.parse(http_request.responseText);
displayDetailsResult(my_JSON_object);
}
};
http_request.send(null);
};
var displayDetailsResult = function(detail){
var resultDiv = document.getElementById('details');
var displayImage;
for (key in detail) {
if (detail.hasOwnProperty(key)) {
if(key=="cover"){
displayImage =true;
}
else{
var li = document.createElement("li");
li.setAttribute('class',"removeDecor");
li.innerHTML = key+ " : " + detail[key];
resultDiv.appendChild(li);
}
}
}
if(displayImage){
var heading = document.getElementById('header');
var image = document.createElement('img');
image.setAttribute('src', detail.cover.source);
heading.insertBefore(image);
}
};
Finally, the detail.html
<!doctype html>
<head>
<title>FaceBook Page Search API - Detail Page</title>
<script type="text/javascript" src='js/app.js'></script>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body onload="getPageDeatil()">
<div class="container">
<h3 id="header">More about Page</h3>
<div class="well">
<ul id="details">
</ul>
</div>
</div>
</body>
</html>
But it gives the following error in console.
{
"error": {
"message": "(#200) Must have a valid access_token to access this endpoint",
"type": "OAuthException",
"code": 200
}
}
Page search API do not require authorization right ? Then how can I solve this ?

Thanks for all, finally solved my problem by referring Facebook Developer Documentation.
First, got details about access_token here, https://developers.facebook.com/docs/reference/api/search/#access_tokens
Searches across page and place objects requires an app access token.
Each application should be registered in https://developers.facebook.com/apps to get an app_id and secret_id.
After getting this details,
Generate access_token using this URL https://graph.facebook.com/oauth/access_token?client_id=app_id&client_secret=secret_id&grant_type=client_credentials
The app_id and secret_id should be changed with generated one.
And changed my request URL in app.js file like this,
var access_token = ""; // my access token here
var url = "https://graph.facebook.com/search?type=page&q="+ str +"&access_token="+access_token;

Related

.send(formData) Error "GET 404 .../upload.php (Not Found)"

i've found this code on a website for uploading files using javascript, but it doesn't seems to work. Could somebody help me with that please?
Index.php :
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<link href="style.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="container">
<div class="row">
<div id="uploads"></div>
<div class="dropzone" id="dropzone">
Drop files fere to upload
</div>
</div>
</div>
<script src="js_script.js" type="text/javascript"></script>
</body>
</html>
And js :
(function() {
var dropzone = document.getElementById('dropzone');
var displayUploads = function(data) {
var uploads = document.getElementById('uploads'),
anchor,
x;
for (x = 0; x < data.length; x = x + 1) {
anchor = document.createElement('a');
anchor.href = data[x].file;
anchor.innerText = data[x].name;
uploads.appendChild(anchor);
}
};
var upload = function(files) {
var formData = new FormData(),
xhr = new XMLHttpRequest(),
x;
for (x = 0; x < files.length; x = x + 1) {
formData.append('file[]', files[x]);
}
xhr.onload = function() {
var data = JSON.parse(this.responseText);
displayUploads(data);
};
xhr.open('post', 'upload.php');
xhr.send(formData);
};
dropzone.ondrop = function(e) {
e.preventDefault();
this.className = 'dropzone';
upload(e.dataTransfer.files);
};
dropzone.ondragover = function() {
this.className = 'dropzone dragover';
return false;
};
dropzone.ondragleave = function() {
this.className = 'dropzone';
return false;
};
}());
and upload.php :
<?php
header("Content-Type: application/json");
$uploaded = array();
if(!empty($_FILES['file']['name'][0])){
foreach($_FILES['file']['name'] as $position => $name){
if(move_uploaded_file($_FILES['file']['tmp_name'][$position], 'uploads/'.$name)){
$uploaded[] = array(
'name' => $name,
'file' => 'uploads/'.$name
);
}
}
}
echo json_encode($uploaded);
?>
And now this issue :
GET .../upload.php 404 (Not Found)
and related code to issue :
xhr.send(formData);
btw what is that "GET" showing in console??
I just saved the file "Upload.php" with uppercase "U" which should be "upload.php".

how to define a var from json to js?

I'm a newbie in javascript and need your help.
I don't know what to do and how to do to make this working:
I have the following js and html code:
var slides = '';
var slideImg = slider.images;
var i;
for (var i=0; i<slider.images.length; i++) {
slides += '<div id="slide'+i+'" class="slideEl" ><img src="'+slider.images[i].src+'"><div class="container-images">'+slider.images[i].CTA.text+'</div></div>';
}
document.getElementById('slides').innerHTML = slides;
document.getElementById('slides').style.width = window.innerWidth * (slideImg.length) + 'px';
document.getElementById('slides').style.transitionDuration = slideImg[0].speed + 's';
document.getElementById('slides').style.left = 0;
var indexSlide = 0;
function moveSlide(params) {
var slideWidth = document.getElementsByClassName('slideEl')[0].offsetWidth;
document.getElementById('slides').style.transitionDuration = slideImg[0].speed + 's';
var element = document.getElementById('slides');
var rect = element.getBoundingClientRect();
var newPos = rect.left;
if(params == 'right' && indexSlide < slideImg.length -1){
newPos -= slideWidth;
indexSlide++;
} else if (params == 'left' && indexSlide > 0) {
newPos += slideWidth;
indexSlide--;
}
document.getElementById('slides').style.transitionDuration = slider.images[indexSlide].speed + 's';
document.getElementById('slides').style.left = newPos + 'px';
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>JS exercise</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/png" href="media/favicon-32x32.png" />
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
<link rel="stylesheet" type="text/css" media="screen" href="css/style.css" />
</head>
<body>
<div id="slider">
<div id="slides" class="slides"></div>
<div class="container-slider">
<span id="arrowLeft" class="arrow" onclick="moveSlide('left')">〈</span>
<span id="arrowRight" class="arrow" onclick="moveSlide('right')">〉</span>
</div>
</div>
<footer>Copyright © 2019</footer>
<script language="javascript" src="js/script.js"></script>
<script type="text/javascript" src="js/data.json"></script>
</body>
</html>
and besides that, I have another file called data.json:
[{
"autoplay" : "yes",
"transition" : "slide",
"images" :[
{
"src" : "https://some-img.jpg",
"speed" : "1.5",
"CTA" : {
"text" : "Join Now",
"link" : "http://test.com",
"position" : "bottom-right"
}
},
{
"src" : "https://some-img.jpg",
"speed" : "1.5",
"CTA" : {
"text" : "Join Now",
"link" : "http://test.com",
"position" : "bottom-right"
}
},
{
"src" : "https://some-img.jpg",
"speed" : "1.5",
"CTA" : {
"text" : "Join Now",
"link" : "http://www.test.com",
"position" : "bottom-right"
}
}
]
}]
How can I get the slider var from json to javascript just to defined the length of the whole slider?
EDIT(from answer):
#Mrunmay Deswandikar, I've added this piece of code at the start of my script.js file:
var xhttp = new xmlhttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(xmlhttp.responseText);
}
};
xhttp.open("GET", "http://wip.2mo.ro/sandra/js-slider/js/data.json", true);
xhttp.send();
var slides = '';
var slideImg = slider.images;
.....
I got this error: Uncaught ReferenceError: xmlhttpRequest is not defined
at script.js:1
(anonymous) # script.js:1
What am I missing?
Many thanks,
Sandra
Script tags are not meant to be used to load json data. Use fetch instead.
fetch('js/data.json')
.then(res=>res.json())
.then(data=>{
const slider = data.shift();
/** rest of your code here */
})
.catch(err=>{
console.log(err.message);
});
Fetch by default uses promises, but if you prefer to use it with async/await (syntaxical sugar for Promises).
async function loadData(){
const res = await fetch('/js/data.json');
const data = await res.json();
const slider = data.shift();
/** rest of code here */
}
loadData().catch(err=>console.log(err);
To get the data from json, use Ajax request to load JSON file.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(xmlhttp.responseText);
}
};
xhttp.open("GET", "data.json", true);
xhttp.send();
This will get all the data of data.json file, into variable data.
If your data.json file is located at the same directory, else you can use releative path, but best way will be use server path, like,
xhttp.open("GET","https://yourwebsite/DIRECTORY/data.json",true);

troubles in a simple weather webapp using openweathermaps API

Initially I had 3 separates .js files, one for each city to test the api, and it worked perfectly.
Now i'm trying to insert all the 3 request in a single .js file, to make all the request at the same time and call a single js from the html, but i am unable to do it.
var APPID = "b4d7400359e1dd91c7dee5cf238c9681";``
var temp1;
var loc1;
var icon1;
var temp2;
var loc2;
var icon2;
var temp3;
var loc3;
var icon3;
function updateById1(){
var url = "http://api.openweathermap.org/data/2.5/weather?id=2525689&APPID=" + APPID;
sendRequest(url);
}
function updateById2(){
var url = "http://api.openweathermap.org/data/2.5/weather?id=2525473&APPID=" + APPID;
sendRequest(url);
}
function updateById3(){
var url = "http://api.openweathermap.org/data/2.5/weather?id=3173435&APPID=" + APPID;
sendRequest(url);
}
function sendRequest (url){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
console.log(xmlhttp.status);
if (xmlhttp.readyState ===
XMLHttpRequest.DONE && xmlhttp.status === 200){
var data = JSON.parse(xmlhttp.responseText);
var weather = {};
weather.icon = data.weather[0].id;
weather.loc = data.name;
weather.temp = K2C(data.main.temp);
update(weather);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function K2C (k) {
return Math.round(k-273.15);
}
function update(weather){
loc.innerHTML = weather.loc;
temp.innerHTML = weather.temp;
icon.src = "imgs/codes/" + weather.icon + ".png";
//console.log(icon.src);
}
window.onload = function () {
temp1 = document.getElementById.innerHTML= "temperature1";
loc1 = document.getElementById("location1");
icon1 = document.getElementById("icon1");
temp2 = document.getElementById("temperature2");
loc2= document.getElementById("location2");
icon2 = document.getElementById("icon2");
temp3 = document.getElementById("temperature3");
loc3 = document.getElementById("location3");
icon3 = document.getElementById("icon3");
updateById1();
updateById2();
updateById3();
}
Here the html
<html>
<head>
<meta charset="utf-8"/>
<title>Weather App</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<div class="weather-app">
<div class="arborea">
<div class="temperature"><span id="temperature1">0</span>°</div>
<div class="location"><span id="location1">Unknown</span></div>
<div class="top">
<img id="icon1" width="75px" src="imgs/codes/200.png"/>
</div>
</div>
<div class="cagliari">
<div class="temperature"><span id="temperature2">0</span>°</div>
<div class="location"><span id="location2">Unknown</span></div>
<div class="top">
<img id="icon2" width="75px" src="imgs/codes/200.png" />
</div>
</div>
<div class="milano">
<div class="temperature"><span id="temperature3">0</span>°</div>
<div class="location"><span id="location3">Unknown</span></div>
<div class="top">
<img id="icon3" width="75px" src="imgs/codes/200.png" />
</div>
</div>
</div>
</body>
</html>
Your update function had loc and temp which were undefined. I have updated and tested the code. Let me know if you need help in understanding anything in particular.
Always look at console (right click -> inspect element -> console) for errors.
var APPID = "b4d7400359e1dd91c7dee5cf238c9681";
var temp1;
var loc1;
var icon1;
var temp2;
var loc2;
var icon2;
var temp3;
var loc3;
var icon3;
function updateById1() {
var url = "http://api.openweathermap.org/data/2.5/weather?id=2525689&APPID=" + APPID;
sendRequest(url, 1);
}
function updateById2() {
var url = "http://api.openweathermap.org/data/2.5/weather?id=2525473&APPID=" + APPID;
sendRequest(url, 2);
}
function updateById3() {
var url = "http://api.openweathermap.org/data/2.5/weather?id=3173435&APPID=" + APPID;
sendRequest(url, 3);
}
function sendRequest(url, id) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
console.log(xmlhttp.status);
if (xmlhttp.readyState ===
XMLHttpRequest.DONE && xmlhttp.status === 200) {
var data = JSON.parse(xmlhttp.responseText);
var weather = {};
weather.icon = data.weather[0].id;
weather.loc = data.name;
weather.temp = K2C(data.main.temp);
update(weather, id);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function K2C(k) {
return Math.round(k - 273.15);
}
function update(weather, id) {
switch (id) {
case 1:
loc1.innerHTML = weather.loc;
temp1.innerHTML = weather.temp;
icon1.src = "imgs/codes/" + weather.icon + ".png";
break;
case 2:
loc2.innerHTML = weather.loc;
temp2.innerHTML = weather.temp;
icon2.src = "imgs/codes/" + weather.icon + ".png";
break;
case 3:
loc3.innerHTML = weather.loc;
temp3.innerHTML = weather.temp;
icon3.src = "imgs/codes/" + weather.icon + ".png";
break;
default:
console.log("incorrect id")
}
}
window.onload = function() {
temp1 = document.getElementById("temperature1");
loc1 = document.getElementById("location1");
icon1 = document.getElementById("icon1");
temp2 = document.getElementById("temperature2");
loc2 = document.getElementById("location2");
icon2 = document.getElementById("icon2");
temp3 = document.getElementById("temperature3");
loc3 = document.getElementById("location3");
icon3 = document.getElementById("icon3");
updateById1();
updateById2();
updateById3();
}

When using XLSX to parse excelsheet - it is throwing _fs is undefined

I am trying to use the XLSX library to read data from excelsheet but I am getting this:-
ERROR: _fs is undefined at xlsx.js (line 11388, col 59)
Here is my code :-
<html>
<head>
<title>Read Excel</title>
<meta meta http-equiv="Content-Type" content="text/html;" charset="UTF-8"/>
</head>
<body>
<script src="xlsx.js"></script>
<script>
function actionbegins(){
console.log("Inside the function action begins !!");
if(typeof XLSX === 'undefined' && typeof require !== 'undefined')
XLSX = require('xlsx');
var workbook = XLSX.readFile("Invoice.xlsx", {type: 'base64'});
var first_sheet_name = workbook.SheetNames[0];
var address_of_cell = 'A2';
var worksheet = workbook.Sheets[first_sheet_name];
var desired_cell = worksheet[address_of_cell];
var desired_value = desired_cell.v;
console.log("we got the value as --> "+desired_value);
}
</script>
<button id="btnDoIt" onclick="actionbegins()" name="btnDoIt" class="btn btn-primary">do It !!</button>
</body>
</html>
I tried searching the net for a suitable answer but could not find any. Please suggest.
It was not working because the file wasn't loaded completely and it started processing it.
Here is the code that is working absolutely fine :
<html>
<head>
<title>Read Excel</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script lang="javascript" src="dist/xlsx.core.min.js"></script>
</head>
<body>
<script>
function letsdoit(){
var url = "Invoice.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
oReq.onload = function(e) {
var arraybuffer = oReq.response;
/* convert data to binary string */
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for(var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
var bstr = arr.join("");
var workbook = XLSX.read(bstr, {type:"binary"});
var first_sheet_name = workbook.SheetNames[0];
var address_of_cell = 'A1';
var worksheet = workbook.Sheets[first_sheet_name];
var desired_cell = worksheet[address_of_cell];
var desired_value = desired_cell.v;
alert("value is -- "+desired_value);
}
oReq.send();
}
</script>
<input type="file" name="file" id="selectfile" onchange="letsdoit()" />
</body>
</html>

Disqus in Ionic APP

I am trying to implement disqus commments in my ionic app. I know I have to host it on the domain its setup for which I believe I have configured correctly. Any assistance will be welcomed
Here is the code in my app.js for the ionic app
$scope.showComments = function () {
$scope.currentView = "comments";
//loadComments(params["shortname"], params["url"], params["title"], params["identifier"]);
//
var disqus_title = "Venue 1";
var disqus_identifier = '/venue/' + $stateParams.id;
var disqus_url = 'liverpool.li/venue/' + $stateParams.id;
var url = "http://liverpool.li/app/disqus.html?";
$scope.url = url + "shortname=liverpoolli&url=" + encodeURIComponent(disqus_url) +
"&title=" + encodeURIComponent(disqus_title) + "&identifier=" + encodeURIComponent(disqus_identifier);
$scope.url = $sce.trustAsResourceUrl($scope.url);
};
$scope.$on("$destroy", function () {
if ($scope.lastScriptElm && $scope.lastScriptElm.parentNode) {
$scope.lastScriptElm.parentNode.removeChild($scope.lastScriptElm);
$scope.lastScriptElm = null;
}
});
And the page it points to (disqus.html) located on my domain
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
</head>
<body>
<div id="disqus_thread"></div>
<script type="text/javascript">
var params;
var disqus_url;
var disqus_title;
var disqus_shortname;
var disqus_identifier;
window.onload = function () {
var match,
pattern = /\+/g,
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pattern, " ")); },
query = window.location.search.substring(1);
params = {};
while (match = search.exec(query))
params[decode(match[1])] = decode(match[2]);
if (params["shortname"] === undefined || params["url"] === undefined || params["title"] === undefined) {
alert("Required arguments missing");
}
else {
loadComments(params["shortname"], params["url"], params["title"], params["identifier"]);
}
};
function loadComments(shortname, url, title, identifier) {
disqus_url = url;
disqus_title = title;
disqus_shortname = shortname;
if (identifier !== undefined)
disqus_identifier = identifier;
else
disqus_identifier = "";
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = false;
dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
}
</script>
<noscript>Please enable JavaScript to view the comments powered by Disqus.</noscript>
blog comments powered by <span class="logo-disqus">Disqus</span>
</body>
</html>
I get the following error
we were unable to load disqus. if you are a moderator please see our
troubleshooting guide.
It looks like you're almost there. The only issue I see is the disqus_url variable must also include the protocol to be valid. Try using this line instead:
var disqus_url = 'http://liverpool.li/venue/' + $stateParams.id;

Categories