How to post JQuery variable into database [duplicate] - javascript

This question already has answers here:
Using AJAX to dynamically update text from a database
(2 answers)
Closed 5 years ago.
I try javascript typing game by nikola. Here is the link codepen.io/nikola1970/pen/oxXbmb and When the time's up i want to post the points i get to the score table on my database.
CREATE TABLE public.score
(
id bigserial,
score integer,
user character varying(50),
"timestamp" timestamp without time zone,
)
how can i do?
I add the countdown function like this.
function countdown() {
points = 0;
var timer = setInterval(function(){
button.disabled = true;
seconds--;
temp.innerHTML = seconds;
if (seconds === 0) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.open("GET", "ajax.php?points=" + points , true);
xmlhttp.send();
// return false;
alert("Game over! Your score is " + points);
//Done!
scoreDiv.innerHTML = "0";
words.innerHTML = "";
button.disabled = false;
clearInterval(timer);
seconds = 60;
timerDiv.innerHTML = "60";
button.disabled = false;
}
}, 10);
}
and here is my ajax.php
<?php
session_start();
include("config.php");
$score = $_GET['points'];
$user = $_SESSION['id'];
$query = pg_query(" insert into t_score (score, id_user, timestamp) values ('$score', $user, 'now()') ") ;
pg_close()
?>
i've editted my countdown function and ajax.php. now it's work to send the score to the database.

You're going to need some server-side code to process incoming data and stick it in your database. PHP, Django/Python, and Ruby on Rails are all good choices. You could then write an AJAX function in the javascript that sends the score data to the server when the game is over.

Related

Validation Form and send data to the php file

