I attached JS and index.php file. This code not working for image, but for type text it is working properly. I have searched very much but not getting how can upload image by jQuery.
index.php file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title><?= TITLE . ' | ' . ucfirst($page); ?></title>
<!-- Tell the brow form_groupser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<?php include('inc/css-inc.php'); ?>
</head>
<body>
<div class="row form_group">
<div for="inputName" class="col-sm-2 control-div">Image A. </div>
<div class="col-sm-4">
<input type="file" class="form-control" id="qimage" name="imga" onchange="un(this.value)">
</div>
<button type="button" onClick="return savequestion()" id="savequestion" class="btn btn-info pull-right"><?= $act; ?></button><!--</form>-->
<!-- jQuery 2.1.4 -->
<script src="plugins/jQuery/jQuery-2.1.4.min.js"></script>
<!-- Bootstrap 3.3.5 -->
<script src="bootstrap/js/bootstrap.min.js"></script>
</body>
</html>
Js file
$('#savequestion').click(function () {
var qimage1 = $('#qimage').prop('files')[0];
var form_data = new FormData();
form_data.append('qimage', qimage1);
form_data.append('mod', mod);
form_data.append('req', req);
$.ajax({
url: 'common_process.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'POST',
success: function (data) {
alert(data);
}
});
});
Try this:
HTML:
<input id="pic" type="file" name="pic" />
<button id="upload">Upload</button>
Jquery:
$('#upload').on('click', function() {
var file_data = $('#pic').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url : 'upload.php', // point to server-side PHP script
dataType : 'text', // what to expect back from the PHP script, if anything
cache : false,
contentType : false,
processData : false,
data : form_data,
type : 'post',
success : function(output){
alert(output); // display response from the PHP script, if any
}
});
$('#pic').val(''); /* Clear the file container */
});
Php:
if ( $_FILES['file']['error'] > 0 ){
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']))
{
echo "File Uploaded Successfully";
}
}
This will uload your file to "uploads" folder. And also check for the folder write permission.
Related
I am having issues understanding ajax. I am trying to upload the array of pictures when the button on the HTML is clicked so the images update onto the HTML site without it refreshing.
My html:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Homework 12</title>
</head>
<body>
<h1>Pictures of Pets</h1>
<form id="my_form_id" action="index.php" method="POST">
<input type="submit" value="Dog">
</form>
<div id="answer"></div>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function(){
$('#my_form_id').on('submit', function(e){
//Stop the form from submitting itself to the server.
e.preventDefault();
var dog = $('#dog');
$.ajax({
type: "POST",
url: 'index.php',
data: {postdog:dog},
success: function(data){
// alert(data);
$( "#answer" ).append(data);
}
});
});
});
</script>
</body>
</html>
My php
<?php
$dogs = array("Corgi", "Husky", "Samoyed");
if(isset($_POST['postdog'])){
foreach ($dogs as $dog) {
echo "<img src='images/dogs/$dog.jpg'> <br>";
}
};
$cats = array("Scottish_Fold", "Persian", "Himalayan");
foreach ($cats as $cat) {
echo "<img src='images/dogs/$cat.jpg'> <br>";
}
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Homework 12</title>
</head>
<body>
<h1>Pictures of Pets</h1>
SUBMIT
<div id="answer"></div>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
function get_result()
$.ajax({
type: "POST",
url: 'upload.php',
data: {action: 'upload'},
success: function(data){
// alert(data);
$( "#answer" ).append(data);
}
});
}
</script>
</body>
</html>
upload.php
<?php
if(isset($_POST['action']) && $_POST['action'] == 'upload' ){
$dogs = array("Corgi", "Husky", "Samoyed");
foreach ($dogs as $dog) {
echo "<img src='images/dogs/$dog.jpg'> <br>";
};
$cats = array("Scottish_Fold", "Persian", "Himalayan");
foreach ($cats as $cat) {
echo "<img src='images/dogs/$cat.jpg'> <br>";
}
}
?>
HTML :
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Homework 12</title>
</head>
<body>
<h1>Pictures of Pets</h1>
<form enctype="multipart/form-data" action="index.php" method="post" id="my_form_id">
<input name="file[]" type="file" />
<button class="pets">Add More</button>
<input type="button" value="Image upload" id="upload"/>
</form>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
</body>
</html>
Script :
$(document).ready(function(){
$('.pets').click(function(e){
e.preventDefault();
$(this).before("<input name='file[]' type='file'/>");
});
});
$('body').on('click', '#upload', function(e){
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
$.ajax({
url: 'index.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function (data) {
alert("Data Uploaded: "+data);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
return false;
});
index.php :
for($i=0; $i<count($_FILES['file']['name']); $i++){
$target_path = "pets/";
$ext = explode('.', basename( $_FILES['file']['name'][$i]));
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];
if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
echo "Your pets images has been uploaded successfully <br>";
} else{
echo "Error, please try again! <br />";
}
}
I'm trying to create a page that uploads an image. When I hit the upload.php I get this error
Undefined index: files in E:\My-Laptop\Wamp\www\image-upload\upload.php on line 3
and if I do print_r($_FILES)I get an empty array.
I'm not sure where I went wrong.
Here is my code.
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link href="css/styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="container" >
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="files[]" id="file" multiple>
<!-- Drag and Drop container-->
<div class="upload-area" id="drop-zone">
<h1>Drag and Drop file here<br/>Or<br/>Click to select file</h1>
</div>
</form>
</div>
<script src="http://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="js/main.js"></script>
</body>
</html>
my main.js
$(document).ready(function(){
var dropZone = document.getElementById('drop-zone');
dropZone.ondrop = function(e){
e.preventDefault();
var transfer = e.dataTransfer.files;
uploadImage(transfer);
}
dropZone.ondragover = function(e){
return false;
}
dropZone.ondragleave = function(e){
return false;
}
});
function uploadImage(files){
var dataString = 'files='+files;
$.ajax({
type: 'POST',
url: 'upload.php',
data: dataString,
success: function(response){
console.log(response);
}
});
}
my upload.php
<?php
print_r($_FILES['files']);
Hope it's help:
function uploadImage(files){
var data = new FormData();
$.each( files, function( key, value ){
data.append( key, value );
});
$.ajax({
type: 'POST',
url: 'upload.php',
data: data,
success: function(response){
console.log(response);
}
});
}
i'm trying to recreate this guide from olanod answer but isn't working for me.
I want to upload a file using AJAX but i'm getting an empty $_POST:
<form enctype="multipart/form-data">
<input type="file" name="file">
<br>
<input type="text" name="as" value="asd">
<!--<button type='button' class="add_more">Add More Files</button>-->
<input type="button" value="Upload" />
</form>
and this is my script (copy paste from olanod answer ):
<script>
$(document).ready(function(){
/* $('.add_more').click(function(e){
e.preventDefault();
$(this).before("<input name='upfile[]' type='file'/><br>");
});*/
$(':button').on('click', function()
{
$.ajax({
// Your server script to process the upload
url: 'ajax.php',
type: 'POST',
// Form data
data: new FormData($('form')[0]),
// Tell jQuery not to process data or worry about content-type
// You *must* include these options!
cache: false,
contentType: false,
processData: false,
// Custom XMLHttpRequest
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
// For handling the progress of the upload
myXhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
$('progress').attr({
value: e.loaded,
max: e.total,
});
}
} , false);
}
return myXhr;
},
});
});
});
</script>
As i said, i'm tring to see what i'm taking and this is the result from my php file:
array(1) {
["as"]=>
string(3) "asd"
}
I returned a text field to be sure.
P.D: Sorry for my english. I hope you can understand me, i'm trying my best!
Check this one..
<!DOCTYPE html>
<html lang="en">
<head>
<title>Ajax Image Upload</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="../js/jquery-3.1.1.min.js"></script>
<script src="../js/validator.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<span id="msg"></span>
<h2>Image Upload Form</h2>
<form data-toggle="validator" role="form" name="image-form" method="post" enctype="multipart/form-data" id="my-form" action="<?php $_SERVER['PHP_SELF']; ?>">
<div class="form-group">
<label for="image">Image:</label>
<input type="file" id="image" name="image[]" data-error="Upload Image" multiple required>
<div class="help-block with-errors"></div>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function (e) {
$("#my-form").on('submit', (function (e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: "upload.php",
type: "POST",
data: formData,
contentType: false,
cache: false,
processData: false,
success: function (data) {
$("#my-form")[0].reset();
//alert(data);
$("#msg").html(data);
},
});
return false; //IE
}));
});
</script>
As #user2486 said,
You should use $_FILES not $_POST – user2486
He is right.
you can use this method to upload file
html-
<input type="file" class="btn btn-default" name="img2" id="img2" />
javascript-
var formData = new FormData();
formData.append('Photo', $('#img2')[0].files[0]);
$.ajax({
url: 'ImgUpload.php',
data: formData,
type: "POST",
// THIS MUST BE DONE FOR FILE UPLOADING
contentType: false,
processData: false,
}).done(function( msg ) {
I have the most simple case of image upload. When I run this as a separate example it DOES work. When I incorporate the same .js code into my project's javascript code, and try the upload from my html page (.js and .php codes identical, id's and names adjusted etc.), it doesn't work.
html:
<html>
<head>
<title>HTML5 File API</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="main">
<h1>Upload Your Images</h1>
<input type="file" name="images" id="images"/>
<input type="submit" id="submitImages" onclick="submitImages()">
<div id="response"></div>
<ul id="image-list">
</ul>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script src="upload.js"></script>
</body>
</html>
javascript:
function submitImages(){
if (window.FormData) {
formdata = new FormData();
}
file = document.getElementById('images').files[0];
if (!!file.type.match(/image.*/)) {
if (formdata) {
formdata.append("images[]", file);
}
}
if (formdata) {
$.ajax({
url: "upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
console.log(res);
}
});
}
}
php:
<?php
foreach ($_FILES["images"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$name = $_FILES["images"]["name"][$key];
move_uploaded_file( $_FILES["images"]["tmp_name"][$key], "uploads/" . $_FILES['images']['name'][$key]);
}
}
echo "<h2>Successfully Uploaded Images</h2>";
?>
The message I get from server when I attempt the upload from my project:
POST-->POST:
Source
-----------------------------2656620091882 Content-Disposition: form-data; name="images[]"; filename="dock_2.jpg" Content-Type: image/jpeg ÿØÿáa"Exif��MM�*��
etc.
POST-->RESPONSE:
<br />
<b>Notice</b>: Undefined index: images in <b>C:\XAMPP\htdocs\Projects\DockMapper\add_edit_upload_images.php</b> on line <b>3</b><br />
<br />
<b>Warning</b>: Invalid argument supplied for foreach() in <b>C:\XAMPP\htdocs\Projects\DockMapper\add_edit_upload_images.php</b> on line <b>3</b><br />
<h2>Successfully Uploaded Images</h2>
It seems that something is sent to the server, but that it is not received on the server. When I run: print_r($_FILES); the array is empty. I spent probably two days over this and I couldn't find the problem. Any suggestions? Big thanks.
Use this
For example
Jquery
$('#upload').on('click', function() {
var file_data = $('#sortpicture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data)
alert(form_data);
$.ajax({
url: 'upload.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data){
alert(data);
}
});
});
PHP
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
Ok, this was the issue:
In my project's html file, jquery was included inside the HEADER with these lines:
<head>
...
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
...
</head>
It worked when I deleted those lines, and included ONLY the following ajax library, inside the FOOTER:
<html>
<body>
...
</body>
...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
...
</html>
I have been trying my hands on PHP lately, so far so good until I hit a brick wall. Here's a little piece of code that I have. It's allowing me to upload a single file, but what I want is to be able to upload multiple files.
Here's the PHP and HTML files:
<html>
<head>
<meta charset="utf-8" />
<title>Ajax upload form</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
function sendfile(){
var fd = new FormData();
for (var i = 0, len = document.getElementById('myfile').files.length; i < len; i++) {
fd.append("myfile", document.getElementById('myfile').files[i]);
}
$.ajax({
url: 'uploadfile.php',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
}
</script>
</head>
<body>
<form action="uploadfile.php" method="post" enctype="multipart/form-data" id="form-id">
<p><input id="myfile" type="file" name="myfile" multiple=multiple/>
<input type="button" name="upload" id="upload" value="Upload" onclick="sendfile()" id="upload-button-id" /></p>
</form>
</body>
</html>
And the PHP file:
<?php
$target = "uploadfolder/";
//for($i=0; $i <count($_FILES['myfile']['name']); $i++){
if(move_uploaded_file($_FILES['myfile']['tmp_name'], $target.$_FILES['myfile']['name'])) {
echo 'Successfully copied';
}else{
echo 'Sorry, could not copy';
}
}//
?>
Any help would be highly appreciated.
Index.html
<html>
<head>
<title>Load files</title>
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#myfiles').on("change", function() {
var myfiles = document.getElementById("myfiles");
var files = myfiles.files;
var data = new FormData();
for (i = 0; i < files.length; i++) {
data.append('file' + i, files[i]);
}
$.ajax({
url: 'load.php',
type: 'POST',
contentType: false,
data: data,
processData: false,
cache: false
}).done(function(msg) {
$("#loadedfiles").append(msg);
});
});
});
</script>
</head>
<body>
<div id="upload">
<div class="fileContainer">
<input id="myfiles" type="file" name="myfiles[]" multiple="multiple" />
</div>
</div>
<div id="loadedfiles">
</div>
</body>
</html>
load.php
<?php
$path="myfiles/";//server path
foreach ($_FILES as $key) {
if($key['error'] == UPLOAD_ERR_OK ){
$name = $key['name'];
$temp = $key['tmp_name'];
$size= ($key['size'] / 1000)."Kb";
move_uploaded_file($temp, $path . $name);
echo "
<div>
<h12><strong>File Name: $name</strong></h2><br />
<h12><strong>Size: $size</strong></h2><br />
<hr>
</div>
";
}else{
echo $key['error'];
}
}
?>