html code
<form method="post" name="file_upload" enctype="multipart/form-data" id="file_upload">
<input type="file" id="_file" name="_file"> <br>
<input type="button" id="button" value="upload"/> <br>
<progress id="p_bar" value="0" max="100" style="width:300px;"> </progress>
</form>
<p id="status"> </p>
<script src="final.js" > </script>
js
var sfile = document.getElementById('_file') ;
var btn = document.getElementById('button') ;
var f_upload= document.getElementById('file_upload') ;
var pbar = document.getElementById('p_bar') ;
var sbar = document.getElementById('status') ;
function upload () {
if(sfile.files.length==0) {
alert("files isn't select ") ;
}
var s_file = sfile.files[0] ;
var formdata = new FormData () ;
formdata.append( 'selected file ',s_file) ;
var ajax = new XMLHttpRequest () ;
ajax.upload.addEventListener("progress", progress , false ) ;
function progress (event) {
var percent = (event.loaded / event.total) * 100 ;
pbar.value = Math.round(percent) ;
sbar.innerHTML = Math.round(percent)+"%.........uploaded" ;
}
ajax.open("POST", "final.php") ;
ajax.send(formdata) ;
}
btn.addEventListener("click", upload , false ) ;`
PHP
<?php
$file_name = $_FILES['_file']['name'] ;
$file_temp = $_FILES['_file']['tmp_name'] ;
$file_size = $_FILES['_file']['size'] ;
$file_type = $_FILES['_file']['type'] ;
$file_error = $_FILES['_file']['size'] ;
$file_destination = "upload/".basename($file_name) ;
if( move_uploaded_file($file_temp, $file_destination) ) {
echo "file uploaded" ;
}
else {
echo " file is failed to upload " ;
}
In these no working on php . if i only put echo still not output in main page . also if in php we caught with name tag in html than why use of send function in ajax.like ajax.send(formdata)
the problem here is you are not looking for ajax response.try this:
<script>
var sfile = document.getElementById('_file');
var btn = document.getElementById('button');
var f_upload= document.getElementById('file_upload');
var pbar = document.getElementById('p_bar');
var sbar = document.getElementById('status');
var ajax = null;
function upload () {
if(sfile.files.length==0) {
alert("files isn't select ");
return;
}
var s_file = sfile.files[0];
var formdata = new FormData();
formdata.append('_file',s_file);//your key is _file
ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progress , false);
ajax.open("POST", "final.php");
ajax.onreadystatechange = OnStateChange;
ajax.send(formdata);
}
btn.addEventListener("click", upload , false);
function progress (event) {
var percent = (event.loaded / event.total) * 100;
pbar.value = Math.round(percent);
sbar.innerHTML = Math.round(percent)+"%.........uploaded";
}
function OnStateChange () {
if (ajax.readyState == 4 && ajax.status == 200) {
var resp = ajax.responseText;
alert(resp);
}
}
</script>
Related
I am trying to build a way for a user to be able to create an article, if they want, with a button they can add an input for a text, a file input etc.
I want to send this form with JavaScript vanilla (training)
so what I do in my js is that I loop into my different added input then I append them to formData
and send this formData to my controller to treat it and add it to my database.
Problem is that by iterating my input when I append my input into formData I have to add the index
so when I send it and print_r my post
I get like:
text01
text02
text03 etc.
it would be fine if it was only these input that I wanted to send but in my post I have other inputs which are sent the same way so I get like
title01
paragraphe01
title02
paragprahe02
the problem will be when I want to query to add the data to my database I would have to bind all of these to my query, but of course I can't make 50 lines of
bind('text01', $text01)
I don't think it would be a nice way to do it
so I am looking for a way to be able to query all of these data I thought of maybe a way getting only the paragraphs indexes and putting them in an array containing only paragraphs then forEach() everything.
another array for another input etc. but I can't find a way to do it, is it even possible
so here is my code
<?php
include '../flash/Flash.php';
$pageTitle = "création d'article";
$css = "create_article";
include './assets/include/_header.php';
?>
<body>
<?php
include '../view/assets/include/_nav.php';
flash('createB');
?>
<main>
<form action="../controller/Crud_controller.php" method="post" class="form_container" enctype="multipart/form-data">
<input type="hidden" name="type" value="createB" id="type">
<h3 id="status"></h3>
<h5>titre du post</h5>
<input type="text" name="title" id="title">
<h5>Paragraphe</h5>
<textarea name="paragraphe" id="product_desc" cols="30" rows="10"></textarea>
<input type="file" id="img_livre" name="name" accept="image/png, image/jpeg">
<h5>Note 1</h5>
<input type="text" name="note" id="note">
<button type="button" data-prototype="" class="btn btn_primary btn-js">Ajouter un paragraphe ou une image ?</button>
<button type="button" class="btn btn_primary btn-js-ajax">envoyer</button>
</form>
</main>
</body>
<script>
const btnSubmit = document.querySelector('.btn-js-ajax');
btnSubmit.addEventListener('click', uploadFiles);
function uploadFiles() {
let formData = new FormData();
let images = document.getElementsByName('name');
let type = document.getElementById('type').value;
let paragraphe = document.getElementsByName('paragraphe');
let note = document.getElementsByName('note');
let title = document.getElementById('title').value;
for(i = 0; i <= images.length; i++) {
let uFiles = images[i];
if (uFiles) {
formData.append("name" + i, uFiles.files[0]);
}
}
for(let i = 0; i < paragraphe.length; i++) {
let paragraphes = paragraphe[i].value;
if (paragraphes) {
formData.append("paragraphe"+i,paragraphes);
}
}
for(let i = 0; i < note.length; i++) {
let notes = note[i].value;
if (notes) {
formData.append("note" + i, notes);
}
}
formData.append('title', title);
formData.append('type',type );
const ajax = new XMLHttpRequest();
fetch("../controller/Crud_controller.php", {method: "POST", body: formData}).then(res => res.text()).then(data => {console.log(data);})
ajax.upload.addEventListener("load", completeHandler, false);
}
var obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}
var result = Object.keys(obj).map((key) => [Number(key)]);
console.log(result);
const form = document.querySelector('.form_container');
const addBtn = document.querySelector('.btn-js');
function addInput() {
const paragraphe = document.createElement('textarea');
paragraphe.name = 'paragraphe';
paragraphe.style = "margin-top:100px";
paragraphe.cols = "30";
paragraphe.rows = "10";
const file = document.createElement('input');
file.type = 'file';
file.style = "border: none";
file.name = 'name';
file.accept = "image/png, image/jpeg";
const note = document.createElement('input');
note.type = 'text';
note.name = 'note';
const btnRemove = document.createElement('a');
btnRemove.className = 'btn_primary btn';
btnRemove.innerHTML = 'supprimer';
form.insertBefore(btnRemove, addBtn);
form.insertBefore(note, btnRemove);
form.insertBefore(file, note);
form.insertBefore(paragraphe, file);
}
addBtn.addEventListener('click', addInput);
</script>
</html>
here the controller getting the post ajax element
<?php
include '../model/CrudModel.php';
include '../model/Blog.php';
require_once '../flash/Flash.php';
class Products
{
private $crudModel;
private $crudBlog;
public function __construct()
{
$this->crudModel = new Product;
$this->crudBlog = new Blog;
}
public function blog()
{
$data = $_POST;
echo "<pre>";
print_r($data);
echo "</pre>";
print_r($_FILES);
if (empty($data['title']) || empty($data['paragraphe'])) {
flash('createB', 'remplir au moins le titre et le paragraphe et ajouter une image');
// header('Location: ../view/crud_blog.php');
} else {
forEach($data as $k => $v)
{if ($this->crudBlog->setBlogPost($data)) {
foreach ($_FILES as $file) {
if ($this->crudBlog->setBlogImages($file)) {
flash('createB', "c'est bon");
// header('Location: ../view/create_blog_page.php ');
}
}
}}
}
}
}
$init = new Products;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
switch ($_POST['type']) {
case 'crud':
$init->produit();
break;
case 'createB':
$init->blog();
break;
default:
echo "je peux pas";
break;
}
}
here is my Model where I have all my queries
<?php
require_once '../dbb/Database.php';
class Blog {
private $con;
private $table_name = "blog_post";
public function __construct()
{
$this->con = new Database;
}
public function setBlogPost($array) {
$query = "INSERT INTO " . $this->table_name . " SET title = :title , paragraphe=:p1 , note = :note1";
$this->con->prepare($query);
$this->con->bind('title' , $array['title']);
$this->con->bind('p1' , $array['paragrape']);
$this->con->bind('note1' , $array['note']);
if($this->con->execute()){
return true;
}return false;
}
public function setBlogImages($file){
$table_name = "blog_image";
$query = "INSERT INTO " . $table_name . " SET name = :img , id = LAST_INSERT_ID()";
$this->con->prepare($query);
$this->con->bind('img',$file['name']);
move_uploaded_file($file['tmp_name'], "../view/assets/uploads/".$file['name']);
if ($this->con->execute()){
return true;
}return false;
}
and this is the response I get in my console.log maybe it will be more clear
thank you
Little edit so i managed to make an array for each of my input
array paragraphe for paragraphes
note for notes etc...
i changed this
for(i = 0; i <= images.length; i++) {
let uFiles = images[i];
if (uFiles) {
formData.append("name" + i, uFiles.files[0]);
}
}
for(let i = 0; i < paragraphe.length; i++) {
let paragraphes = paragraphe[i].value;
if (paragraphes) {
formData.append("paragraphe"+i,paragraphes);
}
}
for(let i = 0; i < note.length; i++) {
let notes = note[i].value;
if (notes) {
formData.append("note" + i, notes);
}
}
by this
for(i = 0; i <= images.length; i++) {
let uFiles = images[i];
if (uFiles) {
formData.append("name[]" + i, uFiles.files[0]);
}
}
for(let i = 0; i < paragraphe.length; i++) {
let paragraphes = paragraphe[i].value;
if (paragraphes) {
formData.append("paragraphe[]"+i,paragraphes);
}
}
for(let i = 0; i < note.length; i++) {
let notes = note[i].value;
if (notes) {
formData.append("note[]" + i, notes);
}
}
but here's the problem
i can't find a way to foreach multiple array in php to add them to my database
this is the response result i get in my console now
reponse2
Basically i have to upload file by chunks as the file is very big,i tried using this solution uploading a file in chunks using html5 but the file is corrupt because the file reconstructed is not in order.
I tried to implement the answer given in the link but i really confused how can i implement it on my php page and my html page. If you guys could give me an advice or a way of doing it, that would be great. Thank you for your time.
The code :
upload.php
<?php
$target_path = "/home/imagesdcard/www/";
$tmp_name = $_FILES['fileToUpload']['tmp_name'];
$size = $_FILES['fileToUpload']['size'];
$name = $_FILES['fileToUpload']['name'];
$target_file = $target_path . basename($name);
$complete = "test.txt";
$com = fopen("/home/imagesdcard/www/".$complete, "ab");
error_log($target_path);
// Open temp file
$out = fopen($target_file, "wb");
if ( $out ) {
// Read binary input stream and append it to temp file
$in = fopen($tmp_name, "rb");
if ( $in ) {
while ( $buff = fread( $in, 1024) ) {
fwrite($out, $buff);
fwrite($com, $buff);
}
}
fclose($in);
fclose($out);
}
fclose($com);
?>
html
<!DOCTYPE html>
<html>
<head>
<title>Upload Files using XMLHttpRequest</title>
<script type="text/javascript">
window.BlobBuilder = window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder;
function sendRequest() {
var blob = document.getElementById('fileToUpload').files[0];
const BYTES_PER_CHUNK = 1048576; // 1MB chunk sizes.
const SIZE = blob.size;
var i=0;
var start = 0;
var end = BYTES_PER_CHUNK;
while( start < SIZE ) {
var chunk = blob.slice(start, end);
uploadFile(chunk,i);
i++;
start = end;
end = start + BYTES_PER_CHUNK;
}
}
function fileSelected() {
var file = document.getElementById('fileToUpload').files[0];
if (file) {
var fileSize = 0;
if (file.size > 1024 * 1024)
fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
else
fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
document.getElementById('fileName').innerHTML = 'Name: ' + file.name;
document.getElementById('fileSize').innerHTML = 'Size: ' + fileSize;
document.getElementById('fileType').innerHTML = 'Type: ' + file.type;
}
}
function uploadFile(blobFile,part) {
//var file = document.getElementById('fileToUpload').files[0];
var fd = new FormData();
fd.append("fileToUpload", blobFile);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "upload.php?num="+part);
xhr.onload = function(e) {
alert("loaded!");
};
xhr.send(fd);
//alert("oen over");
}
function uploadProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
}
else {
document.getElementById('progressNumber').innerHTML = 'unable to compute';
}
}
function uploadComplete(evt) {
/* This event is raised when the server send back a response */
alert(evt.target.responseText);
}
function uploadFailed(evt) {
alert("There was an error attempting to upload the file.");
}
function uploadCanceled(evt) {
xhr.abort();
xhr = null;
//alert("The upload has been canceled by the user or the browser dropped the connection.");
}
</script>
</head>
<body>
<form id="form1" enctype="multipart/form-data" method="post" action="upload.php">
<div class="row">
<label for="fileToUpload">Select a File to Upload</label><br />
<input type="file" name="fileToUpload" id="fileToUpload" onchange="fileSelected();"/>
<input type="button" value="cancel" onClick="uploadCanceled();"/>
</div>
<div id="fileName"></div>
<div id="fileSize"></div>
<div id="fileType"></div>
<div class="row">
<input type="button" onclick="sendRequest();" value="Upload" />
</div>
<div id="progressNumber"></div>
</form>
</body>
</html>
Your script doesn't work because js is async.
You should change your code to:
xhr.open("POST", "upload.php?num="+part, false);
and file save fine.
My solution for upload big files by chunk.
upload.php (php part)
<?php
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$chunk = $_FILES["chunk"]["tmp_name"];
$filename = $_POST['filename'];
if(!isset($_SESSION[$filename]))
{
$_SESSION[$filename] = tempnam(sys_get_temp_dir(), 'upl');
}
$tmpfile = $_SESSION[$filename];
if(isset($chunk))
{
file_put_contents($tmpfile, file_get_contents($chunk), FILE_APPEND);
}
else
{
rename($tmpfile, $filename);
}
exit();
}
?>
upload.php (html\js part)
<!DOCTYPE html>
<html>
<head>
<title>Upload Files using XMLHttpRequest</title>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script type="text/javascript">
function sendRequest() {
// 1MB chunk sizes.
var chunk_size = 1048570;
var file = document.getElementById('file').files[0];
var filesize = file.size;
var filename = file.name;
var pos = 0;
while(pos < filesize) {
let chunk = file.slice(pos, pos+chunk_size);
pos += chunk_size;
var data = new FormData();
data.append('chunk', chunk);
data.append('filename', filename);
$.ajax({url:'upload.php',type: 'post',async:false,data: data,processData: false,contentType: false});
let percentComplete = Math.round(pos * 100 / filesize);
document.getElementById('progressNumber').innerHTML = (percentComplete > 100 ? 100 : percentComplete) + '%';
}
$.post('upload.php',{filename:filename});
}
</script>
</head>
<body>
<form>
<div class="row">
<label for="file">Select a File to Upload</label><br />
<input type="file" name="file" id="file" onchange="sendRequest();"/>
</div>
<div id="progressNumber"></div>
</form>
</body>
</html>
but this code have one bug - progress bar don't work in chrome because sync request used, work only in firefox.
Oddly enough if I use this code in a jsfiddle it works perfectly
var file = document.getElementById("file");
function CallAlert(){
alert(file.files[0].name);
}
<form method="post" enctype="multipart/form-data">
<div>
<label for="file">Choose file to upload</label>
<input type="file" id="file" name="file" onchange="CallAlert()">
</div>
<div>
<button>Submit</button>
</div>
</form>
The result of this is an alert with the name of the file
Now on to my issue using this same method in sorts in my case this returns Uncaught TypeError: Cannot read property '0' of undefined
function _(el) {
return document.getElementById(el);
}
function uploadFile() {
var file = _('file1').files[0];
if (typeof file === 'undefined') {
_('status').innerHTML = 'ERROR: Please browse for a file before clicking the upload button';
_('progressBar').value = 0;
} else {
$.get('https://outsource.technologyforthefuture.org/wp-content/plugins/video-contest/shortcodes/handles/upload_handle.php?getsize', function(sizelimit) {
if (sizelimit > file.size) {
var formdata = new FormData();
formdata.append('file1', file);
formdata.append('size', file.size);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener('progress', progressHandler, false);
ajax.addEventListener('load', completeHandler, false);
ajax.addEventListener('error', errorHandler, false);
ajax.addEventListener('abort', abortHandler, false);
ajax.open('POST', 'https://outsource.technologyforthefuture.org/wp-content/plugins/video-contest/shortcodes/handles/upload_handle.php');
ajax.send(formdata);
} else {
var sizewarn = 'ERROR: The File is too big! The maximum file size is ';
sizewarn += sizelimit / (1024 * 1024);
sizewarn += 'MB';
_('status').innerHTML = sizewarn;
_('progressBar').value = 0;
}
});
}
}
function progressHandler(event) {
// _('loaded_n_total_bytes').innerHTML = event.loaded+'bytes/''+event.total+'bytes';
// _('loaded_n_total_kb').innerHTML = event.loaded/1024+'kb/''+event.total/1024+'kb';
_('loaded_n_total_mb').innerHTML = Math.round(event.loaded / 1024 / 1024) + 'mb/' + Math.round(event.total / 1024 / 1024) + 'mb';
var percent = (event.loaded / event.total) * 100;
_('progressBar').value = Math.round(percent);
_('percentage_loaded').innerHTML = Math.round(percent) + '%';
if (Math.round(percent) == 100) {
_('status').innerHTML = 'Generating Link Please Wait...';
} else {
_('status').innerHTML = 'uploading... please wait';
}
}
function completeHandler(event) {
_('status').innerHTML = event.target.responseText;
_('progressBar').value = 0;
}
function errorHandler(event) {
_('status').innerHTML = 'Upload Failed';
}
function abortHandler(event) {
_('status').innerHTML = 'Upload Aborted';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="upload_form" enctype="multipart/form-data" method="post">
<input type="file" name="file1" id="file1" onchange="uploadFile()"><br>
<progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
<p class="loading">
<pt id="percentage_loaded"></pt>|
<!--<pt id="loaded_n_total_bytes"></pt>|
<pt id="loaded_n_total_kb"></pt>|-->
<pt id="loaded_n_total_mb"></pt>|
<pt id="status"></pt>
</p>
</form>
What I am trying to do is when a file is selected it sends it as an ajax response to a script to put the file on our server. I dont see how this is producing an error when there is no difference in the example snippet vs my actual code other then the extra stuff around it but I dont see how that could be affecting it.
Perhaps someone smarter then me knows what the answer to this issue is.
instead of this
function uploadFile() {
var file = _('file1').files[0];
...
try this
function uploadFile(event){
var file=event.target.files[0];
...
and don't forget to change this
<input type="file" name="file1" id="file1" onchange="(event)=>uploadFile(event)"><br>
I have a form that upload a file..
<form enctype="multipart/form-data" name="" action="" method="POST">
<input type="file" name="file[]" id="files" multiple />
<div id="selectedFiles"></div>
<form>
And a javascript function to display the name and size.
<script>
var selDiv = "";
document.addEventListener("DOMContentLoaded", init, false);
function init() {
document.querySelector('#files').addEventListener('change', handleFileSelect, false);
selDiv = document.querySelector("#selectedFiles");
}
function handleFileSelect(e) {
if(!e.target.files) return;
selDiv.innerHTML = "";
var files = e.target.files;
for(var i=0; i<files.length; i++) {
var f = files[i];
selDiv.innerHTML += "<span class='attach'>" + f.name + " <" + f.size + " bytes>" + "</span>";
}
}
</script>
is their anyone know how to make a delete function on the attachment??
example:
the image shows the uploaded file.. and the red "x" is the delete...
can anyone please help me with this? using javascript..
See comments below.
<form action="some.php" method="post" id="form">
<input type="file" id="file" multiple style="display: none;" />
<button type="button" id="button">Select files</button>
<div id="selectedFiles"></div>
<button type="submit" id="submit">Upload</button>
<form>
var selDiv = document.querySelector("#selectedFiles");
document.querySelector("#button").addEventListener("click", function() {
document.querySelector("#file").click();
}, false);
document.querySelector("#file").addEventListener("change", function() {
var files = this.files;
for (var i = 0; i < files.length; ++i) {
var file = files[i],
span = document.createElement("span");
span.className = "attach";
span.innerHTML = file.name+" <"+file.size+" bytes>";
span.file = file;
var remove = document.createElement("span");
remove.innerHTML = "Remove";
span.appendChild(remove);
selDiv.appendChild(span);
remove.addEventListener("click", function() {
this.parentNode.removeChild(this);
}, false);
}
}, false);
document.querySelector("#form").addEventListener("submit", function(e) {
var files = selDiv.querySelectorAll("span.attach"),
data = new FormData(),
xmlhttp = new XMLHttpRequest();
for (var i = 0; i < files.length; ++i) {
data.append("file[]", files[i].file);
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
selDiv.innerHTML = "Uploading completed!";
}
}
xmlhttp.open("POST", "upload.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(data);
return false;
}, false);
I am using javascript to check file size. If it is bigger than 1m it shows an alert and after that it redirect to index page.
I want know how to make it stay in the same page without redirect and without refresh and keep all page information inserted by user as it is.
This is the code:
if(fileInput.files[0].size > 1050000) {
alert('File size is bigger than 1Mb!');
return false;
}
the hole code:
var handleUpload = function(event){
event.preventDefault();
event.stopPropagation();
var fileInput = document.getElementById('file');
var data = new FormData();
data.append('javascript', true);
if(fileInput.files[0].size > 1050000) {
//document.getElementById("image_id").innerHTML = "Image too big (max 1Mb)";
alert('File bigger than 1Mb!');
//window.location="upload.php";
return false;
}
for (var i = 0; i < fileInput.files.length; ++i){
data.append('file[]', fileInput.files[i]);
}
var request = new XMLHttpRequest();
request.upload.addEventListener('progress', function(event){
if(event.lengthComputable){
var percent = event.loaded / event.total;
var progress = document.getElementById('upload_progress');
while (progress.hasChildNodes()){
progress.removeChild(progress.firstChild);
}
progress.appendChild(document.createTextNode(Math.round(percent * 100) +' %'));
document.getElementById("loading-progress-17").style.width= Math.round(percent * 100) +'%';
}
});
request.upload.addEventListener('load', function(event){
document.getElementById('upload_progress').style.display = 'none';
});
request.upload.addEventListener('error', function(event){
alert('Upload failed');
});
request.addEventListener('readystatechange', function(event){
if (this.readyState == 4){
if(this.status == 200){
var links = document.getElementById('uploaded');
var uploaded = eval(this.response);
var div, a;
for (var i = 0; i < uploaded.length; ++i){
div = document.createElement('div');
a = document.createElement('a');
a.setAttribute('href', 'files/' + uploaded[i]);
a.appendChild(document.createTextNode(uploaded[i]));
div.appendChild(a);
links.appendChild(div);
}
}else{
console.log('server replied with HTTP status ' + this.status);
}
}
});
request.open('POST', 'upload.php');
request.setRequestHeader('Cache-Control', 'no-cache');
document.getElementById('upload_progress').style.display = 'block';
request.send(data);
}
window.addEventListener('load', function(event){
var submit = document.getElementById('submit');
submit.addEventListener('click', handleUpload);
});
the upload.php code with the html
<?php
foreach($_FILES['file']['name'] as $key => $name){
if ($_FILES['file']['error'][$key] == 0 && move_uploaded_file($_FILES['file']['tmp_name'][$key], "files/{$name}")){
$uploaded[] = $name;
}
}
if(!empty($_POST['javascript'])){
die(json_encode($uploaded));
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="upload.js"></script>
</head>
<body>
<div id="uploaded">
<?php
if (!empty($uploaded)){
foreach ($uploaded as $name){
echo '<div>',$name,'</div>';
}
}
?>
</div>
<div id="upload_progress"></div>
<div>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" id="file" name="file[]" />
<input type="submit" id="submit" value="upload" />
</form>
Thanks in advance
You may get rid of return it should work. Else, maybe you should try modals instead of alerts. They are more neat and pretty
Return false is preventing the redirect.
var val = $("#inputId").val();
if (val >= 0 || val <=9)
{
return true;
}
else
{
alert("Enter Digits Only");
return false;
}
```
Add event.preventDefault(); below the alert function.
This may help you to stay on the same page.