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.
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:
- 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
- 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.
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);
}
});
});
Uploading both data and files in one form using Ajax?
The problem I had was using the wrong jQuery identifier.
You can upload data and files with one form using ajax.
PHP + HTML
<?php
print_r($_POST);
print_r($_FILES);
?>
<form id="data" method="post" enctype="multipart/form-data">
<input type="text" name="first" value="Bob" />
<input type="text" name="middle" value="James" />
<input type="text" name="last" value="Smith" />
<input name="image" type="file" />
<button>Submit</button>
</form>
jQuery + Ajax
$("form#data").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
});
Short Version
$("form#data").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.post($(this).attr("action"), formData, function(data) {
alert(data);
});
});
jQuery AJAX file upload - getting the actual file from input
Since I'm not sure what you want to do with the data on the server side and how the server's response should be, I used the standard example for uploading files.
@app.route('/upload-csv', methods=['POST'])
def upload_csv():
if 'csvfile' in request.files:
file = request.files['csvfile']
if file.filename == '':
return '', 400
dest = os.path.join(
current_app.instance_path,
current_app.config.get('UPLOAD_FOLDER', 'files'),
secure_filename(file.filename)
)
file.save(dest)
return '', 201
return '', 400
To transfer the data of the form via Ajax you can use an object of the type FormData.
The data is sent with the POST method of a form as "multipart/form-data".
There are many functions within jquery that enable the sending and querying of data. The $.ajax(...)
variant is the most versatile.
<form name="csvimportdataform" id="csvimportdataform">
<input
type="file"
name="csvfile"
id="csvfile"
class="form-control-file"
/>
<button
type="submit"
name="importdata"
id="importdata"
class="btn btn-info"
>Proceed</button>
</form>
<script type="text/javascript">
$("form[name='csvimportdataform']").submit(function (event) {
event.preventDefault();
const formData = new FormData($(this)[0]);
$.ajax({
type: 'POST',
url: '/upload-csv',
data: formData,
contentType: false,
cache: false,
processData: false,
success: function(data) {
console.log("success");
}
});
});
</script>
WordPress ajax file upload with jQuery
If I try to pass the data like this (with processData: false):
data: {
action: 'cas_contact_form',
data: data, }, admin-ajax.php still dies with a 0.
Well you moved the rest of the data “down one level” now, by introducing another data
key inside the data object. But the receiving end likely expects the data fields and the action key on the same level.
But you can append this additional parameter to the FormData object the same way you already added the input fields:
data.append('action', 'cas_contact_form');
https://developer.mozilla.org/en-US/docs/Web/API/FormData/append
Related Topics
Adding Additional Data to Select Options Using Jquery
Dynamically Loading CSS Stylesheet Doesn't Work on Ie
Jquery Event Won't Fire After Ajax Call
Get Iframe'S Document, from JavaScript in Main Document
How to Automatically Reload a Web Page At a Certain Time
How to Get the Background Color of an HTML Element
How to Open a Link in New Tab (And Not New Window)
Does Schema.Org Markup Work If Markup Is Dynamically Built With JavaScript
How to Refer to JavaScript Variables Across Webpages in a Browser Session
Html5 Dragleave Fired When Hovering a Child Element
Select All Elements With a "Data-Xxx" Attribute Without Using Jquery
Var Functionname = Function() {} VS Function Functionname() {}
"Thinking in Angularjs" If I Have a Jquery Background
Use a Content Script to Access the Page Context Variables and Functions
How to Redirect to Another Webpage
How to Replace All Occurrences of a String in JavaScript