uploading multiple files with XMLHttprequest - php

I am trying to make an asynchronous file upload form with progress in percent. I thought this might work with a FormData object but I don't think the post is working. nothing happens when I submit. I have checked and there are no bugs and it works without the javascript,so the PHP is OK is there something fundamentally wrong with the code?
var handleUpload = function(event){
event.preventDefault();
event.stopPropagation();
var fileInput = document.getElementById('file');
var data = new FormData();
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.hasChildNones()){
progress.removeChild(progress.firstChild);
}
progress.appendChild(document.createTextNode(Math.round(percent * 100) + '%'));
}
});
request.upload.addEventListener('load',function(event){
document.getElementById('upload_progress').style.display = 'none';
});
request.upload.addEventListener('error',function(event){
alert("failed");
});
request.open('POST','upload.php');
request.setRequestHeader('Cache-Control','no-cache');
document.getElementById('upload_progress').style.display = 'block';
};
window.addEventListener('load',function(event){
var submit = document.getElementById('submit');
submit.addEventListener('click',handleUpload);
});
the html:
<div id = "upload_progress"></div>
<form id="form" action="" method="post" enctype="multipart/form-data">
<input id="file" name="file[]" type="file" multiple /><br>
<input type="submit" name="send" id ="submit" value="send">
</form>
and upload.php
if(!empty($_FILES['file'])){
foreach ($_FILES['file']['name'] as $key => $name) {
move_uploaded_file($_FILES['file']['tmp_name'][$key],"myfiles/$name");
}
}

you have forgotten the most important line in your javascript code:
request.send(data);
after this:
request.setRequestHeader('Cache-Control','no-cache');