I develop a Validation Form with Javascript All think as right
but I want when Al think are accepted send the information to the php file
How I can make that ?
The HTML code :
<?php
if(isset($_GET['submit'])){
$message = '';
$email = '';
$name ='';
$message = $_GET['comment'];
$email = $_GET['commentMail'];
$name = $_GET['commentName'];
$to = "emailme";
$subject = 'New Message';
$message = " Le nom : ".$name."<br><br>".$message."<br><br> Email : ".$email;
$header = "$email";
if(mail($to, $subject, $message, $header)){
echo '<b style="color: green">Messange Send</b>';
}
else{
echo '<b style="color: red">Sommthing wrong</b>';
}}
?>
<html>
<head>
<title>Contact</title>
<meta charset="UTF-8">
</head>
<body onload="randNums()">
<form>
<input id="commentName" onkeyup="validateName()" name="name" type="text" placeholder="Name"><label id="commentNamePrompt"></label><br>
<input id="commentMail" onkeyup="validateMail()" name="mail" type="text" placeholder="Mail"><label id="commentMailPrompt"></label><br>
<input id="commentPhone" onkeyup="validatePhone()" name="phone" type="text" placeholder="Phone"><label id="commentPhonePrompt"></label><br>
<textarea id="comment" onkeyup="validateComment()" name="commente" placeholder="Message here"></textarea><label id="commentPrompt"></label><br>
<span id="digit1"></span> +
<span id="digit2"></span> =
<input id="captcha" size="2" onkeyup="validateCaptcha()"><label id="captchaPrompt"></label><br>
</form>
<button href="index.php" name="submit" onclick="validateCommentForm()" > Send</button><label id="commentFormPrompt"> </label>
<script type="text/javascript" src="javascript.js"></script>
</body>
</html>
js code
function randNums(){
var rand = Math.floor(Math.random() * 10) + 1;
var rand2 = Math.floor(Math.random() * 10) + 1;
document.getElementById("digit1").innerHTML = rand;
document.getElementById("digit2").innerHTML = rand2;
}
function validateName(){
var name = document.getElementById("commentName").value;
if (name.length == 0){
producePrompt("Name *", "commentNamePrompt", "red");
return false;
}
if(!name.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/))
{
producePrompt("name wrong","commentNamePrompt","red");
return false;
}
producePrompt("accept", "commentNamePrompt", "green");
return true;
}
function validatePhone(){
var phone = document.getElementById("commentPhone").value;
if(phone.length == 0){
producePrompt("phone *", "commentPhonePrompt", "red");
return false;
}
if(phone.length != 10){
producePrompt("10 numbers", "commentPhonePrompt", "red");
return false;
}
if(!phone.match(/^[0-9]{10}$/))
{
producePrompt("phone wrong","commentPhonePrompt","red");
return false;
}
producePrompt("Accept", "commentPhonePrompt", "green");
return true;
}
function validateMail() {
var mail = document.getElementById("commentMail").value;
if(mail.length == 0){
producePrompt("mail *", "commentMailPrompt", "red");
return false;
}
if(!mail.match(/^[A-Za-z._\-0-9]*[#][A-Za-z]*[\.][a-z]{2,4}$/))
{
producePrompt("Wrong mail","commentMailPrompt","red");
return false;
}
producePrompt("accept", "commentMailPrompt", "green");
return true;
}
function validateComment(){
var comment = document.getElementById("comment").value;
var required = 30;
var left = required-comment.length;
if (left > 0){
producePrompt(left + " lettre" ,"commentPrompt","red" );
return false;
}
producePrompt("accept", "commentPrompt", "green");
return true;
}
function validateCaptcha(){
var captcha = document.getElementById("captcha").value;
var digit1 = parseInt(document.getElementById("digit1").innerHTML);
var digit2 = parseInt(document.getElementById("digit2").innerHTML);
var sum = digit1 + digit2;
if(captcha.length == 0){
producePrompt("captcha *", "captchaPrompt", "red");
return false;
}
if(!captcha.match(/^[0-9]{1,2}$/) || !captcha.match(sum)){
producePrompt("Captchas wrong","captchaPrompt","red");
return false;
}
producePrompt("Accept", "captchaPrompt", "green");
return true;
}
function submitForm(){
var server = 'http://localhost/test'; // Your PHP file
var commentName = $('#commentName').val(); // The values of your form
var commentMail = $('#commentMail').val(); // The values of your form
var commentPhone = $('#commentPhone').val(); // The values of your form
var comment = $('#comment').val(); // The values of your form
$.ajax({ // Here the magic starts
url: server+"/index.php", // Where this function will send the values
type:"get", // To get the status of your php file
data: "action=insertNews&commentName="+commentName+"&commentMail="+commentMail+"&commentPhone="+commentPhone+"&comment="+comment, // The values
success: function (data){ // After sending the values to your php file you will receive number 1 or 2, if you receives number 1 it means sucess, but if you receives number 2 it means fail.
if(data == 'Messange Send'){
//
}
else{
//
}
}
});
}
function validateCommentForm(){
if(!validateName() || !validateMail() || !validatePhone() || !validateComment()){
jsShow("commentFormPrompt");
producePrompt("Invalide form","commentFormPrompt","red");
setTimeout(function(){jsHide("commentFormPrompt")}, 2000);
}
else
submitForm();
}
function jsShow(id){
document.getElementById(id).style.display = "block";
}
function jsHide(id){
document.getElementById(id).style.display = "none";
}
function producePrompt(message, promptLocation, color){
document.getElementById(promptLocation).innerHTML = message;
document.getElementById(promptLocation).style.color = color;
}
that's is my code, the php code with HTML, And javascript with Ajax but when I click into submit button nothing happens, Any solution ?
function validateCommentForm(){
if(!validateName() || !validateMail() || !validatePhone() || !validateComment()){
jsShow("commentFormPrompt");
producePrompt("Invalide Form ","commentFormPrompt","red");
setTimeout(function(){jsHide("commentFormPrompt")}, 2000);
}
else
submitForm();
}
function submitForm(){
var server = 'url'; // Your PHP file
var commentName = $('#commentName').val(); // The values of your form
var commentMail = $('#commentMail').val(); // The values of your form
var commentPhone = $('#commentPhone').val(); // The values of your form
var comment = $('#comment').val(); // The values of your form
$.ajax({ // Here the magic starts
url: server+"/api.php", // Where this function will send the values
type:"get", // To get the status of your php file
data: "action=insertNews&commentName="+commentName+"&commentMail="+commentMail+"&commentPhone="+commentPhone+"&comment="+comment, // The values
success: function (data){ // After sending the values to your php file you will receive number 1 or 2, if you receives number 1 it means sucess, but if you receives number 2 it means fail.
if(data == 'Messange Send'){
// sucess code
}
else{
// fail code
}
}
});
}
Edit: You need to echo in your php echo a number 1 if sucess or a number 2 if fail.
PHP
$message = $_GET['comment'];
$email = $_GET['commentMail'];
$name = $_GET['commentName'];
$to = "$email";
$subject = 'New Message';
$message = " Le nom : ".$name."<br><br>".$message."<br><br> Email : ".$email;
$header = "$email";
if(mail($to, $subject, $message, $header)){
echo '<b style="color: green">Messange Send</b>';
}
else{
echo '<b style="color: red">Sommthing wrong</b>';
}
So AJAX is about creating more versatile and interactive web applications by enabling web pages to make asynchronous calls to the server transparently while the user is working. AJAX is a tool that web developers can use to create smarter web applications that behave better than traditional web applications when interacting with humans.
The technologies AJAX is made of are already implemented in all modern web browsers, such as Mozilla Firefox, Internet Explorer, or Opera, so the client doesn't need to install any extra modules to run an AJAX website. AJAX is made of the following:
JavaScript is the essential ingredient of AJAX, allowing you to
build the client-side functionality. In your JavaScript functions
you'll make heavy use of the Document Object Model (DOM) to
manipulate parts of the HTML page.
The XMLHttpRequest object enables JavaScript to access the server
asynchronously, so that the user can continue working, while
functionality is performed in the background. Accessing the server
simply means making a simple HTTP request for a file or script
located on the server. HTTP requests are easy to make and don't cause
any firewall-related problems.
A server-side technology is required to handle the requests that come
from the JavaScript client. In this book we'll use PHP to perform the
server-side part of the job.
For the client-server communication the parts need a way to pass data and understand that data. Passing the data is the simple part. The client script accessing the server (using the XMLHttpRequest object) can send name-value pairs using GET or POST. It's very simple to read these values with any server script.
The server script simply sends back the response via HTTP, but unlike a usual website, the response will be in a format that can be simply parsed by the JavaScript code on the client.
The suggested format is XML, which has the advantage of being widely supported, and there are many libraries that make it easy to manipulate XML documents. But you can choose another format if you want (you can even send plain text), a popular alternative to XML being JavaScript Object Notation (JSON).
Simple example with old school style:
The HTML
<html>
<head>
<title>AJAX with PHP: Quickstart</title>
</head>
<body onload='process()'>
Server wants to know your name:
<input type="text" id="myName" />
<div id="divMessage"></div>
</body>
</html>
The Magician
// stores the reference to the XMLHttpRequest object
var xmlHttp = createXmlHttpRequestObject();
// retrieves the XMLHttpRequest object
function createXmlHttpRequestObject() {
// will store the reference to the XMLHttpRequest object
var xmlHttp;
// if running Internet Explorer
if (window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
xmlHttp = false;
}
}
// if running Mozilla or other browsers
else {
try {
xmlHttp = new XMLHttpRequest();
}
catch (e) {
xmlHttp = false;
}
}
// return the created object or display an error message
if (!xmlHttp)
alert("Error creating the XMLHttpRequest object.");
else
return xmlHttp;
}
// make asynchronous HTTP request using the XMLHttpRequest object
function process() {
// proceed only if the xmlHttp object isn't busy
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
// retrieve the name typed by the user on the form
name = encodeURIComponent(document.getElementById("myName").value);
// execute the quickstart.php page from the server
xmlHttp.open("GET", "**yourPHPfiletoretrievedata**.php?name=" + name, true);
// define the method to handle server responses
xmlHttp.onreadystatechange = handleServerResponse;
// make the server request
xmlHttp.send(null);
}
else
// if the connection is busy, try again after one second
setTimeout('process()', 1000);
}
// executed automatically when a message is received from the server
function handleServerResponse() {
// move forward only if the transaction has completed
if (xmlHttp.readyState == 4) {
// status of 200 indicates the transaction completed successfully
if (xmlHttp.status == 200) {
// extract the XML retrieved from the server
xmlResponse = xmlHttp.responseXML;
// obtain the document element (the root element) of the XML structure
xmlDocumentElement = xmlResponse.documentElement;
// get the text message, which is in the first child of
// the the document element
helloMessage = xmlDocumentElement.firstChild.data;
// update the client display using the data received from the server
document.getElementById("divMessage").innerHTML =
'<i>' + helloMessage + '</i>';
// restart sequence
setTimeout('process()', 1000);
}
// a HTTP status different than 200 signals an error
else {
alert("There was a problem accessing the server: " + xmlHttp.statusText);
}
}
}

unset $_POST inside javascript if statements

i need to unset $_POST['u'] but only inside a javascript function, now $_POST ARRAY unsets itself automatically after the page is ready...
function resetChat(cod_c){
if(confirm('are you sure?')){
if (sendReq.readyState == 4 || sendReq.readyState == 0) {
sendReq.open("POST", 'getChat.php?chat='+cod_c+'&last=' + lastMessage, true);
sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
sendReq.onreadystatechange = handleResetChat;
var param = 'action=reset';
param += '&user=' + document.getElementById('cod_user').value;
sendReq.send(param);
document.getElementById('txt_message').value = '';
}
<?php unset($_POST['u']); ?> // this only 1 time after confirm???
}
}
function handleResetChat() {
}
PHP is server side language and JavaScript is on client side :) You need learn more about webdev ;)

