Hi I'm having some trouble figuring out whats wrong with my ajax request. Its a script for uploading pictures.
The php file sets up a page with an inline popup for selecting images and displaying their previews
the selection is done in a form called #uploads and if the form is submitted it works the way its supposed to, refreshing to a page where the $_FILES info is included
the php file:
<?php
echo (print_r($_FILES));
$html = '
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="/style/style.css">
<title>test</title>
</head>
<body>
<div id="overlay"></div>
<div id="bilder"></div>
<div id="nybild">
<div id="ny_header">
<form id="upload" method="post" enctype="multipart/form-data">
<input type="file" id="filer" name="filer" multiple>
<input type="submit">
</form>
<div id="preview"></div>
</div>
<div>
<button id="add">Lägg till</button>
<button id="cancel">Avbryt</button>
</div>
</div>
<button id="lagg_till">Lägg till nu bild</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="/js/page.js"></script>
</body>
</html>
';
echo $html;
The java script file contains the logic for showing selection popup, creating previews of files and finally uploading them with ajax. This last part however does not work. The page returned displays an empty $_FILES array
page.js:
$(function(){
$nybild = $("#nybild");
$overlay = $("#overlay");
$overlay2 = $("#overlay2");
$preview = $("#preview");
$("#lagg_till").click(function(){
$overlay.show();
$nybild.show();
});
$("#filer").on("change", function(){
$preview.html("");
var files = this.files;
for(var i = 0; i < files.length; i++){
if(files[i].type.match("image.*")){
var reader = new FileReader();
reader.onload = (function(theFile){
return function(e){
$preview.append(["<img src='", e.target.result, "' class='thumb' title='", escape(theFile.name), "'/>"].join(''));
};
})(files[i]);
reader.readAsDataURL(files[i]);
}
}
});
$("#cancel").click(close_nybild);
$("#add").click(function(){
var formdata = new FormData($("#upload").get());
$.ajax({
type: 'POST',
dataType: 'text',
beforeSend: function(){
console.log(formdata);
},
success: function(data){
var pop = window.open("", "MsgWindow", "width=200, height=100");
pop.document.write(data);
},
error: function(){
$overlay2.hide();
alert("Upload Misslyckades B(");
},
// Form data
data: formdata,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
})
});
function close_nybild(){
$overlay.hide();
$nybild.hide();
reset($nybild);
}
var reset = function(e){
e.wrap("<form>").closest('form').get(0).reset();
e.unwrap();
$preview.html("");
}
});
The majority of the code is shamelessly copied from here: How can I upload files asynchronously?