// add jquery
// <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
$(document).ready(function() {
$("#form").on('submit', (function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr('action'),
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(response) {
$("#form").trigger("reset"); // to reset form input fields
},
error: function(e) {
console.log(e);
}
});
}));
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Uploads With AJAX</title>
</head>
<body>
<form id="file-form" action="fileUpload.php" method="post" enctype="multipart/form-data">
Upload a File:
<input type="file" id="myfile" name="myfile">
<input type="submit" id="submit" name="submit" value="Upload File Now" >
</form>
<p id="status"></p>
<script type="text/javascript" src="fileUpload.js"></script>
</body>
</html>
Code language: HTML, XML (xml)
$(function() {
// Configure Cloudinary
// with the credentials on
// your Cloudinary dashboard
$.cloudinary.config({ cloud_name: 'YOUR_CLOUD_NAME', api_key: 'YOUR_API_KEY'});
// Upload button
var uploadButton = $('#submit');
// Upload-button event
uploadButton.on('click', function(e){
// Initiate upload
cloudinary.openUploadWidget({ cloud_name: 'YOUR_CLOUD_NAME', upload_preset: 'YOUR_UPLOAD_PRESET', tags: ['cgal']},
function(error, result) {
if(error) console.log(error);
// If NO error, log image data to console
var id = result[0].public_id;
console.log(processImage(id));
});
});
})
function processImage(id) {
var options = {
client_hints: true,
};
return '<img src="'+ $.cloudinary.url(id, options) +'" style="width: 100%; height: auto"/>';
}
Code language: JavaScript (javascript)