After the
request.setRequestHeader('Cache-Control','no-cache');
You forget to send the data..
request.send(data);
BTW, you need to send the proper headers
request.setRequestHeader("Content-type", ,,,
request.setRequestHeader("Content-length",...
request.setRequestHeader("Connection", "close");

Related

Axios image uploading with text

I am using Axios for uploading images.
Here is my HTML:
<form action="" method="post">
<input type="text" id="name">
<input type="files" multiple id="file">
<button type="submit" onclick="submit_form()">Upload</button>
</form>
Axios code:
function submit_form(e) {
e.preventDefault();
var form = new FormData();
var name = document.getElementById("name").value;
var image = document.getElementById("file");
for (i = 0; i < image.files.length; i++) {
let file = image.files[i];
form.append("files[" + i + "]", file);
}
form.append("name", name);
axios.post("ajax.php", form, {headers: {'content-type': 'multipart/form-data'}})
.then((r) => {
console.log(r);
})
}
ajax.php:
$data = json_decode(file_get_contents("php://input"), true);
echo json_encode($data);
In the console it shows me null
If my PHP code is wrong, then can someone give a simple example?

FormData Ajax not posting data in PHP

Hope you can help me with my problem.
The problem is that i put my data in FormData but when i'm calling them in php file using echo there is no values and data existing and gives me error
an undefined variable
But when im using var_dump() or print_r() it show all the values. and also if i var_dump the files for the images it throws me also an error.
Here in html:
<form id="form" action="myurl.php" method="post" enctype="multipart/form-data" onsubmit="return false">
<input type="file" name="image" accept="image/*"/>
<input type="text" name="description"/>
<input type="submit" />
</form>
Here is my code in ajax:
function getName(key)
{
key = document.getElementsByName(key)[0];
return key;
}
function getId(key)
{
key = document.getElementById(key);
return key;
}
var url = getId('form').getAttribute('action');
var datas = new FormData();
var xhr = new XMLHttpRequest();
var image = getName('image').value.trim();
var description = getName('description').value.trim();
datas.append('file_image', image.files[0]);
datas.append('description', description);
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(datas);
xhr.onreadystatechange = function()
{
var OK = 4;
var DONE = 200;
if(xhr.readyState == 4 && xhr.status == DONE)
{
alert(xhr.responseText);
}
}
now in my myurl.php php file
var_dump($_POST);
var_dump($_FILES);
We don't actually using third party script like jQuery. We practice native javascript language.
Thank you.
You don't have to append the element manually to form data, create FormData from the form itself.
Give your form a name name="upload-image
<form id="form" action="myurl.php" name="upload-image" method="post" enctype="multipart/form-data">
<input type="file" name="image" accept="image/*"/>
<input type="text" name="description"/>
<input type="submit" />
</form>
In your Javascript
var form = document.forms.namedItem("upload-image");
var url = form['action'];
form.addEventListener('submit', function(ev) {
var oData = new FormData(form);
var oReq = new XMLHttpRequest();
oReq.open("POST", url, true);
oReq.onload = function(oEvent) {
if (oReq.status == 200) {
alert(oReq.responseText);
} else {
alert(oReq.status + " occurred when trying to upload your file.");
}
};
oReq.send(oData);
ev.preventDefault();
}, false);

Basic jquery & PHP session.upload_progress.name

I am trying to get the file progress working with the new session.upload_progress.name functionality in PHP 5.4.
So far my code is this:
<?
session_start();
?>
<!DOCTYPE html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function () {
$("#jimbo").submit(function () {
setInterval(function() {
$.ajax({
url: "ajx.php",
success: function (data) {
$("#feedback").html(data + Math.random(999));
}
});
//$("#feedback").html("hello " + Math.random(999));
},500);
//return false;
});
});
</script>
</head>
<body>
<h1>Upload</h1>
<br/>
<form action="test.php" method="POST" enctype="multipart/form-data" id='jimbo'>
<input type="hidden" name="<?=ini_get('session.upload_progress.name'); ?>" value="myupload" />
<input type="file" name="file1" />
<input type="submit" id='submitme' />
</form>
<div id="feedback">Hello</div>
</body>
</html>
And then the ajx.php file:
<? session_start(); ?>
<pre>
<?
echo "SESSIONVAR<br/>";
var_dump($_SESSION);
?>
</pre>
Now. When I click the submit button (after selecting a file), The file starts uploading, but the setinterval doesnt start. However, If I have the return false; in there, I get the setInterval results, but the file doesnt start uploading. If I submit the file without returning false, and in a seperate window view the contents of ajx.php, I can see that the variable is working fine and updating. So how do I get the #feedback div to update once the form has been clicked?
note the session array is populated, the problem here is with the jquery and nothing else.
You can achieve similar functionality using javascript XMLHttpRequest objects 'upload' property. It has a couple of events you can hook into, 'progress' is one of them.
here's a sample I've used. It will add a row with the progression (in %) to a <div class="progression"> for each file from a <input type="file"> field:
function startUpload() {
var fileInput = document.getElementById("file1");
$('.progression').show();
for(var i = 0;i<fileInput.files.length;i++) {
doFileUpload(fileInput.files[i]);
}
}
function doFileUpload(file) {
var xhr = new XMLHttpRequest();
var data = new FormData();
var $progress = $('<div class=\"progress\"><p>' + file.name + ':</p><span>0</span>%</div>');
$('div.progression').append($progress);
data.append("file", file);
data.append("album", $("#album").val());
xhr.upload.onprogress = function(e) {
var percentComplete = (e.loaded / e.total) * 100;
$progress.find('span').text(Math.ceil(percentComplete));
};
xhr.onload = function() {
if (xhr.status == 200) {
var result = JSON.parse(xhr.responseText);
if(result.success == "true") {
console.log("Great success!");
}
else {
console.log("Error! Upload failed");
}
};
xhr.onerror = function() {
console.log("Error! Upload failed.");
};
xhr.open("POST", "/_admin/_inc/upload.php", true);
xhr.send(data);
}

how to check which button is clicked in php file with ajax call

I have a form post.php where the user inputs data and receivepost.php where the data entered is transferred through Ajax post. I want to achieve the following in the receivepost.php:
if (button save is pressed) {
save to database
} else if (button retrieve is pressed) {
retrieve from database
}
I tried using isset($_POST['submit']) on the reveivepost.php but it does not detect the button which is pressed. The Ajax post is working and all the data is available on the receivepost page. I have another solution that is to create 2 different PHP files and run them according to the button pressed but I think there is a better solution to it.
Here is my ajax call :
$("document").ready(function () {
$("#submit").click(function () {
var xmlhttp;
// test browsers
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// get the values of textboxes
var desc_text = $("#desc").val();
var speed_text = $("#speed").val();
var tarea_text = $("#tarea").val();
// variable to hold value of textboxes
var content = "desc=" + desc_text + "&speed=" + speed_text + "&tarea=" + tarea_text;
// open the request
xmlhttp.open("POST", "receivepost.php", true);
// set header
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// check xmlhttp state and status and display text in div
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('para').innerHTML = xmlhttp.responseText;
}
}
// send the content of the textboxes
xmlhttp.send(content);
});
});
Here is my post.php form:
<form id="myform">
<label for="description">Description:</label>
<input type="text" id="desc" name="desc" /><br/>
<label for="speed">Speed: </label>
<input type="text" id="speed" name="speed" /><br/>
<textarea id="tarea" cols="10" rows="10" name="tarea"></textarea><br/>
<input type="button" id="submit" name = "submit" value="Save">
<input type="button" id="retrieve" name="retrieve" value="Retrieve">
</form>
<div id="para"></div>
Try to add to the content an extra parameter called button-pressed which you can later use in receivepost.php as below:
if($_POST['button-pressed']=="save"){
//savetodb code
}
else if($_POST['button-pressed']=="retrieve"){
//retreivefromdb code
}
Perhaps you have two JavaScript functions, one on each button:
$("#submit").click(function () {
var content = "button-pressed=save" + "&desc=" + desc_text + "&speed=" + speed_text + "&tarea=" + tarea_text;
$("#retrieve").click(function () {
var content = "button-pressed=retrieve" + "&desc=" + desc_text + "&speed=" + speed_text + "&tarea=" + tarea_text;
Hope this helps?
<input type="button" id="submit" name ="submit" value="save" onClick="fnc(this.id)">
<input type="button" id="retrieve" name="retrieve" value="retrieve" onClick="fnc(this.id)">
<script type="text/javascript">
function fnc(myid) {
var val=document.getElementById(myid).value;
alert(val);
}
</script>

PHP AJAX Image Upload Example Not Uploading

My code produces no errors on the console. When I click the upload button, nothing happens. There is a post sent to itself, as instructed in the tutorial I used but the image is not uploaded to my folder and it is not displayed on my page. Barring the fact I know I should use jquery (I will make the transition once I get it to upload to the folder) what is wrong with my code?
<?php
if (!empty($_FILES)) {
$name = $_FILES['file']['name'];
if ($_FILES['file']['error'] == 0) {move_uploaded_file($_FILES['file']
['tmp_name'], "post_images/" . $name))}
}
?>
<script type="text/javascript">
var handleUpload = function (event) {
event.preventDefault();
event.stopPropagation();
var fileInput = document.getElementById('file');
var data = new FormData();
data.append('file', fileInput.files[1]);
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) +
'%'));
}
});
request.upload.addEventListener('load',function(event) {
document.getElementById('upload_progress').style.display = 'none';
});
request.upload.addEventListener('error', function(event) {
alert('Upload failed');
});
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);
});
</script>
<div id="uploaded">
<?php
if (!empty($name)) {
echo '<img src="post_images/' . $name . '" width="100" height="100" />';
}
?>
</div>
<div id="upload_progress"></div>
<div>
<form action="" method="post" enctype="multipart/form-data">
<div>
<input type="file" id="file" name="file" />
<input type="submit" id="submit" value="upload" />
</div>
</form>
</div>
There is only one file in a non- multiple file input element, fileInput.files[1] attempts to use the second file.
data.append('file', fileInput.files[0]);

Categories