I have a button on my front end that allows the user to update their profile photo (using Cloudinary api), and I basically call my nodejs post request and pass it the users data so it can query the db and update the profile photo url. works great, but it doesn't redirect / render the page after it calls that function.
here's my front end (with Cloudinary and js)
<input type="hidden" name="" id="employee_num" value="<%= data[i].EMPLOYEE_NUM %>">
<script src="https://widget.cloudinary.com/v2.0/global/all.js" type="text/javascript"></script>
<script type="text/javascript">
var myWidget = cloudinary.createUploadWidget({
cloudName: 'xxx',
uploadPreset: 'xxx'}, (error, result) => {
if (!error && result && result.event === "success") {
console.log('Done! Here is the image info: ', result.info);
console.log(result.info.secure_url)
var result_url = result.info.secure_url;
console.log("result url is " + result_url)
document.getElementById("url").value = result_url;
var employee_num = document.getElementById('employee_num').value;
fetch('/changeProfileImage', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
result_url,
employee_num
})
})
}
}
)
document.getElementById("upload_widget").addEventListener("click", function(){
myWidget.open();
}, false);
</script>
now below is my nodejs function for the post request /changeProfileImage
app.post('/changeProfileImage', (req, res) => {
if (req.session.loggedin) {
var employee_num = req.body.employee_num;
var url = req.body.result_url;
console.log("e " + employee_num)
console.log("u " + url)
var changeProfileImage = "update EMPLOYEES set (PROFILE_IMAGE)= '" + url + "' where EMPLOYEE_NUM = '" + employee_num + "'";
ibmdb.open(ibmdbconnMaster, function (err, conn) {
if (err) return console.log(err);
conn.query(changeProfileImage, function (err, rows) {
if (err) {
console.log(err);
}
res.redirect('/account');
conn.close(function () {
});
})
})
} else {
res.render('login.ejs')
}
})
forgive me for the messy code, but above is everything that is needed. it basically says in my console that it updated everything, and successfully went through, which is true, but it never refreshes. any ideas?
The thing is you are making a AJAX call so the js is making the HTTP request to the server and it is not the whole page, so you need yo do it manually in the callback of the fetch:
fetch('/changeProfileImage', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
result_url,
employee_num
})
}).then(response => {
if (response.redirected) {
window.location.href = response.url;
})
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