How to send curl upload progress to ajax to be displayed

What I am trying to do is upload the file/files information to upload.php using ajax, then uploading the same information again to a remote server by curl to remoteUpload.php. Finally in remoteUpload.php file I perform the actual upload of the file/files.
When doing the first step -> upload the file/files information to upload.php I display a progress bar of this step using ajax.
But the when doing the second step -> upload the same information again to remote server using curl to remoteUpload.php the progress bar is not displayed, and this is my problem.
How to display the progress bar for second step by ajax ?
Javascript:
var upload_btn = document.getElementById('upload_file');
var result = document.getElementById('result');
upload_btn.onclick = function () {
var uploadInput = document.getElementsByName('file[]')[0];
if (uploadInput.files.length > 0) {
console.clear();
var ajax = new XMLHttpRequest();
var inputFileData = formData(uploadInput);
ajax.onreadystatechange = function () {
if (ajax.readyState == 4 && ajax.status == 200) {
var json = JSON.parse(ajax.responseText);
result.innerHTML = json.text;
}
};
ajax.upload.addEventListener('progress', function (e) {
result.innerHTML = Math.round(e.loaded / e.total * 100) + "%";
});
ajax.open("post", "upload.php");
ajax.send(inputFileData);
}
};
function formData(inputFileObj) {
var formData = new FormData;
var inputFile = inputFileObj.files;
if (inputFile.length > 0) {
for (i = 0; i < inputFile.length; i++) {
formData.append(inputFileObj.name, inputFile[i]);
}
}
return formData;
}
PHP: (upload.php)
function progressCallback($dltotal, $dlnow, $ultotal, $ulnow) {
static $last;
$progress = #round($ulnow / $ultotal * 100);
if($last < $progress) echo json_encode(array('text' => $progress));
flush();
$last = $progress;
}
if (strtolower($_SERVER['REQUEST_METHOD']) == 'post' && !empty($_FILES)) {
foreach ($_FILES['file']['tmp_name'] as $index => $tmpFileName) {
if ($_FILES['file']['error'][$index] > 0) {
$text = "A file did not uploaded correctly.";
return false;
}
$ch = curl_init("http://serverfiles/remoteUpload.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'progressCallback');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('fileupload' => '#' . $tmpFileName));
$text = curl_exec($ch);
}
}
echo json_encode(array('text' => $text));
exit;
PHP: (remoteUpload.php)
if (move_uploaded_file($_FILES['fileupload']['tmp_name'], "files/" . $_FILES['fileupload']['name']))
echo "The file has been uploaded.";
else
echo "error";
You can save in progressCallback() to $_SESSION your $progress and from js side after "first step" upland complete run setIntevral(/*ajax*/) make ajax requests to server get $_SESSION['progress] and display second progress bar(or load first progress barr till 50% and continue load second 50%) in your form and when it complete call clearInterval()
DETAILED ANSWER
Explanation: we will count progress in following logic. If we have uploaded 5 files at once (as in your case seems uploaded was multi file) then we will divide 100% by 5 and will increase by 25% progress during one file curl submit, for this you need following 5 modifications
1) call somewhere above session_start() in your upload.php if it not done
2) save to session total files count and current processing file index
// Saveing total amount of uploaded files
$_SESSION['UP_total_count'] = count($_FILES['file']);
foreach ($_FILES['file']['tmp_name'] as $index => $tmpFileName) {
...
// Saving current index of uploaded file
$_SESSION['UP_current_index'] = ($index+1);//+1 as it starts from 0
}
3) save in progressCallback function current progress number in 0-100 format
function progressCallback($dltotal, $dlnow, $ultotal, $ulnow) {
...
$_SESSION['UP_current_progress'] = $progress;
}
4) create new getUploadProgress.php and return json encoded progress infromation from session
session_start();
echo json_encode( array(
'total_count' => $_SESSION['UP_total_count'],
'current_index' => $_SESSION['UP_current_index'],
'current_progress' => $_SESSION['UP_current_progress'],
) );
5) add in your ajax.onreadystatechange setInteval function call, and define in your js global variable progressSetInterval
....
var progressSetInterval = null;// Global
ajax.onreadystatechange = function () {
if (ajax.readyState == 4 && ajax.status == 200) {
...
progressSetInterval = setInterval(function(){
$.ajax({
type: "POST",
url: "getUploadProgress.php",
success: function(data){
// Calculating progress based on 100 25 logic explained above
var progressPart = 100 / data['total_count'];
var currProgress =
(data['total_count'] - data['current_index']) * progressPart;
currProgress += (progressPart/100) * data['current_progress'];
// You can display progress somehow, apped to div or show prgoress...
console.log( "Second progress: " + currProgress);
// if currProgress is 100% removing setinterval
if( currProgress >= 100 ){
clearInterval( progressSetInterval );
}
},
dataType: 'json'
});
}, 1000);
}
};
NOTE: during usage of this example code of course there will be needed additional rounds, JS/PHP functions addition, variable adjustments or some logical adjustments for more effectiveness, but basically this is logic of one option which you can use

AJAX insert in MySQL delay - non inserting

I'm programming kind of pool application -
I have about 50 divs - 1 shown, 49 hidden. In every div there is a form with radiobuttons and after user clicks on radiobutton, JS calls AJAX - PHP request and inserts answer into MySQL. After success, next div is shown and so on...
Everything works fine, until i answer faster - about 3 question/second.
Then some answers stop being stored. For exmaple answers 1,2,4,6,7,10 are stored. 3,5,8,9 are missing...
How could i avoid it? It's really important to have consictency in answers.
Here is my JS
$('input[type=radio]').click(function () {
$.ajax({
url: 'assets/ajax/save_answer.php',
data: {action: 'save_answer', question: currentQuestion, answer: $('input[name=answer-' + currentQuestion + ']:checked').val(), answer_pattern: 'agree-disagree', seconds: currentTime},
type: 'post',
dataType: 'json',
success: function (output) {
if (output.success) {
$('.loading img').css("display", "none");
$('#' + currentQuestion).remove();
currentQuestion += currentQuestion;
$('#' + currentQuestion).show();
} else {
alert("Answer wasn't stored");
$('.loading img').css("display", "none");
}
},
error: function () {
alert("Answer wasn't stored");
$('.loading img').css("display", "none");
}
});
PHP function
if (isset($_POST['action']) && $_POST['action'] == "save_answer") {
$resp = new stdClass();
$config = HTMLPurifier_Config::createDefault();
$purifier = new HTMLPurifier($config);
$user = $purifier->purify($_SESSION['user_id']);
$projekt = $purifier->purify($_SESSION['projekt_id']);
$otazka = $purifier->purify($_POST['question']);
$odpoved = $purifier->purify($_POST['answer']);
$answer_pattern = $purifier->purify($_POST['answer_pattern']);
$seconds = $purifier->purify($_POST['seconds']);
if(check_answer($answer_pattern, $odpoved)){
$stmt = $db->prepare("SELECT * FROM odpovedi WHERE uzivatel = :uzivatel AND projekt = :projekt AND otazka = :otazka");
$stmt->bindParam(':uzivatel', $user);
$stmt->bindParam(':projekt', $projekt);
$stmt->bindParam(':otazka', $otazka);
$stmt->execute();
$answers_count = count($stmt->fetchAll());
if ($answers_count != 1) {
$stmt = $db->prepare("INSERT INTO odpovedi (uzivatel, projekt, otazka, odpoved, seconds) VALUES (:uzivatel, :projekt, :otazka, :odpoved, :seconds) ");
$stmt->bindParam(':uzivatel', $user);
$stmt->bindParam(':projekt', $projekt);
$stmt->bindParam(':otazka', $otazka);
$stmt->bindParam(':odpoved', $odpoved);
$stmt->bindParam(':seconds', $seconds);
$stmt->execute();
$stmt = $db->prepare("SELECT * FROM odpovedi WHERE uzivatel = :uzivatel AND projekt = :projekt AND otazka = :otazka");
$stmt->bindParam(':uzivatel', $user);
$stmt->bindParam(':projekt', $projekt);
$stmt->bindParam(':otazka', $otazka);
$stmt->execute();
$answer_inserted = count($stmt->fetchAll());
if ($answer_inserted < 1) {
$resp->success = false;
} else {
$resp->success = true;
}
}else{
$resp->success = true;
}
}else{
$resp->success = false;
}
}
print json_encode($resp);
At least alert should be shown, right? But it is not...
Thank you,
Tomáš
Change your alert to
alert('Answer wasn\'t stored');
or,
alert("Answer wasn't stored");
Try option async: false in ajax options.
http://api.jquery.com/jquery.ajax/
As the option name says make asynchronous false, i.e it will wait for ajax to complete before showing next div/element(whatever is in your success).
Well, I've found solution by myself.
I didn't disable radiobutons when one of them was clicked. Because of that - another AJAX function was called and interrupted the previous one.
Now when I disable buttons after click and enable them after ajax succeed is everything fine.
Thank you for your help.

Video File Upload Progress Bar with Javascript and PHP

I want to upload a video file using PHP and show the progress of the upload via an Progress Bar. But this is more difficult like i thought and i tried to put the pieces ive found together but unfortunately i didnt found a working piece of code that has the needed php, ajax and html code all together, so ive tried to put different pieces together.
My Code functions nearly completely. The only thing is, that the current process of the file upload, which i've got in percent, is loaded by my javascript only AFTER the process has ended, and not from the beginning.
Here is my PHP Code:
function file_get_size($file) {
//open file
$fh = fopen($file, "r");
//declare some variables
$size = "0";
$char = "";
//set file pointer to 0; I'm a little bit paranoid, you can remove this
fseek($fh, 0, SEEK_SET);
//set multiplicator to zero
$count = 0;
while (true) {
//jump 1 MB forward in file
fseek($fh, 1048576, SEEK_CUR);
//check if we actually left the file
if (($char = fgetc($fh)) !== false) {
//if not, go on
$count ++;
} else {
//else jump back where we were before leaving and exit loop
fseek($fh, -1048576, SEEK_CUR);
break;
}
}
//we could make $count jumps, so the file is at least $count * 1.000001 MB large
//1048577 because we jump 1 MB and fgetc goes 1 B forward too
$size = bcmul("1048577", $count);
//now count the last few bytes; they're always less than 1048576 so it's quite fast
$fine = 0;
while(false !== ($char = fgetc($fh))) {
$fine ++;
}
//and add them
$size = bcadd($size, $fine);
fclose($fh);
return $size;
}
$filesize = file_get_size('remote-file');
$remote = fopen('remote-file', 'r');
$local = fopen('local-file', 'w');
$read_bytes = 0;
while(!feof($remote)) {
$buffer = fread($remote, 2048);
fwrite($local, $buffer);
$read_bytes += 2048;
//Use $filesize as calculated earlier to get the progress percentage
$progress = min(100, 100 * $read_bytes / $filesize);
fwrite(fopen('files/upload/progress.txt', 'w'), $progress);
//you'll need some way to send $progress to the browser.
//maybe save it to a file and then let an Ajax call check it?
}
fclose($remote);
fclose($local);
This is my Javascript Code:
function main()
{
var pathOfFileToRead = "files/upload/progress.txt";
var contentsOfFileAsString = FileHelper.readStringFromFileAtPath
(
pathOfFileToRead
);
document.body.innerHTML = contentsOfFileAsString;
}
function FileHelper()
{}
{
FileHelper.readStringFromFileAtPath = function(pathOfFileToReadFrom)
{
var request = new XMLHttpRequest();
request.open("GET", pathOfFileToReadFrom, false);
request.send(null);
var returnValue = request.responseText;
return returnValue;
}
}
main();
function progressBarSim(al) {
var bar = document.getElementById('bar-fill');
var status = document.getElementById('status');
status.innerHTML = al+"%";
bar.value = al;
al++;
var sim = setTimeout("progressBarSim("+al+")",1000);
if(al == 100){
status.innerHTML = "100%";
bar.value = 100;
clearTimeout(sim);
var finalMessage = document.getElementById('finalMessage');
finalMessage.innerHTML = "Process is complete";
}
}
var amountLoaded = 0;
progressBarSim(amountLoaded);
The Progressbar does currently work over an Timer, because the main() function doesnt read the content of the "progress.txt" from the beginning but only at the end. so i would like to have some help to combine progressBarSim with main().
*Edit: * I have found a working piece of code: http://www.it-gecko.de/html5-file-upload-fortschrittanzeige-progressbar.html and am using that now.
Here is a ajax function for modern browsers:
//url,callback,type,FormData,uploadFunc,downloadFunc
function ajax(a,b,e,d,f,g,c){
c=new XMLHttpRequest;
!f||(c.upload.onprogress=f);
!g||(c.onprogress=g);
c.onload=b;
c.open(e||'get',a);
c.send(d||null)
}
more about this function https://stackoverflow.com/a/18309057/2450730
here is the html
<form><input type="file" name="file"><input type="submit" value="GO"></form>
<canvas width="64" height="64"></canvas>
<canvas width="64" height="64"></canvas>
<pre></pre>
you can add more fields inside the form and you don't need to change anything in the javascript functions. it always sends the whole form.
this is the code to make this ajax function work
var canvas,pre;
window.onload=function(){
canvas=document.getElementsByTagName('canvas');
pre=document.getElementsByTagName('pre')[0];
document.forms[0].onsubmit=function(e){
e.preventDefault();
ajax('upload.php',rdy,'post',new FormData(this),progressup,progressdown)
}
}
function progressup(e){
animate(e.loaded/e.total,canvas[0],'rgba(127,227,127,0.3)')
}
function progressdown(e){
animate(e.loaded/e.total,canvas[1],'rgba(227,127,127,0.3)')
}
function rdy(e){
pre.textContent=this.response;
}
this is the animation that moves the circular canvas progress bar
function animate(p,C,K){
var c=C.getContext("2d"),
x=C.width/2,
r=x-(x/4),
s=(-90/180)*Math.PI,
p=p||0,
e=(((p*360|0)-90)/180)*Math.PI;
c.clearRect(0,0,C.width,C.height);
c.fillStyle=K;
c.textAlign='center';
c.font='bold '+(x/2)+'px Arial';
c.fillText(p*100|0,x,x+(x/5));
c.beginPath();
c.arc(x,x,r,s,e);
c.lineWidth=x/2;
c.strokeStyle=K;
c.stroke();
}
you can extend this function with some nice bounce effect on initializzation or on progresschange.
http://jsfiddle.net/vL7Mp/2/
to test i would just simply use a upload.php file like that
<?php
print_r(array('file'=>$_FILE,'post'=>$_POST));
?>
test it with chrome first... then apply the necessary changes to use it with older browsers... anyway this code should work with all the newest browsers now.
i understand that this functions are not simple to understand so ...
if you have any questions just ask.
maybe there are some syntax error or something is missing... because i just copied the whole functions and applied some changes on the fly.
some other useful functions:
display a readable filesize:
https://stackoverflow.com/a/20463021/2450730
convert MS to time string or a time string to MS
function ms2TimeString(a){
var ms=a%1e3>>0,s=a/1e3%60>>0,m=a/6e4%60>>0,h=a/36e5%24>>0;
return (h<10?'0'+h:h)+':'+(m<10?'0'+m:m)+':'+(s<10?'0'+s:s)+'.'+(ms<100?(ms<10?'00'+ms:'0'+ms):ms);
}
function timeString2ms(a){
var ms=0,b;
a=a.split('.');
!a[1]||(ms+=a[1]*1);
a=a[0].split(':'),b=a.length;
ms+=(b==3?a[0]*3600+a[1]*60+a[2]*1:b==2?a[0]*60+a[1]*1:s=a[0]*1)*1e3;
return ms
}
A simple PAD LEFT function
function padL(a,b,c){//string,length=2,char=0
return (new Array(b||2).join(c||0)+a).slice(-b);
}
ps.i'm also working on a conversion progress bar. if you are intrested i can show you my progress.

Categories