Uploading a File via Ajax with 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.

File Upload via Ajax with PHP

The first problem is that you are using GET method in your AJAX request. GET requests cannot have a request body. To be more precise, a client can send a
GET request having a body, but servers are implemented to ignore it.
Note that you use POST method in the form.

The second problem is that you are not actually including the file data in your JavaScript code. There is an example on MDN website: see how FormData is used to send a file in the POST request

        function sendFile(file) {
const uri = "/index.php";
const xhr = new XMLHttpRequest();
const fd = new FormData();

xhr.open("POST", uri, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText); // handle response.
}
};
fd.append('myFile', file);
// Initiate a multipart/form-data upload
xhr.send(fd);
}

As a side note, for this kind of operation I recommend to look into HTML5 File API, to read the bytes of the file, and send them to the server. You can also chunk the bytes to make more web requests, to support uploading files of any size.

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

upload image file through ajax and php

ok I solved my issue/error about my own question. I understood a lot actually about how openCart upload images, how ajax and xhr works and so on. Anyway, the code I have used is this:

Inside file profile.tpl:

$('#upload-image').on('click',function(e){
var formData = new FormData($('#submitProfile')[0]);
formData.append('route','account/profile');
$.ajax({
url: 'index.php?route=tool/upload/logo',
type: 'post',
data: formData,
cache: false,
contentType: false,
processData: false,
beforeSend: function() {
$("#containerAlertMessages").html("<div class='alert alert-info'><strong>Sending...</strong></div>");
$("#containerAlertMessages").removeClass("containerAlertMessages").addClass("containerAlertMessagesVisible");
},
complete: function() {
$("#containerAlertMessages").html("<div id='alertMessages' class='alert alert-success'><strong>Success!</strong> Your logo has been uploaded successfully! Do not forget to save the abovr information by clicking the Save button at the bottom right corner!</div>");
$("#containerAlertMessages").removeClass("containerAlertMessages").addClass("containerAlertMessagesVisible");
},
success: function() {
//nothing yet
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
});

Inside file upload.php:

public function logo() {
$this->load->language('tool/upload');

if (!empty($this->request->files['file']['name']) && is_file($this->request->files['file']['tmp_name'])) {
$filename = html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8');

$route = $this->request->post['route'];
if($route == "account/profile") {
$file = "image/" . $filename;
move_uploaded_file($this->request->files['file']['tmp_name'], DIR_LOGOS . $file);
}
}
}
  • DIR_LOGOS has been defined inside config.php file, so I could reffer to this variable again in another file if I want it to.
  • Furthermore, I am sending the route variable, in order to know from where the image upload is coming.
    So, if the uploading is coming from 'account/profile' I am saving the image to '/image' folder
    if its coming from 'accoun/register' I am saving to '/image/register' or whatever folder I want to (existing one or not), and so on

I hope that helps someone, with same issues!

Upload file with AJAX & PHP - $_FILES array is empty

Your AJAX logic is fine. The issue is because you're using a very, very outdated version of jQuery, and there have been many tweaks to the AJAX logic over the years of development - especially since the rise in support for FormData and sending binary data via AJAX.

You should upgrade jQuery to at least 1.12, ideally 3.2 if you don't need legacy IE support.

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.



Related Topics



Leave a reply



Submit