Using parse.com's javascript API, I would like to get a variable number or images from img
tags on a page and save those images in the currently logged in user's user object.
To my knowledge, parse cannot store image files directly from a url so I am using ajax to send each url to a php
page that converts it and returns a base64 encoded string
Of course, left unchecked, the code would continue to run and save the user object before the php
page returns the encoded images.
As a quick and dirty solution I set async: false
which does work but of course give the warning: synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.
How can I re-write the below to use promises
instead of async: false
?
Or, should I gather up all of the image urls, send them in one ajax call, encode each, send them all back, and move the save user code into the success function of the ajax call?
function accountCreation(){
var user = Parse.User.current(); // get the currently logged in user object
// loop through each image element
$('.images').each(function(index, element) {
// first we'll need to get the image source
var src = $(element).attr('src');
// alone, the source is just a url and not of much use to us
// we'll need to take the source and create a base64 encoded string from it
// we'll use an ajax call to a small php script (shown below) to do this
// it might be better to gather up each src url and send them all in one ajax call??
var encodedImg;
try {
$.ajax({
type: "POST",
url: "encodeImgToBase64.php", // you may need to adjust this path depending on where you store the file in relation to this file
data: 'url='+src,
success: function(data){
encodedImg = data; // encodedImg is now a base64 encoded string
// if I did send all the image urls at once and return all the encoded strings in one response, I guess I could just move the rest of the below code into this success function and be done with it
},
async: false
// note the use of `async: false` here
// this works but gives the warning:
// synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.
// I know I should be using a promise here but Im not sure how to incorporate it
});
var file = new Parse.File("photo.jpg", { base64: encodedImg }); // this part actually saves the image file to parse
user.set("image"+index,file); // set this image to the corosponding column on our object
} catch (e) {
console.log('failed to create file, src= '+src+', encoded img='+encodedImg)
}
});
// save the user object
user.save(null,{
success: function(user) {
// do success stuff...
},
error: function(user, error) {
// do fail stuff...
}
});
}
Here is the php
code from encodeImgToBase64.php
<?php
if (isset($_POST['url']) ){
echo base64_encode(file_get_contents($_POST['url']));
}else{
echo 'Error: No image to encode';
}
?>