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()" />
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With