0

I have the following code to save multiple objects to my parse.com table. I have debugged my code and everything should be working properly. This code is saving n objects all with the same information as the last object. The images are being save correctly.

Images and captions are just two arrays with the same length.

I am thinking the problem is because I have to wait for the callback from the previous save or the php code to finish. I am changing the image base on the fly as well.

I saw very similar problems posted but I tried the solution and it did not work: Parse.com save object once and here only first object getting saved in javascript for loop

Any idea what I am doing wrong here?

for(i = 0; i < images.length; i++){

            var caption = convert(captions[i]);

            //change image to base64
            $.post("base64.php", {base64: images[i]}, function(data){

                var image = data;

                var post = new Post();

                post.set("post", id);
                post.set("number", i + 1);
                post.set("by", by);
                post.set("title", title);
                post.set("description", description);
                post.set("caption", caption);
                post.set("views", 0);
                post.set("type", "image");

                var parseImage = new Parse.File("image.png", {base64: image});
                post.set("image", parseImage);

                post.save(null, {
                    success: function(messages) {

                    },error: function(messages, error) {

                    }
                });


            });
        }
Community
  • 1
  • 1
Max Pain
  • 1,217
  • 7
  • 19
  • 33

1 Answers1

3

Batch them up:

var posts = [];
for(i = 0; i < images.length; i++){
    var caption = convert(captions[i]);

    //change image to base64
    $.post("base64.php", {base64: images[i]}, function(data){

        var image = data;

        var post = new Post();

        post.set("post", id);
        post.set("number", i + 1);
        post.set("by", by);
        post.set("title", title);
        post.set("description", description);
        post.set("caption", caption);
        post.set("views", 0);
        post.set("type", "image");

        var parseImage = new Parse.File("image.png", {base64: image});
        post.set("image", parseImage);

        // push to array for batch saving
        posts.push(post);
    });
}
Parse.Object.saveAll(posts)
.then(function() {
    console.log('all saved');
}, function(error) {
    console.error(error);
});
Timothy Walters
  • 16,866
  • 2
  • 41
  • 49