Axios image uploading with text - php

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?

Related

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);

file upload and form data on single form using ajax

I have a html form with 2 input filed and a file upload form and i want to send these data to some index.php file using ajax what i did so far is
<form class="col-md-3" id="form" name="reg" method="post" action="index.php" enctype="multipart/form-data">
<label>Name</label>
<input type="text" name="name" class="form-control" id="name">
<label>Address</label>
<input type="text" name="address" class="form-control">
<div id="sugg">
</div>
<input type="file" name="file">
<input type="button" name="submit" class="btn-default" id="btn" value="submit">
</form>
jquery for send data using ajax is
$("#btn").click(function() {
$.ajax({
url: "index.php",
type: "POST",
data: new FormData($('form')[0]),
cache: false,
conentType: false,
processData: false,
success: function(result) {
console.log(result);
}
});
});
php file has just this
echo $_POST["name"];
but in my browser window i am undefined index
I found similar questions but all that doesn't solved my problem that's why i asking your help please help me to find my error
I am create below code according to my need and you can make changes according to your requirement:
when you click upload/select file button use this function :
$('input[type=file]').on('change', function(e){
e.preventDefault();
$this = $(this);
if($this.prop("files")){
if(setImagestoUpload(e, $this.prop("files"), $this.attr("name"))){
var reader = new FileReader();
reader.onload = function(e){
$('.brandLogo img').attr("src", e.target.result);
$this.parent().prev("img.imageSelection").attr("src", e.target.result);
};
reader.readAsDataURL(this.files[0]);
}
}
});
function setImagestoUpload(e, $file, name){
e.preventDefault();
var type = [];
var isSize = [];
$($file).each(function(i, v){
type[i] = isImage(v);
isSize[i] = isValidSize(2, v.size);
});
if($.inArray(false, type) === -1){
if($.inArray(false, isSize) === -1){
/*if(checkTotalFileInputs() > 1 && files.length>0){
$.each($file, function(ind, val){
files[name] = val;
});
files[name] = $file[0];
}else{
files = $file;
}*/
formData.append(name, $file[0]);
console.log(files);
return true;
}else{
alert("Error: Upload max size limit 2MB");
}
}else{
alert("Please select only image file format to upload !");
return false;
}
}
function isImage(file){
var type = file.type.split("/");
if(type[0] === "image"){
return true;
}else{
return false;
}
}
and when you submit form then use below function:
function fileAndFormSubmit(ev, $this, get, options){
var defaults = {
redirect : false,
redirectTo : "#",
redirectAfter : 5000
};
var settings = $.extend({}, defaults, options);
removeErrorAndSuccess();
var $form = $($this).parent('form');
/*var formData = new FormData();
if(files.length > 0){
$.each(files, function(key, val){
formData.append(key, val);
});
}*/
var doc = {
data : $form.serialize()
};
formData.append("doc", doc.data);
/*Call to ajax here*/
}

Can't figure out how to POST form data to php with $.ajax

EDIT: * updated code to reflect state and current issue *
My HTML form is properly accepting the input[type=file]. I know I'm appending the proper data (file.name) to formData. I know my script archive_upload.php is being called, but this is where things go wrong. $_POST doesn't seem to be taking in any thing. If I print $len after $len = (int) $_POST['CONTENT_LENGTH'];, it shows 0.
How can I properly retrieve the FormData being sent to my script?
Here's my JS:
var formData = new FormData();
var fileSelect = document.getElementById('file');
var uploadButton = document.getElementById('upload');
var form = document.getElementById('file_form');
/*$('#file').change(function() { });*/
form.onsubmit = function(event) {
event.preventDefault();
var files = fileSelect.files;
for (var i=0; i<files.length; i++) {
var file = files[i];
if(!file.type.match('image.*')) {
continue;
}
formData.append(i, file.name);
}
xhr = new XMLHttpRequest();
xhr.open('POST', 'archive_upload.php');
xhr.send(formData);
}
Here's my HTML:
<form id="file_form" action="archive_upload.php" method=POST enctype=multipart/form-data accept-charset=utf-8>
<input type="file" id="file" name="photos[]" />
<button type="submit" id="upload">Upload</button>
</form>
And the PHP:
<?php
$len = (int) $_POST['CONTENT_LENGTH'];
$files = array();
for ($i=0; $i < $len; $i++) {
$f = $_POST[$i]['name'];
$files.append($f);
}
$j = fopen('test.json', 'w');
fwrite($j, json_encode($files));
fclose($j);
?>
From what I understand it is not calling the ajax page at all, therefore consider adding the following code snippet as options in your ajax call:
processData: false,
contentType: false,
I believe this post has experience in a similar issue with file[s] and FormData
Since you are using Html form and ajax for submitting the form data, the simplest way would be something like this :
<script>
$(document).ready(function(){
$("#upload").click(function(){
$.ajax({url: "<your url>",
data: {<put your data here>}
success: function(result){
}
cache: false,
contentType: false,
processData: false
});
});
});
</script>
HTML form:
<form id="file_form" action="archive_upload.php" method=POST enctype=multipart/form-data accept-charset=utf-8>
<input type="file" id="file" name="photos[]" />
<button type="button" id="upload">Upload</button>
</form>

uploading multiple files with XMLHttprequest

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");

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