stop javascript to redirect after alert() function - javascript

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.

Related

Javascript automatic file input fill and upload

I have json file genertor and file upload input on my page and its working like that:
Press button "Generate file" then press link "Download" then save file "test.json" locally.
Then I can load this file and send to target using html input file on the same page.
But I dont know how to upload generated file automaticaly using "doSubmit" function when button "Generate file" is pressed without saving locally before.
Is it even possible?
Can someone help how to solve this problem?
I am still beginner and I cant help myself...
Thank you very much!
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Generate Json File In JavaScript</title>
</head>
<body>
<div class="wrap-title">
<h2>Generate Json File using plain JavaScript</h2>
</div>
<div class="wrap-footer">
<button id="btnCreateFile">Generate File</button>
<a download="test.json" id="downloadFile" style="display: none">Download</a>
</div>
<hr>
<h5>File upload</h5>
<input class="form-control" type="file" id="file-select-input">
<div class="input-group-append">
<button class="btn btn-primary btn-sm" type="button" style="width: 120px" onclick='doSubmit()' id="upload-button" >Upload</button>
</div>
<hr>
<script>
var upData = "[\n";
function doJson(){
var num = 5;
for ( let i = 1; i < num + 1 ; i++ ){
upData += "{\"nr\":\"" + i + "\",\"class\":" + i + ",\"group\":" + i + "}";
if ( i < num ) upData += ",\n"; else upData += "\n]";
}
}
function generateJsonFile(text){
var jsonFile = null;
var data = new Blob([text], {type: 'text/json'});
if (jsonFile !== null) {
window.URL.revokeObjectURL(jsonFile);
}
jsonFile = window.URL.createObjectURL(data);
return jsonFile;
}
(function () {
btnCreateFile.addEventListener('click', function () {
var link = document.getElementById('downloadFile');
doJson();
console.log( upData );
link.href = generateJsonFile(upData);
link.style.display = 'inline-block';
}, false);
})();
function doSubmit(){
var formData = new FormData();
var fileSelect = document.getElementById( "file-select-input" );
if( !fileSelect.files[0] ) return; /* do not send empty file input */
document.getElementById( "upload-button" ).innerHTML = 'Uploading...';
if( fileSelect.files && fileSelect.files.length == 1 ) {
var file = fileSelect.files[0]
formData.append( "fileUpload", file , file.name );
}
var ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = function(){ /* prepare response */
if( ajaxRequest.readyState == 4 && ajaxRequest.status == 200 ){
if( ajaxRequest.responseText == "ERROR" ) document.getElementById( "upload-button" ).innerHTML = 'Error';
else if( ajaxRequest.responseText == "OK" ) {
document.getElementById( "upload-button" ).innerHTML = 'Upload'; /* change upload button label */
document.getElementById( "file-select-input" ).value = null; /* empty file input -> prevent send the same data again */
console.log( 'file delivered OK!');
}
}
}
ajaxRequest.open( 'POST', "fileUpload" );
ajaxRequest.send( formData );
console.log( "file sent..." );
}
</script>
</body>
</html>

uploading a file in chunks using html5 , javascript and PHP

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.

After submit a form, stay same page, show a word in the page

After clicking "submit", stay on the page.
Input data, like "computer number" and "profit", stay inside those blank square.
A word "Submitted", appear in the center of this page.
The following is my code, Please help, thank you!
<html>
<head>
<title></title>
</head>
<body>
<form name="form"
onsubmit="return validateForm()">
Computer Number:<br>
<input type="text" name="Computer" required><br>
<p>How much is your profit?
<input id="id1" name = "id1" required>
<button type = "button" onclick="myFunction()">My Answer</button>
<button type="button" id="btn1" onclick="Solution()" style="display:none;">Solution</button>
</p>
<p id="Q1"></p>
<script>
var errosCount = 0;
function myFunction() {
var x, text;
x = document.getElementById("id1").value;
if (isNaN(x) || x != 100) {
text = "Incorrect"; document.getElementById("Q1").style.color = "red";errosCount++;
} else {
text = "Correct"; document.getElementById("Q1").style.color = "green";
}
document.getElementById("Q1").innerHTML = text;
if(errosCount === 3){
errosCount = 0;
document.getElementById('btn1').style.display = 'block';
document.getElementById("Q1").innerHTML = '';
} else {
document.getElementById('btn1').style.display = 'none';
}
}
function Solution(){
text = "(P - w) * q<sub>o</sub> - I = (53 - 43) * 30 - 200 = 100"; document.getElementById("Q1").style.color = "red";
document.getElementById("Q1").innerHTML = text;
}
</script>
<input type="submit" value="Submit">
</form>
<script>
function validateForm() {
var q = document.forms["my form"]["Computer"].value;
if (q == "") {
alert("Computer Number is Missing!");
return false;}
var w = document.forms["my form"]["id1"].value;
if (w != "100") {
alert("Question 1 is Incorrect!");
return false;}
}
</script>
</body>
</html>
Firstly, you were having document.forms["my form"] which was invalid since your form name was form so I changed it to document.forms["form"].
And, on submit, I added return false at the bottom of the function to stay on the page. Also, before that, added "Submitted" text in the center of the page as shown below.
Here's working code snippet!
Hope that helps!
var errosCount = 0;
function myFunction() {
var x, text;
x = document.getElementById("id1").value;
if (isNaN(x) || x != 100) {
text = "Incorrect";
document.getElementById("Q1").style.color = "red";
errosCount++;
} else {
text = "Correct";
document.getElementById("Q1").style.color = "green";
}
document.getElementById("Q1").innerHTML = text;
if (errosCount === 3) {
errosCount = 0;
document.getElementById('btn1').style.display = 'block';
document.getElementById("Q1").innerHTML = '';
} else {
document.getElementById('btn1').style.display = 'none';
}
}
function Solution() {
text = "(P - w) * q<sub>o</sub> - I = (53 - 43) * 30 - 200 = 100";
document.getElementById("Q1").style.color = "red";
document.getElementById("Q1").innerHTML = text;
}
function validateForm() {
var q = document.forms["form"]["Computer"].value;
if (q == "") {
alert("Computer Number is Missing!");
return false;
}
var w = document.forms["form"]["id1"].value;
if (w != "100") {
alert("Question 1 is Incorrect!");
return false;
}
document.getElementById("submitted").innerHTML = "Submitted"
return false;
}
#submitted {
text-align: center
}
<form name="form" onsubmit="return validateForm()">
Computer Number:<br>
<input type="text" name="Computer"><br>
<p>How much is your profit?
<input id="id1" name="id1" required>
<button type="button" onclick="myFunction()">My Answer</button>
<button type="button" id="btn1" onclick="Solution()" style="display:none;">Solution</button>
</p>
<p id="Q1"></p>
<input type="submit" value="Submit">
</form>
<br/>
<div id="submitted">
</div>
Hello you should think abut using AJAX as you are sending a form.
This can be the button:
<button type="button"
onclick="validateForm('ajax_info.php', myFunction)"> Clic to Submit
</button>
And this the AJAX function:
function validateForm(url, cFunction) {
var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET", url, true); //can be POST
xhttp.send();
}
function myFunction(xhttp) {
document.getElementById("submited").innerHTML =
xhttp.responseText;
}

what's wrong with these code? why it not sort preview image upload?

