so I've built a little game (with p5.js library) and wanted to implement a Leaderboard loaded from a JSON file, used as a kind of DB to store Username/score, all of this using a Node.js server, with express installed to make things easier. So here is the html (with ajax code) :
<html>
<head>
<title>KassBric - Mouetto</title>
<meta charset="UTF-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/p5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/addons/p5.dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/addons/p5.sound.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script language="javascript" type="text/javascript" src="sketch.js"></script>
<script language="javascript" type="text/javascript" src="Paddle.js"></script>
<script language="javascript" type="text/javascript" src="Ball.js"></script>
<script language="javascript" type="text/javascript" src="Brick.js"></script>
<script language="javascript" type="text/javascript" src="Grid.js"></script>
<script language="javascript" type="text/javascript" src="Attractor.js"></script>
<script language="javascript" type="text/javascript" src="methods.js"></script>
<script language="javascript" type="text/javascript" src="Bonus.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript">
$.ajax({
url: '/scores.json',
dataType: 'json',
success: function(data) {
var keys = Object.keys(data);
for(var i = 0; i < keys.length; i++) {
var username = keys[i];
var score = data[username];
var row = $('<tr><td>' + username + '</td><td>' + score + '</td></tr>');
$('#Leaderboard').append(row);
}
},
error: function(jqXHR, textStatus, errorThrown){
alert('Error: ' + textStatus + ' - ' + errorThrown);
}
});
</script>
</head>
<body>
<div>
<p id="LeaderboardHolder" style = "background-color : rgb(51, 51, 51); color: rgb(150, 150, 150); padding: 15px;">
<table id="Leaderboard">
<tr>
<th>Username</th>
<th>Best Score</th>
</tr>
</table>
</p>
</div>
</body>
</html>
this is my server.js :
console.log("server is starting");
var express = require('express');
var fs = require('fs');
var app = express();
var server = app.listen(3000, listen);
function listen() {
console.log("Listening...");
};
app.use(express.static('public'));
var data = fs.readFileSync('scores.json');
var scores = JSON.parse(data);
console.log(scores);
app.get('/leaderboard', showLeaderboard);
function showLeaderboard(request, response){
response.send(scores);
};
app.get('/leaderboard/add/:username/:score?', addPlayer);
function addPlayer(request, response){
var data = request.params;
var username = data.username;
var score = Number(data.score);
var type = typeof score;
if(!score || type !== 'number'){
var reply = "Score is required, and must be a number.";
}else{
scores[username] = score;
var data = JSON.stringify(scores, null, 2);
fs.writeFile('scores.json', data, finished);
function finished(err){
console.log("Updated the database.");
var reply = {
request: "Submitted",
username: username,
score: score
};
};
};
response.send(reply);
};
app.get('/leaderboard/:username', showPlayer);
function showPlayer(request, response){
var word = request.params.username;
if(scores[word]){
var reply = {
username: word,
score: scores[word]
};
}else{
var reply = {
msg: "Username not found"
};
};
response.send(reply);
};
and my directory looks like :
-Project:
-node_modules
-public:
-index.html (code above)
-all my game files & folders
-packages.json
-scores.json
-server.js
and so, with this running with Node/Express, I get an error:
"GET http://localhost:3000/scores.json 404 (Not Found)"
and by doing more tests, I tried to run a "basic" python SimpleHTTPServer in my project directory (in the public folder) and I get no errors, ajax gets the data and parses it into the html table. I can't find why this does work with python's server and not my node one ...
Your Ajax url /scores.json but you don't have the route to /scores.json in server.js
In this case my solution is:
$.ajax({
url: '/handler',
dataType: 'json',
success: function(data) {
var keys = Object.keys(data);
for(var i = 0; i < keys.length; i++) {
var username = keys[i];
var score = data[username];
var row = $('<tr><td>' + username + '</td><td>' + score + '</td></tr>');
$('#Leaderboard').append(row);
}
},
error: function(jqXHR, textStatus, errorThrown){
alert('Error: ' + textStatus + ' - ' + errorThrown);
}
});
and in server.js:
app.get('/handler', function(req, res) {
var filePath = path.join(__dirname, '/scores.json');
var file = fs.readFileSync(filePath, 'utf8');
var result = JSON.parse(file);
res.send(result);
}
Sorry for my English.
Related
I am using this phonegap(js) code to upload a recorded video to php server.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
<title>Mobile_Insurance</title>
</head>
<body>
<script type="text/javascript">
$(document).ready(function(){
$('input[name="visit"]').click(function(){
var inputValue = $(this).attr("value");
var targetBox = $("." + inputValue);
$(".box").not(targetBox).hide();
$(targetBox).show();
});
});
function captureSuccess(mediaFiles) {
var i, len;
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
uploadFile(mediaFiles[i]);
}
}
// Called if something bad happens.
//
function captureError(error) {
var msg = 'An error occurred during capture: ' + error.code;
navigator.notification.alert(msg, null, 'Uh oh!');
}
// A button will call this function
//
function captureVideo() {
// Launch device video recording application,
// allowing user to capture up to 2 video clips
navigator.device.capture.captureVideo(captureSuccess, captureError, {limit: 1});
}
// Upload files to server
function uploadFile(mediaFile) {
var ft = new FileTransfer(),
path = mediaFile.fullPath,
name = mediaFile.name;
var options = new FileUploadOptions();
options.chunkedMode = true;
options.fileKey = "file";
options.fileName = name;
options.mimeType = "video/mp4";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
ft.upload(path, "http://192.168.0.46/upload/upload.php",
function(result) {
console.log('Upload success: ' + result.responseCode);
console.log(result.bytesSent + ' bytes sent');
console.log("Response = " + r.response);
alert("Response = " + r.response);
},
function(error) {
console.log('Error uploading file ' + path + ': ' + error.code);
alert('Error uploading file ' + path + ': ' + error.code);
},
options);
alert(mediaFile.fullPath);
}
</script>
<script type="text/javascript" src="cordova.js"></script>
<div data-role="page">
<div data-role="header">
<h3>Welcome </h3>
</div>
<div data-role="main" class="ui-content">
<h3 style="text-align: center;">Input Your IMEI:</h3>
<input type="number"/>
<h3 style="text-align: center;"> yes?</h3>
<input type="radio" name="visit" value="YES" id="Video"> YES
<input type="radio" name="visit" value="NO" id="self"> NO
<br>
<h3 style="text-align: center;"> damage.</h3>
<input type="radio" name="damage" value="Physical"> Physical
<input type="radio" name="damage" value="Water"> Water <br><br>
<h3 style="text-align: center;">Please give a breig description about the damage</h3><br>
<textarea rows="5" cols="10" style="resize:none"></textarea>
<div class="YES box"><input type="button" value="self analysis" hidden="true"></div>
<div class="NO box"> <button onclick="captureVideo();">Capture Video</button></div>
</div>
</div>
</body>
</html>
This is my php code..
<?php
print_r($_FILES);
$new_image_name = "r.mp4";
move_uploaded_file($_FILES["file"]["tmp_name"], $new_image_name);
?>
The uploadFile function is supposed to upload the file to the specified php file. but in my case the phonegap filetransfer is giving error code 1 which is file not found. I have alert the file path after capture which is same file to be uploaded. How is it throwing error code 1?
Try this, you might be able to use this
http://findnerd.com/list/view/Capturing-and-Uploading-Video-to-PHP-Server-in-Cordova/9398/
From the site:
If you want to send image as base64 string you can change destination
type to Camera.DestinationType.DATA_URL and you can send imageData to
server via ajax call. or, if you want to send as file array then keep
the same destination type to camera.DestinationType.FILE_URI and use
cordova file plugin to send file data in server:
var options = new FileUploadOptions();
options.fileKey="tickitFile";
options.fileName=imageData.substr(imageData.lastIndexOf('/')+1);
options.contentType = "multipart/form-data";
options.chunkedMode = false;
options.mimeType="image/jpeg";
options.httpMethod="POST";
options.headers = {
Connection: "close"
};
var ft = new FileTransfer();
ft.upload(imageData, PHP_URL, win, fail, options);
function win(r) {
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
function fail(error) {
console.log(JSON.stringify(error));
}
you can try this below :
function upload(file){
var fd = new FormData();
fd.append("dir", dir);
fd.append("file", file);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload.php', true);
xhr.send(fd);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
//alert(xhr.responseText);
var message = xhr.responseText;
message=message.trim();
if ( message != 0)
{
//alert(message);
}
}
};
}
and the php file :
<?php
if (isset($_FILES["file"]["name"])) {
$destination = $_POST["dir"];
$name = $_FILES["file"]["name"];
$tmp_name = $_FILES['file']['tmp_name'];
$error = $_FILES['file']['error'];
//echo $name;
//echo $tmp_name;
//echo $error;
move_uploaded_file($_FILES['file']['tmp_name'], $destination.$name);
}
echo "File transfer completed";
?>
XHR POST has no size limit, but you're sending data to PHP which has a size limit ;) Create the following php-file and open it in a browser:
Now search for the variable "post_max_size", this variable limits the maximum data that can be sent to PHP (but it can be changed in the php.ini)
My upload function and my php file works perfectly for an input file like :
var obj=document.getElementById("inputfile");
var len = obj.files.length;
for (i=0; i<=len; i++){
upload( obj.files[i] );
}
for me the problem is the output type of your capturevideo() function or an error in captureSuccess(mediaFiles): try to change for smomething like this below :
function captureSuccess(mediaFiles) {
var i, len;
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
uploadFile(mediaFiles[i].fullPath);
}
}
I'm opening a new window to display a report using javascript and jquery in an MVC 4 application. The code is as follows.
window.open method:
$(document).ready(function () {
// validation stuff
submitHandler: function (form) {
var brewery = document.getElementById('BrewerySelect').value;
var line = document.getElementById('LineSelect').value;
var day = document.getElementById('datepicker').value;
var width = window.innerWidth * 0.66;
var height = width * window.innerHeight / window.innerWidth;
var urlStr = '/DashboardReport/Report?brewery=' + brewery + '&line=' + line.trim() + '&day=' + day;
alert(urlStr);
window.open(urlStr, 'newwindow', 'width=' + width + ', height=' + height + ', top=' + ((window.innerHeight - height) / 2) + ', left=' + ((window.innerWidth - width) / 2));
}
});
});
The controller does nothing, which I have tried as both PartialViewResult and ActionResult, the rest of the methods in the controller work fine for the ajax calls. The report works in a modal.:
public ActionResult Report()
{
return View();
}
The page that is opened:
#{
Layout = null;
}
<html>
<head>
<title>Report</title>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="reportBody" style="height: 100%;">
</div>
<script src="~/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="~/Scripts/scripts.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var brewery = GetURLParameter('brewery');
var line = GetURLParameter('line');
var day = GetURLParameter('day');
alert('document hit');
SetReport(brewery, line, day);
});
function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
function SetReport(brewery, line, day) {
var url = '#Url.Action("GetUrl")';
alert('SetReport Hit ( action url = ' + url + ')');
$.ajax({
url: url,
data: { breweryCode: brewery, packageLine: line, date: day },
dataType: 'json',
cache: false,
type: "POST",
success: function (data) {
alert('SetReport success. data = ' + data);
var url = '<iframe src="' + data + '" height="100%" width="100%" scrolling="auto"></iframe>';
$('#reportBody').html(url).show();
},
error: function (response) {
alert('document.ready() dashboardReportForm SetForm() method failed');
}
});
}
</script>
</body>
</html>
I've set alerts throughout the javascript to let me know what is getting hit, but none of the alerts are firing. The document.ready function is not being hit.
There's a U+200b character after the ending bracket of GetURLParameter function, which causes syntax error. Remove it and it should work.
See No visible cause for "Unexpected token ILLEGAL"
I am learning Nodejs with node cookbook 2nd edition.
I like this book because it is teaching us with explaining sample code which looks very practical.
The example code is part of Browser-server transmission via AJAX part
Anyway the main question is that below is in the EX code, below is index.html file
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script>
$.get("http://localhost:8080/profiles",function (profile_names) {
$.each(profile_names, function (i, pname) {
$("#profiles").append("<option>" + pname + "</option>");
});
}, "json");
$("#formats, #profiles").change(function () {
alert("2");
var format = $("#formats").val();
$.get("http://localhost:8080/profile/" + $("#profiles").val() + "." + format,
function (profile, stat, jqXHR) {
var cT = jqXHR.getResponseHeader("Content-Type");
$("#raw").val(profile);
$("#output").html('');
if (cT === "application/json") {
$.each($.parseJSON(profile), function (k, v) {
$("#output").append("<b>" + k + "</b> : " + v + "<br>");
});
return;
}
if (cT === "application/xml") {
profile = jqXHR.responseXML.firstChild.childNodes;
$.each(profile, function (k, v) {
if (v && v.nodeType === 1) {
$("#output").append("<b>" + v.tagName + "</b> : " + v.textContent + "<br>");
}
});
}
},
"text");
});
</script>
<style>
#frm, #raw {display:block; float:left; width:210px},
#raw {height:150px; width:310px; margin-left:0.5em}
</style>
<title> INDEX </title>
</head>
<body>
<form id="frm">
Profile: <select id="profiles">
<option> </option>
</select>
<br></br>
Format:<select id="formats">
<option value="json"> JSON </option>
<option value="xml"> XML </option>
</select>
<br></br>
<div id="output"></div>
</form>
<textarea id="raw"></textarea>
</body>
</html>
Second, server.js file
var http = require('http');
var fs = require('fs');
var path = require('path');
var profiles = require('./profiles');
var xml2js = require('xml2js');
var index = fs.readFileSync('index.html');
var routes, mimes = {xml: "application/xml", json: "application/json"}
function output(content, format, rootNode) {
if (!format || format === 'json') {
return JSON.stringify(content);
}
if (format === 'xml') {
return (new xml2js.Builder({rootName: rootNode})).buildObject(content);
}
}
routes = {
'profiles': function (format) {
return output(Object.keys(profiles), format);
},
'/profile': function (format, basename) {
return output(profiles[basename], format, basename);
}
};
http.createServer(function (request, response) {
var dirname = path.dirname(request.url),
extname = path.extname(request.url),
// $.get('http://localhost:8080/profile/' + $('#profiles').val() + '.' + format
basename = path.basename(request.url, extname);
extname = extname.replace('.', ''); //remove period
response.setHeader("Content-Type", mimes[extname] ||'text/html');
if (routes.hasOwnProperty(dirname)) {
response.end(routes[dirname](extname, basename));
return;
}
if (routes.hasOwnProperty(basename)) {
response.end(routes[basename](extname));
return;
}
response.end(index);
}).listen(8080);
below is profiles.js file
module.exports = {
ryan: {
name: "Ryan Dahl",
irc: "ryah",
twitter: "ryah",
github: "ry",
location: "San Francisco, USA",
description: "Creator of node.js"
},
isaac: {
name: "Isaac Schlueter",
irc: "isaacs",
twitter: "izs",
github: "isaacs",
location: "San Francisco, USA",
description: "Former project gatekeeper, CTO npm, Inc."
}
};
I think at index file $("#formats, #profiles").change(function () { is not working.
I just input alert("2"); to test the code but I have never seen the alert.
I also tried to change code like
$("#formats").change(function () {,
$("#profiles").change(function () {
Both of them were not working neither.
Can you let me know what is the reason?
Either wrap your client-code in a DOM ready statement or move it to the end of the <body>. Your script is being executed before the page has rendered.
You can see What I'm trying to do.
I want to Connect all the users in a session by providing them separate token under a
sessionId, so that they can view each other's streaming. But users can see only their
straming. I just need to allocate div on my page for each user with a token connected to any
particular sessionId.
This is the code using which users can see their streaming only
<script src="http://static.opentok.com/webrtc/v2.0/js/TB.min.js" ></script>
<script src="https://static.opentok.com/webrtc/v2.0/js/TB.min.js" ></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
var publisher;
var session;
var apiKey = "44686132";
var sessionId = "1_MX40NDY4NjEzMn4xMjcuMC4wLjF-V2VkIE1hciAxOSAyMDo1ODozNyBQRFQgMjAxNH4wLjAzMTA3MTAwN34";
var token = document.getElementById("<%= hdn1.ClientID %>").value;
publisher = TB.initPublisher(apiKey);
session = TB.initSession(sessionId);
session.connect(apiKey, token);
session.addEventListener("sessionConnected",
sessionConnectedHandler);
session.addEventListener("streamCreated",
streamCreatedHandler);
function sessionConnectedHandler(event) {
alert("sessionConnectedHandler");
subscribeToStreams(event.streams);
session.publish(publisher);
}
function subscribeToStreams(streams) {
if (stream.connection.connectionId
!= session.connection.connectionId) {
//var streams = event.streams;
for (var i = 0; i < streams.length; i++) {
var stream = streams[i];
var newDivId = "streams" + stream[i].streamId;
var newDiv = $('<div />', { id: newDivId });
$('body').append(newDiv);
if (stream.connection.connectionId
!= session.connection.connectionId) {
session.subscribe(stream[i], newDivId);
}
}
}
}
function streamCreatedHandler(event) {
subscribeToStreams(event.streams);
}
</script>
your session and publisher object are outside the scope of the other methods and your are probably getting errors. If you define session and publisher variables outside your method a() everything will work as expected.
<script type="text/javascript">
var session, publisher;
function sessionConnectedHandler(event)...
...
<script src="http://static.opentok.com/webrtc/v2.0/js/TB.min.js" ></script>
<script src="https://static.opentok.com/webrtc/v2.0/js/TB.min.js" ></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
var publisher;
var session;
var apiKey = "44686132";
var sessionId = "1_MX40NDY4NjEzMn4xMjcuMC4wLjF-V2VkIE1hciAxOSAyMDo1ODozNyBQRFQgMjAxNH4wLjAzMTA3MTAwN34";
var token = document.getElementById("<%= hdn1.ClientID %>").value;
publisher = TB.initPublisher(apiKey);
session = TB.initSession(apiKey,sessionId);
$.post('generate token url', data)
.success(function (data, status, headers, config) {
session.connect(data.token, function (error) {
if (error)
{
}
});
});
session.addEventListener("sessionConnected",
sessionConnectedHandler);
session.addEventListener("streamCreated",
streamCreatedHandler);
function sessionConnectedHandler(event) {
alert("sessionConnectedHandler");
subscribeToStreams(event.streams);
session.publish(publisher);
}
function subscribeToStreams(streams) {
if (stream.connection.connectionId
!= session.connection.connectionId) {
//var streams = event.streams;
for (var i = 0; i < streams.length; i++) {
var stream = streams[i];
var newDivId = "streams" + stream[i].streamId;
var newDiv = $('<div />', { id: newDivId });
$('body').append(newDiv);
if (stream.connection.connectionId
!= session.connection.connectionId) {
session.subscribe(stream[i], newDivId);
}
}
}
}
function streamCreatedHandler(event) {
subscribeToStreams(event.streams);
}
generate token every time new when u want to connect to singal session with diffrent token.
this code will help u.
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;