This question already has an answer here:
Need a big favor! I'm trying to send uploaded file using JavaScript & Ajax, however not getting any success.
I want that when I upload the file, it will call the function myFunction()
, and send the file to the PHP path(ajax.php) I've set.
Below is the code I've so far.
<script>
function myFunction() {
var x = document.getElementById("up");
$.ajax({
type: 'GET',
url: 'ajax.php',
data: {},
beforeSend: function() {},
success: function(data) {
alert(data);
}
});
}
</script>
<input type="file" name="images" id="up" onchange="myFunction()" />
</div>
Uploading files with Jquery and Ajax is a little tricky, but it is something that is already fairly well documented. A quick google search returns a fairly good example of this https://abandon.ie/notebook/simple-file-uploads-using-jquery-ajax
The most important part is obtaining the formdata. Javascript can grab the file elements and build a FormData
object from it. From the example above
$('input[type=file]').on('change', prepareUpload);
function prepareUpload(event)
{
files = event.target.files;
}
You can then build the form object and use that as the data component of your ajax request.
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
});
When you upload a field with ajax, you have to create a formData
object, then you can change the attribute data
: Try this:
<script>
function myFunction() {
var form = $('form')[0];
var formData = new FormData(form);
$.ajax({
type: 'POST',
url: 'ajax.php',
data: formData,
contentType: false,
processData: false,
success: function(data) {
alert(data);
}
});
}
</script>
<form method="POST">
<input type="file" name="images" id="up" onchange="myFunction()" />
</form>
If you only have one image and are using your input in a form, you can get the object by using FormData().And sending it when you click on a submit button. When passing it to AJAX use the variable (formdata) to tell AJAX what data to send. Hope this helps:
function myFunction(event){
event.preventDefault();
var formdata = new FormData();
formdata.append("images[]",images);
$.ajax({
type: 'GET',
url: 'ajax.php',
data: formdata,
beforeSend: function() {},
success: function(data) {
alert(data);
}
});
}
If you are uploading multiple images:
<form id="yourform" method="POST" enctype="multipart/form-data">
<input type="file" name="images[]" id="up" onchange="myFunction()"
multiple/>
</form>
Try this, THis is my working code.
function myFuction(){
var form = $("#formId").get(0);
e.preventDefault(); //keeps the form from behaving like a normal (non-ajax) html form
$.ajax({
url: ajax.php,
type: 'POST',
data: new FormData(form),
dataType: 'json',
mimeType: 'multipart/form-data',
processData: false,
contentType: false,
success: function (response) {
alert('success');
},
error: function (data) {
alert('error');
}
});
}
<form id="formId" method="POST">
<input type="file" name="images" id="up" onchange="myFunction()" />
</form>