Jquery Ajax File Upload PHP

jQuery AJAX file upload PHP

You need a script that runs on the server to move the file to the uploads directory. The jQuery ajax method (running on the client in the browser) sends the form data to the server, then a script running on the server handles the upload.

Your HTML is fine, but update your JS jQuery script to look like this:

(Look for comments after // <-- )

$('#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', // <-- 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(php_script_response){
alert(php_script_response); // <-- display response from the PHP script, if any
}
});
});

And now for the server-side script, using PHP in this case.

upload.php: a PHP script that is located and runs on the server, and directs the file to the uploads directory:

<?php

if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}

?>

Also, a couple things about the destination directory:

  1. Make sure you have the correct server path, i.e., starting at the PHP script location what is the path to the uploads directory, and
  2. Make sure it's writeable.

And a little bit about the PHP function move_uploaded_file, used in the upload.php script:

move_uploaded_file(

// this is where the file is temporarily stored on the server when uploaded
// do not change this
$_FILES['file']['tmp_name'],

// this is where you want to put the file and what you want to name it
// in this case we are putting in a directory called "uploads"
// and giving it the original filename
'uploads/' . $_FILES['file']['name']
);

$_FILES['file']['name'] is the name of the file as it is uploaded. You don't have to use that. You can give the file any name (server filesystem compatible) you want:

move_uploaded_file(
$_FILES['file']['tmp_name'],
'uploads/my_new_filename.whatever'
);

And finally, be aware of your PHP upload_max_filesize AND post_max_size configuration values, and be sure your test files do not exceed either. Here's some help how you check PHP configuration and how you set max filesize and post settings.

jQuery Ajax File Upload

File upload is not possible through AJAX.

You can upload file, without refreshing page by using IFrame.

You can check further details here.


UPDATE

With XHR2, File upload through AJAX is supported. E.g. through FormData object, but unfortunately it is not supported by all/old browsers.

FormData support starts from following desktop browsers versions.

  • IE 10+
  • Firefox 4.0+
  • Chrome 7+
  • Safari 5+
  • Opera 12+

For more detail, see MDN link.

How to upload file and insert data with php jquery ajax

i think your problem may be in ajax code
since you are using formData object . try append the message variable with it

$('#submit').on('click', function(){

var fd = new FormData(this);
fd.append('file',$('#file')[0].files[0]);
fd.append('message ',$('#message').val());

$.ajax({
method:"POST",
url:"<?php echo site_url('home/send_chat');?>",
data: fd,
cache: false,
contentType: false,
processData: false,
success: function(data){
alert(data);
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
});

jQuery AJAX - send file and variable to PHP in single request

You can also append the number key => value to to the form data as

form_data.append('number',  variable1);

Then in Ajax call

data: form_data,

How to upload multiple files using PHP, jQuery and AJAX

Finally I have found the solution by using the following code:

$('body').on('click', '#upload', function(e){
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);

$.ajax({
url: 'upload.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;
});

managing file upload with ajax jquery and php

TL;DR :)

You can easily process different input[type=file] via it's onChange event

Let's assume, that we have an input

<input type="file" id="myAwesomeFilepicker" />

We want to send file whenever user select file(s), so we are adding an event listener (I don't like jQuery, so I'll write some vanilla JS, hope you will understand):

document.getElementById("myAwesomeFilepicker").addEventListener("change", function(event) {
var input = event.target
if (input.files.length > 0) {
// create an empty FormData instance
var formData = new FormData()

// Iterate through picked files
for (var i = 0; i < input.files.length; i++) {
var file = input.files[i]
// append file to the FormData instance
formData.append(file.name, file)
}

/*
At this point you can just send formData through AJAX
and handle it by your PHP script
*/

// Don't forget to clear input
input.value = ""
} else {
// process 0 files picked, if you wish
}
})


NOTA BENE

FormData has restricted functionality on iOS / MacOS (AFAIK, only FormData.append(...) is present), so be careful with it.


With some small modifications you can make files send after another user's action (for example, button click or something).
Hope, my answer was useful for you :)


Yes, I wrote answer by my memory and without testing code. It should work, but there can be some errors :)

How to write file upload function ajax, jquery, php? How should I write my '.submit()' using Ajax function?

Please use the below files code to upload the files and return success or error in the jason format:

index.php file code

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title>Files Upload</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>

<form action="upload.php" method="post" enctype="multipart/form-data" >
<input id="file-upload" type="file" name="fileToUpload[]" multiple required>
<input type="submit" id="file-submit" value="Upload Selected Files">
</form>

<script type="text/javascript">
$(document).ready(function(){
$("#file-submit").click(function(event){
event.preventDefault();
var formdata = new FormData($(this).parents('form')[0]);

$.ajax ({
type: "POST",
url: "upload.php",
dataType : 'json',
data: formdata,
success: function(data){

if(data.status){
alert(data.status);
}else{
alert(data.error);
}
},
processData:false,
contentType: false,
cache: false
});
return false;
})
});
</script>
</body>
</html>

upload.php file code here

<?php
function getExt($name){
$array = explode(".", $name);
$ext = strtolower(end($array));
return $ext;
}

//create global array
$allowed = array('jpg', 'png', 'jpeg', 'mp4');
$message = array();
$error = array();
$jason = array();

if(isset($_FILES['fileToUpload']) && !empty($_FILES['fileToUpload'])){
foreach ($_FILES['fileToUpload']['name'] as $key => $name) {
$tmp = $_FILES['fileToUpload']['tmp_name'][$key];
$ext = getExt($name);
$size = $_FILES['fileToUpload']['size'][$key];

// check the extension is valid or not
if(in_array($ext, $allowed) == true){
$filename = md5($name) . time() .'.'.$ext;
//check the size of the file
if($size <= 10485760){
if(move_uploaded_file($tmp, 'uploadFiles/'.$filename) === true){
$message['status'] = 'File is uploaded successfully';

}else{
$message['error'] = 'File is not uploaded';
}
}else{
$message['error'] = 'File size more than 2MB';
}
}else{
$message['error'] = 'File Type not allowed';
}
}

echo json_encode($message);exit();

}
?>

Hope this help!!



Related Topics



Leave a reply



Submit