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".
Related
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);
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 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>
I am using fileReader for checking if a profile picture uploaded matches with my conditions. However, i don't have always the same result. Can you help me to fix that bug ?
Here my htlm code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>File API</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="page-wrapper">
<h1>Image File Reader</h1>
<div>
Select an image file:
<input type="file" id="fileInput">
</div>
</div>
<script src="images.js"></script>
</body>
</html>
Here my javascript/fileReader (images.js) code:
window.onload = function()
{
var width=0;
var height=0;
var exten= false;
var size = false;
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e)
{
var file = fileInput.files[0];
var imageType = /image.png/;
if (file.type.match(imageType))
{
exten = true;
var reader = new FileReader();
reader.onload = function(e)
{
var img = new Image();
img.src = reader.result;
img.onload = function()
{
width=this.width;
height=this.height;
}
}
reader.readAsDataURL(file);
}
else
{
exten= false;
}
if(width == 50 && height ==50)
{
size = true;
}
else
{
size = false;
}
//Here, we check that the image matches with png and 50*50px
if(size && exten)
{
alert('Your image is ok.');
}
else
{
if(!size && !exten)
{
alert('Image needs to be 50*50px and in png');
}
else
{
if(!size && exten)
{
alert('Image needs to be 50*50px');
}
else
{
if(size && !exten)
{
alert('Image needs to be in png');
}
}
}
}
});
}
Thank you for your help
You've to wait the execution of the img.onload event before checking width and height.
The code that's outside that event handler and that uses those properties should be moved inside it.
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;