Here is the full code for html5 multiple upload file with removeable and preview image
but I don't know in function handleFileSelect(e) why it show the preview images with wrong sorting when choose more than 2 files? (Although, it upload to my folder correctly sort but I still want it to show preview with correct sorting)
<!doctype html>
<html>
<head>
<title>Proper Title</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<style>
#selectedFiles img {
max-width: 200px;
max-height: 200px;
float: left;
margin-bottom:10px;
}
.delete_img{
cursor:pointer;
color:red;
font-size:14px;
margin-left:10px;
}
</style>
</head>
<body>
<form id="myForm" method="post">
Username: <input type="text" name="username" id="username"><br/>
Email: <input type="text" name="email" id="email"><br/>
Multiple Files: <input type="file" id="files" name="files[]" multiple><br/>
<div id="selectedFiles"></div>
<input type="submit">
</form>
<script>
var selDiv = "";
var storedFiles = [];
$(document).ready(function() {
$("#files").on("change", handleFileSelect);
selDiv = $("#selectedFiles");
$("#myForm").on("submit", handleForm);
$("body").on("click", ".delete_img", removeFile);
});
function handleFileSelect(e) {
var files = e.target.files;
var filesArr = Array.prototype.slice.call(files);
filesArr.forEach(function(f) {
if(!f.type.match("image.*")) {
return;
}
storedFiles.push(f);
var reader = new FileReader();
reader.onload = function (e) {
var html = "<div><img src=\"" + e.target.result + "\" data-file='"+f.name+"' class='selFile' title='Click to remove'> <span class='delete_img'> DEL </span><br>" + f.name + "<br clear=\"left\"/></div>";
selDiv.append(html);
}
reader.readAsDataURL(f);
});
}
function handleForm(e) {
e.preventDefault();
var username = document.getElementById('username').value; //get value จาก form input
var email = document.getElementById('email').value;
var data = new FormData();
data.append('username', username); //มาใส่ในajax object formdata เพื่อเตรียมส่งเข้าฝั่งserver
data.append('email', email);
for(var i=0, len=storedFiles.length; i<len; i++) {
data.append('files[]', storedFiles[i]); //อย่าลืม []
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload.php', true);
xhr.onload = function(e) {
if(this.status == 200) {
console.log(e.currentTarget.responseText);
//alert(e.currentTarget.responseText + ' items uploaded.');
window.location = "http://www.google.com";
}
}
xhr.send(data);
}
function removeFile(e) {
var img = e.target.parentElement.querySelector("img")
var file = img.getAttribute('data-file');
for(var i=0;i<storedFiles.length;i++) {
if(storedFiles[i].name === file) {
storedFiles.splice(i,1);
break;
}
}
$(this).parent().remove();
}
</script>
</body>
</html>
Maybe the total upload size of your files overcomes the max_upload_limit.Usually is 2 MB.As i tested your code in liveweave i don't have problem (5 images).Check the total size of your files. How much is it?

I have an issue to create dynamic fields with string count using Javascript OR Jquery

I have an issue to create dynamic fields with string count using JavaScript or jQuery.
Briefing
I want to create dynamic fields with the help of sting count, for example when I write some text on player textfield like this p1,p2,p3 they create three file fields on dynamicDiv or when I remove some text on player textfield like this p1,p2 in same time they create only two file fields that's all.
The whole scenario depend on keyup event
Code:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function commasperatedCount(){
var cs_count = $('#player').val();
var fields = cs_count.split(/,/);
var fieldsCount = fields.length;
for(var i=1;i<=fieldsCount;i++){
var element = document.createElement("input");
element.setAttribute("type", 'file');
element.setAttribute("value", '');
element.setAttribute("name", 'file_'+i);
var foo = document.getElementById("dynamicDiv");
foo.appendChild(element);
}
}
</script>
<form>
<label>CountPlayerData</label>
<input type="text" name="player" id="player" onkeyup="return commasperatedCount();" autocomplete="off" />
<div id="dynamicDiv"></div>
<input type="submit" />
</form>
var seed = false,
c = 0,
deleted = false;
$('#player').on('keyup', function(e) {
var val = this.value;
if ($.trim(this.value)) {
if (e.which == 188) {
seed = false;
}
if (e.which == 8 || e.which == 46) {
var commaCount = val.split(/,/g).length - 1;
if (commaCount < c - 1) {
deleted = true;
}
}
commasperatedCount();
} else {
c = 0;
deleted = false;
seed = false;
$('#dynamicDiv').empty();
}
});
function commasperatedCount() {
if (deleted) {
$('#dynamicDiv input:last').remove();
deleted = false;
c--;
return false;
}
if (!seed) {
c++;
var fields = '<input value="" type="file" name="file_' + c + '">';
$('#dynamicDiv').append(fields);
seed = true;
}
}​
DEMO
<script>
function create(playerList) {
try {
var player = playerList.split(/,/);
} catch(err) {
//
return false;
}
var str = "";
for(var i=0; i<player.length; i++) {
str += '<input type="file" id="player-' + i + '" name="players[]" />';
//you wont need id unless you are thinking of javascript validations here
}
if(playerList=="") {str="";} // just in case text field is empty ...
document.getElementById("dynamicDiv").innerHTML = str;
}
</script>
<input id="playerList" onKeyUp="create(this.value);" /><!-- change event can also be used here -->
<form>
<div id="dynamicDiv"></div>
</form>

Categories

Resources