Skip to content

Instantly share code, notes, and snippets.

@mahammad
Created July 25, 2022 19:29
Show Gist options
  • Save mahammad/03379a03644d6abc6f8f7feb302d2dac to your computer and use it in GitHub Desktop.
Save mahammad/03379a03644d6abc6f8f7feb302d2dac to your computer and use it in GitHub Desktop.
How to upload ajax in Laravel
<script type="text/javascript">
$(document).ready(function(e) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#image').change(function() {
let reader = new FileReader();
reader.onload = (e) => {
$('#preview-image-before-upload').attr('src', e.target.result);
}
reader.readAsDataURL(this.files[0]);
});
$('#image-upload').submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type: 'POST',
url: "{{ url('upload') }}",
data: formData,
cache: false,
contentType: false,
processData: false,
success: (data) => {
this.reset();
alert('Image has been uploaded using jQuery ajax successfully');
},
error: function(data) {
console.log(data);
}
});
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment