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);
}
}
Related
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".
I have a small test application to record the camera and sent the file to a directory on my server.
The main file is as follow:
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.WebRTC-Experiment.com/RecordRTC.js"></script>
<style>
video {
max-width: 100%;
border: 5px solid yellow;
border-radius: 9px;
}
body {
background: black;
}
h1 {
color: yellow;
}
</style>
</head>
<body>
<h1 id="header">RecordRTC Upload to PHP</h1>
<video id="your-video-id" controls="" autoplay=""></video>
<script type="text/javascript">
// capture camera and/or microphone
navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then(function(camera) {
// preview camera during recording
document.getElementById('your-video-id').muted = true;
document.getElementById('your-video-id').srcObject = camera;
// recording configuration/hints/parameters
var recordingHints = {
type: 'video'
};
// initiating the recorder
var recorder = RecordRTC(camera, recordingHints);
// starting recording here
recorder.startRecording();
// auto stop recording after 5 seconds
var milliSeconds = 5 * 1000;
setTimeout(function() {
// stop recording
recorder.stopRecording(function() {
// get recorded blob
var blob = recorder.getBlob();
// generating a random file name
var fileName = getFileName('webm');
// we need to upload "File" --- not "Blob"
var fileObject = new File([blob], fileName, {
type: 'video/webm'
});
uploadToPHPServer(fileObject, function(response, fileDownloadURL) {
if(response !== 'ended') {
document.getElementById('header').innerHTML = response; // upload progress
return;
}
document.getElementById('header').innerHTML = '' + fileDownloadURL + '';
alert('Successfully uploaded recorded blob.');
// preview uploaded file
document.getElementById('your-video-id').src = fileDownloadURL;
// open uploaded file in a new tab
window.open(fileDownloadURL);
});
// release camera
document.getElementById('your-video-id').srcObject = null;
camera.getTracks().forEach(function(track) {
track.stop();
});
});
}, milliSeconds);
});
function uploadToPHPServer(blob, callback) {
// create FormData
var formData = new FormData();
formData.append('video-filename', blob.name);
console.log("blob.name:");
console.log(blob.name);
formData.append('video-blob', blob);
callback('Uploading recorded-file to server.');
makeXMLHttpRequest('https://xxx/yyy/', formData, function(progress) {
if (progress !== 'upload-ended') {
callback(progress);
return;
}
var initialURL = 'https://xxx/yyy/' + blob.name;
callback('ended', initialURL);
});
}
function makeXMLHttpRequest(url, data, callback) {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
if (request.responseText === 'success') {
callback('upload-ended');
return;
}
alert(request.responseText);
return;
}
};
request.upload.onloadstart = function() {
callback('PHP upload started...');
};
request.upload.onprogress = function(event) {
callback('PHP upload Progress ' + Math.round(event.loaded / event.total * 100) + "%");
};
request.upload.onload = function() {
callback('progress-about-to-end');
};
request.upload.onload = function() {
callback('PHP upload ended. Getting file URL.');
};
request.upload.onerror = function(error) {
callback('PHP upload failed.');
};
request.upload.onabort = function(error) {
callback('PHP upload aborted.');
};
request.open('POST', url);
request.send(data);
}
// this function is used to generate random file name
function getFileName(fileExtension) {
var d = new Date();
var year = d.getUTCFullYear();
var month = d.getUTCMonth();
var date = d.getUTCDate();
return 'RecordRTC-' + year + month + date + '-' + getRandomString() + '.' + fileExtension;
}
function getRandomString() {
if (window.crypto && window.crypto.getRandomValues && navigator.userAgent.indexOf('Safari') === -1) {
var a = window.crypto.getRandomValues(new Uint32Array(3)),
token = '';
for (var i = 0, l = a.length; i < l; i++) {
token += a[i].toString(36);
}
return token;
} else {
return (Math.random() * new Date().getTime()).toString(36).replace(/\./g, '');
}
}
</script>
</body>
</html>
in the location where the files are stored I have the following file
<?php
// path to ~/tmp directory
$tempName = $_FILES['video-blob']['tmp_name'];
// move file from ~/tmp to "uploads" directory
if (!move_uploaded_file($tempName, $filePath)) {
// failure report
echo getcwd();
echo " | ";
echo 'Problem saving file: '.$tempName .' to ' .$filePath .' Not uploaded because of error #'.$_FILES['video-blob']['error'];
if (!is_writable($filePath)) {
echo " | ";
echo "dir not writable or existing";
}
die();
}
// success report
echo 'success';
?>
When I run this on my local server it works fine. But when I upload it to my windows 2012 R2 server I get the error
POST https://xxx/yyy/ 405 (Method Not Allowed)
I tried to play with the handler mappings in ISS and disabled WebDAV but no luck.
Since it works on the localhost but not on the windows server I figure it must be something related with the IIS setting but can not find out what.
Any help is appreciated.
In the end I found the error myself.
The settings in the web.config file where not standing correctly for FastCgiModule / StaticFileModules.
This is an cordova android app. Whenever i click on the delete img button it deletes the img and goes to home page but after doing two times it deletes img stays on same page which is fine.
I don't want it go to homepage. Please help.
//Html page
<div id="main">
<div id="server-div" style="display:none;">
Server URL :<input type="text" name="server_1" id="server_1"
value="http://www.indiafastener.com/webservices/listing/upload.php" />
</div>
<div id="gallery_images_list"></div>
<br>
<div><button style="color: black" id="remImg" onclick="delImg()"
hidden>Delete Image</button>
</div>
<br><img id="loader_icon" src="images/loader.gif" style="display:none;" />
<br>
<div id="picture_msg_1" style="color:green;font-size:11px;"> </div>
<br>
<div id="image-upload" onClick="uploadImageGallery()">
<img id="pimage_1" src="images/file-upload-1.png" width="64px"
height="64px" />
</div>
<input type="hidden" name="server_image_url_1" id="server_image_url_1">
</div>
//Code
//Upload image
function uploadImageGallery() {
var imgage = document.getElementById('pimage_1');
//$("#add_company_category").val("Loading gallery...");
//$("#add_company_category").html("Loading gallery...");
$("#loader_icon").css('display', 'block');
document.getElementById('picture_msg_1').innerHTML = "";
// Get URI of picture to upload
navigator.camera.getPicture(
function(uri) {
try {
// Pick image from div
var img = document.getElementById('pimage_1');
// var img_11 = document.getElementById('pimage_11');
img.style.visibility = "visible";
img.style.display = "block";
var imageURI = uri;
if (!imageURI || (img.style.display == "none")) {
document.getElementById('picture_msg_1').innerHTML = "Tap on picture to select image from gallery.";
return;
}
// Verify server has been entered
server = document.getElementById('server_1').value;
// server = http +'/webservices/listing/upload.php';
server = http + '/gallery-upload.php?post_id=' + localStorage.post_id_1;
console.log("Server " + server);
// alert("Server "+server);
if (server) {
// Specify transfer options
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
options.chunkedMode = false;
// Transfer picture to server
var ft = new FileTransfer();
ft.upload(imageURI, server, function(r) {
document.getElementById('picture_msg_1').innerHTML = "Upload successful: " + r.bytesSent + " bytes uploaded.";
// img.src = uri;
// img.width = 50;
// img.height = 50;
$("#gallery_images_list").append('<img src="' + uri + '" style="width:50px;" id="im">');
// shows delete img button
document.getElementById('remImg').removeAttribute('hidden');
$("#server_image_url_1").val(r.response.toString());
//$("#add_company_category").val("Submit & Finish");
//$("#add_company_category").html("Submit & Finish");
$("#loader_icon").css('display', 'none');
},
function(error) {
document.getElementById('picture_msg_1').innerHTML = "Upload failed: Code = " + error.code;
}, options);
} else {
document.getElementById('picture_msg_1').innerHTML = "Server Not Found";
}
} catch (exce) {
navigator.notification.alert(exce);
}
},
function(e) {
console.log("Error getting picture: " + e);
document.getElementById('picture_msg_1').innerHTML = "No Image Found";
}, {
quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
}
);
}
// Delete image
function delImg() {
$(function() {
document.getElementById('im').remove();
document.getElementById('picture_msg_1').innerHTML = "Image Removed";
delBtn();
});
};
// Hide Delete Button
function delBtn() {
var x = document.getElementById('gallery_images_list').childElementCount;
if (x < 1) {
document.getElementById('remImg').setAttribute('hidden');
document.getElementById('picture_msg_1').innerHTML = "";
}
};
Edit 2:
Try changing this
function delBtn() {
var x = document.getElementById('gallery_images_list').childElementCount;
if (x < 1) {
document.getElementById('remImg').setAttribute('hidden');
document.getElementById('picture_msg_1').innerHTML = "";
}
};
to this
function delBtn() {
var x = document.getElementById('gallery_images_list').childElementCount;
if (x < 1) {
$('#remImg').attr('hidden', true);
$('#picture_msg_1').html("");
}
};
Edit:
Try changing this code:
function delImg() {
$(function() {
document.getElementById('im').remove();
document.getElementById('picture_msg_1').innerHTML = "Image Removed";
delBtn();
});
};
To this.
function delImg() {
$('#im').remove();
$('#picture_msg_1').html("Image Removed");
delBtn();
};
I think you are using the remove() method wrong. You need to know the parent and remove children from that like this.
var child = document.getElementById("p1");
child.parentNode.removeChild(child);
This example was taken from here.
https://www.w3schools.com/js/js_htmldom_nodes.asp
You could also use jQuery.
$('#id').remove()
Anyone can help me with my code? I wanna build an upload function using HTML5 API. if I upload less than 1mb the file is alright. However, if file more than 1mb the file will be corrupted.
the HTML file :
<!DOCTYPE html>
<html>
<head>
<title>Upload</title>
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
</head>
<body>
<form method="POST" action="upload.php" enctype='multipart/form-data'>
<input type="file" name="fileToUpload" id="file"><br />
<input type="submit" id="submit">
</form>
</body>
<script>
$(document).ready(function(){
$('#submit').on('click', function(e){
e.preventDefault();
sendRequest();
});
//window.BlobBuilder = window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder;
var bytes_per_chunk = 1048576; // 1mb chunk sizes.
var global_upload_counter = 0;
function sendRequest(){
var blob = document.getElementById('file').files[0];
var total_size = blob.size;
var start = 0;
var end = bytes_per_chunk;
// var counter = 1;
while(start < total_size)
{
// console.log('start : ' + start + ', end :' + end + ' and counter : ', counter);
var chunk = blob.slice(start, end);
uploadFile(chunk, blob.name);
start = end;
end = start + bytes_per_chunk;
//counter++;
}
}
function uploadFile(chunk, filename){
var fd = new FormData();
fd.append('fileToUpload', chunk);
var xhr = new XMLHttpRequest();
xhr.addEventListener('load', uploadComplete, false);
xhr.addEventListener('error', uploadFailed, false);
xhr.addEventListener('abort', uploadCanceled, false);
xhr.open('POST', 'upload.php?filename=' + filename);
xhr.send(fd);
}
function uploadComplete(evt) {
// This event is raised when the server send back a response
if (evt.target.responseText != ""){
alert(evt.target.responseText);
}
}
function uploadFailed(evt) {
alert("There was an error attempting to upload the file.");
}
function uploadCanceled(evt) {
xhr.abort();
xhr = null;
}
});
</script>
</html>
PHP code (upload.php):
<?php
$target_path = "upload/";
$tmp_name = $_FILES['fileToUpload']['tmp_name'];
$size = $_FILES['fileToUpload']['size'];
$name = $_FILES['fileToUpload']['name'];
$filename = $_GET['filename'];
//$target_file = $target_path.$name;
$complete = $target_path. $filename;
// append; open or create binary file for writing at end-of-file
$com = fopen($complete, "ab");
error_log($target_path);
// read as binary
$in = fopen($tmp_name, "rb");
if($in){
while ($buff = fread($in, $size)){
fwrite($com, $buff);
}
}
fclose($in);
First of all, why do you want to separate the file into chunks? You can upload the whole file in a go via AJAX. The error that you are encountering might be due to the chunk logic.
Try removing the chunk logic and it will work just fine. So your upload function would look something like this:
$(document).ready(function(){
$('#submit').on('click', function(e){
e.preventDefault();
sendRequest();
});
//window.BlobBuilder = window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder;
var bytes_per_chunk = 1048576; // 1mb chunk sizes.
var global_upload_counter = 0;
function sendRequest(){
var blob = document.getElementById('file').files[0];
var total_size = blob.size;
uploadFile(blob,filename);
}
function uploadFile(chunk, filename){
var fd = new FormData();
fd.append('fileToUpload', chunk);
var xhr = new XMLHttpRequest();
xhr.addEventListener('load', uploadComplete, false);
xhr.addEventListener('error', uploadFailed, false);
xhr.addEventListener('abort', uploadCanceled, false);
xhr.open('POST', 'upload.php?filename=' + filename);
xhr.send(fd);
}
function uploadComplete(evt) {
// This event is raised when the server send back a response
if (evt.target.responseText != ""){
alert(evt.target.responseText);
}
}
function uploadFailed(evt) {
alert("There was an error attempting to upload the file.");
}
function uploadCanceled(evt) {
xhr.abort();
xhr = null;
}
});
Instead of chunks, send the full file and it should work.
If you are worried about the upload progress, here are a few solutions:
jQuery Upload Progress and AJAX file upload ,
File upload progress bar with jQuery
Looking at the answer provided by user470714 on uploading a file in chunks using html5 I found the issues.
Which the ajax didn't actually uploading the chunks in order. So I updated my HTML code as follow and now it works fine :
<!DOCTYPE html>
<html>
<head>
<title>Upload</title>
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
</head>
<body>
<form method="POST" action="upload.php" enctype='multipart/form-data'>
<input type="file" name="fileToUpload" id="file"><br />
<input type="submit" id="submit">
</form>
</body>
<script>
$(document).ready(function(){
$('#submit').on('click', function(e){
e.preventDefault();
sendRequest();
});
//window.BlobBuilder = window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder;
var bytes_per_chunk = 1048576; // 1mb chunk sizes.
var global_upload_counter = 0;
function sendRequest(){
var blob = document.getElementById('file').files[0];
var total_size = blob.size;
window.upload_counter = 0;
window.upload_filearray = [];
var start = 0;
var end = bytes_per_chunk;
while(start < total_size)
{
var chunk = blob.slice(start, end);
window.upload_filearray[window.upload_counter] = chunk;
window.upload_counter++;
start = end;
end = start + bytes_per_chunk;
}
// initiate upload the first time
window.upload_counter = 0;
window.filename = blob.name;
uploadFile(window.upload_filearray[window.upload_counter]);
}
function uploadFile(chunk){
var fd = new FormData();
fd.append('fileToUpload', chunk);
var xhr = new XMLHttpRequest();
xhr.addEventListener('load', uploadComplete, false);
xhr.addEventListener('error', uploadFailed, false);
xhr.addEventListener('abort', uploadCanceled, false);
xhr.open('POST', 'upload.php?filename=' + window.filename);
window.upload_counter++;
xhr.send(fd);
}
function uploadComplete(evt) {
// This event is raised when the server send back a response
if (evt.target.responseText != ""){
console.log(evt.target.responseText);
}
if(window.upload_filearray.length > window.upload_counter){
uploadFile(window.upload_filearray[window.upload_counter]);
}
}
function uploadFailed(evt) {
alert("There was an error attempting to upload the file.");
}
function uploadCanceled(evt) {
xhr.abort();
xhr = null;
}
});
</script>
</html>
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;