How to update jQuery-UI progress bar with AJAXcall (files scan) - javascript

I want to hash all the files in a specific folder with AJAX and update the progress, meaning I don't want the AJAX to stop at the first reply. I searched online and I thing I found the right answer but it doesn't work.
My jQuery( mixed js):
jQuery(document).ready(function($) {
$('#progress').progressbar();
document.getElementById('save').onclick = function() {
var div = document.getElementById('save_log');
var security = $('#save_security').val();
div.innerHTML = '';
xhr = new XMLHttpRequest();
xhr.open("POST", checkit.admin_ajax, false);
xhr.onprogress = function(evt) {
//var json = JSON.parse(e.currentTarget.responseText);
//var percentComplete = ( json.currentFile * 100 ) / json.filesCount;
var progress = evt.currentTarget.responseText;
$('#progress').progressbar("value", progress);
}
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
console.log(xhr);
}
}
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send("action=checkit_scan_files&security=" + security);
};
});
and my php AJAX
$iterator = new RecursiveDirectoryIterator($dir);
$iterator->setFlags(RecursiveDirectoryIterator::SKIP_DOTS);
$fi = new RecursiveIteratorIterator( $iterator );
$files = array();
$i = 1;
$size = $this->get_files_count();
foreach ($fi as $file) {
if ( !$file->isDir() ) {
$files[$i]['md5'] = md5_file( $file->getPathname() );
$files[$i]['path'] = $file->getPathname();
$progress = ($i * 100) / $size;
$i++;
echo intval( $progress );
}
}

Related

i want to save or download an image from blob url or data

im doing a paste event from clipboard, it creates a blob url. Now i dont how to save or get the file. How can i save it to my computer? I think im totally wrong in getting the blob in my php. im getting it as a string then trying to save it
This is my code for creating the blob
<?php
if( isset( $_FILES['file'] ) ) {
$file_contents = file_get_contents( $_FILES['file']['tmp_name'] );
header("Content-Type: " . $_FILES['file']['type'] );
die($file_contents);
}
else {
header("HTTP/1.1 400 Bad Request");
}
print_r($_FILES);
?>
<script type="text/javascript">
document.onpaste = function (e) {
var items = e.clipboardData.items;
var files = [];
for( var i = 0, len = items.length; i < len; ++i ) {
var item = items[i];
if( item.kind === "file" ) {
submitFileForm(item.getAsFile(), "paste");
}
}
};
function submitFileForm(file, type) {
var extension = file.type.match(/\/([a-z0-9]+)/i)[1].toLowerCase();
var formData = new FormData();
formData.append('file', file, "image_file");
formData.append('extension', extension );
formData.append("mimetype", file.type );
formData.append('submission-type', type);
var xhr = new XMLHttpRequest();
xhr.responseType = "blob";
xhr.open('POST', '<?php echo basename(__FILE__); ?>');
xhr.onload = function () {
if (xhr.status == 200) {
var img = new Image();
img.src = (window.URL || window.webkitURL)
.createObjectURL( xhr.response );
document.getElementById("nye").appendChild(img);
document.getElementById("nye").style.display = "none" ;
var x = document.getElementById("image");
x.setAttribute("type", "text");
x.setAttribute("value", img.src);
document.getElementById("image").appendChild(x);
}
};
xhr.send(formData);
}
</script>
This is my code that's save to my computer, it runs but i juts recive a blank jpg file
<?php
$data = $_POST['url'];
$filePath = $uploadDir . $name;
$contents_split = explode(',', $data);
$encoded = $contents_split[count($contents_split)-1];
$decoded = "";
for ($i=0; $i < ceil(strlen($encoded)/256); $i++) {
$decoded = $decoded . base64_decode(substr($encoded,$i*256,256));
}
$fp = fopen('sample23.jpg', 'w');
fwrite($fp, $decoded);
fclose($fp);
?>
it saves but i think the file is blank.

Json decode from Javascript to php to Javascript

I am trying to get the value from json.stringfy sent to PHP file, for some reason php file is not receiving the key. If I manually add the key it is working fine. What could be wrong here:
My php file:
$request = json_decode(file_get_contents('php://input'), true);
$getID = $request['docid'];
$query = mysqli_query($con, "SELECT * FROM user_details WHERE id = $getID'");
if(mysqli_num_rows($query) > 0)
{
$response["details"] = array();
while ($row = mysqli_fetch_array ($query))
{
// temp user array
$detail = array();
$detail["docname"] = $row["docname"];
$detail["textresults"] = $row["textresults"];
array_push($response["details"], $detail);
}
echo json_encode($response);
$response["success"] = 1;
}
else
{
$response["success"] = 0;
echo json_encode($response);
}
This is my javascript file:
function loadData() {
var docid = window.localStorage.getItem('myKey');
console.log("Docid " + docid);
var xhr = new XMLHttpRequest();
var url = "./api/getData.php";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json);
}
};
var data = JSON.stringify({'docid': docid});
xhr.send(data);
}

Can't upload large files using XHR and FormData

I have created simple script using XMLHttpRequest. It sends text and (optionally) file. It works but problem is that large files (above 50MB) are not accepted. I thought that problem was with PHP's upload_max_filesize or post_max_size but it doesn't (I set it up 512MB). I don't know what to do now... Any ideas?
function publishPost() {
if (!event) { event = window.event; }
event.preventDefault();
var data = new FormData();
data.append('SelectedFile', document.querySelector('#post input').files[0]);
var x = new XMLHttpRequest();
x.open('POST', 'upload.php', true);
x.setRequestHeader('TEXT', post.innerHTML);
x.onload = function() {
if (x.readyState == XMLHttpRequest.DONE) {
if (x.responseText == '1') {
location.reload();
} else {
alert('Error: ' + x.responseText);
}
}
}
x.send(data);
}
And PHP:
$text = strip_tags($_SERVER['HTTP_TEXT']);
$file = $_FILES['SelectedFile']['name'];
$info = pathinfo($file);
$uniqid = uniqid();
if (!empty($file)) {
$newfile = '../files/'.$uniqid.'.'.$info['extension'];
if (move_uploaded_file($_FILES['SelectedFile']['tmp_name'], $newfile)) {
$file = $uniqid.'.'.$info['extension'];
}
}
// Adding to Database
My error is Undefined index: SelectedFile

Sending two files in a queue

Hey I have a problem with sending two files in a queque. I don't have any idea how to do that when I select 2 files, 2 were uploaded at once, and the next 2 were waiting in queue. Now when I select 4 files, 2 are sent and the next two will not send. Please look in my code. Maybe you have an idea. What I must to do that make it work in function induction ?
(function() {
var imageType = /image.*/;
function uploadFile(file, percent_info, p_bar, licznik) {
var url = "server/index.php";
if (file[licznik].type.match(imageType)) {
var xhr = new XMLHttpRequest();
var fd = new FormData();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentLoaded = Math.round((evt.loaded / evt.total) * 100);
if (percentLoaded < 100) {
percent_info[licznik].style.width = percentLoaded + "%";
}
}
});
xhr.upload.addEventListener("load", function(e) {
var percentLoaded = Math.round((e.loaded / e.total) * 100);
percent_info[licznik].style.width = percentLoaded + "%";
});
function ready() {
return function() {
if (xhr.readyState == 4 && xhr.status == 200) {
p_bar[licznik].classList.add('trans_completed');
if (licznik < file.length){
licznik++;
}
}
};
}
xhr.onreadystatechange = ready();
xhr.open("POST", url, true);
fd.append('uploaded_file', file[licznik]);
xhr.send(fd);
}
};
var uploadfiles = document.querySelector('#file-upload');
uploadfiles.addEventListener('change', function() {
var files = this.files;
var percent_info = document.querySelectorAll('.progress_bar:not(.trans_completed) .percent');
var p_bar = document.querySelectorAll('.progress_bar:not(.trans_completed)');
/* --- Upload files to server loop --- */
(function induction(files, percent_info, p_bar) {
counter_file = 0;
counter_file_2 = 1;
function caller() {
uploadFile(files, percent_info, p_bar, counter_file);
uploadFile(files, percent_info, p_bar, counter_file_2);
}
caller();
})(files, percent_info, p_bar);
});
})();

Submit the form when on browser reload/add new tab

Just got some codes from worldofwebcraft.com for my project examination system.I only know PHP,and I actually have no idea on javascripts because our teacher hasnt taught us yet. Please help me on how do I submit the form automatically when the user reloads the page or when he/she opens a new tab.
heres the codes:
<?php if(isset($_GET['question'])){
$question = preg_replace('/[^0-9]/', "", $_GET['question']);
$next = $question + 1;
$prev = $question - 1; ?>
<script type="text/javascript">
function countDown(secs,elem) {
var element = document.getElementById(elem);
element.innerHTML = "You have "+secs+" seconds remaining.";
if(secs < 1) {
var xhr = new XMLHttpRequest();
var url = "userAnswers.php";
var vars = "radio=0"+"&qid="+<?php echo $question; ?>;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert("You did not answer the question in the allotted time. It will be marked as incorrect.");
clearTimeout(timer);
}
}
xhr.send(vars);
document.getElementById('counter_status').innerHTML = "";
document.getElementById('btnSpan').innerHTML = '<h2>Times Up!</h2>';
document.getElementById('btnSpan').innerHTML += 'Click here now';
}
secs--;
var timer = setTimeout('countDown('+secs+',"'+elem+'")',1000);
}
</script>
<script>
function getQuestion(){
var hr = new XMLHttpRequest();
hr.onreadystatechange = function(){
if (hr.readyState==4 && hr.status==200){
var response = hr.responseText.split("|");
if(response[0] == "finished"){
document.getElementById('status').innerHTML = response[1];
}
var nums = hr.responseText.split(",");
document.getElementById('question').innerHTML = nums[0];
document.getElementById('answers').innerHTML = nums[1];
document.getElementById('answers').innerHTML += nums[2];
}
}
hr.open("GET", "questions.php?question=" + <?php echo $question; ?>, true);
hr.send();
}
function x() {
var rads = document.getElementsByName("rads");
for ( var i = 0; i < rads.length; i++ ) {
if ( rads[i].checked ){
var val = rads[i].value;
return val;
}
}
}
function post_answer(){
var p = new XMLHttpRequest();
var id = document.getElementById('qid').value;
var url = "userAnswers.php";
var vars = "qid="+id+"&radio="+x();
p.open("POST", url, true);
p.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
p.onreadystatechange = function() {
if(p.readyState == 4 && p.status == 200) {
document.getElementById("status").innerHTML = '';
alert("Your answer was submitted.");
var url = 'exam.php?question=<?php echo $next; ?>';
window.location = url;
}
}
p.send(vars);
document.getElementById("status").innerHTML = "processing...";
}
</script>
<script>
window.oncontextmenu = function(){
return false;
}
document.onkeydown = function() {
if(event.keyCode == 116) {
event.returnValue = false;
event.keyCode = 0;
return false;
}
}
</script>
I would do something like :
window.onbeforeunload = function() {
post_answer();
}
If post_answer() is your "submit the form"-handler. Cannot tell exactly from the code.

Categories

Resources