Question

I posted something similar yesterday but it works but only deleted the last object in the data.

What I want to happen

This ajax upload will be handling a lot of data, so I'm using indexeddb. This will also be use on mobile phones. So I wanted it to upload one item at a time and if one item failed to have only deleted the previous items out of the data so they wouldn't need to upload everything again.

I have tried async = false, This works exactly how i want it but this freezers browser.

Current Code Tried to comment out any bits that could be confusing, currently this only deletes the last item once finished.

function uploadData(e) {

 //Get Database 
 var transaction = db.transaction(["data"], "readonly");
 var objectStore = transaction.objectStore("data");
 var cursor = objectStore.openCursor();

 //Starts Looping
 cursor.onsuccess = function(e) {
     var res = e.target.result;
     if (res) {
         if (navigator.onLine) {
             $('.popup-heading').text('Uploading...');
             var passData = {
                 client_id: res.value.client_id,
                 parent_id: res.value.parent_id,
                 storename: res.value.storename,
                 image: res.value.image,
                 key: res.key,
             };
             var jsonData = JSON.stringify(passData);
             $.ajax({
                 url: "{{ path('destination_app_ajax') }}",
                 type: "post",
                 // Works but freezes browser 
                 /*async, flase*/
                 data: {
                     "json": passData
                 },
                 success: function(JsonData) {

                     //Delete item once successfull 
                     var t = db.transaction(["data"], "readwrite");
                     var request = t.objectStore("data").delete(passData.key);
                     t.oncomplete = function(event) {
                         console.log('item deleted');
                     };
                 },
                 error: function() {
                     $('.popup-heading').text('Upload Failed!');
                 }
             });
         } else {
             $('.popup-heading').text('Please find stronger signal or wifi connection');
         }
         res.
         continue ();
     }
 }

}

Was it helpful?

Solution

It sounds like you have a scope issue with passData. Inside of your loop, but before you defined var passData = ... try wrapping the codeblock with an anonymous function:

(function() {
   /* Your code here */
}());

That should prevent passData from leaking into the global scope, which seems to be why your IDB code only works on the last loop. (passData is being redefined each time before your AJAX response is able to complete.)

Update: There is no loop, you're dealing with callbacks. What I see happening is that you're redefining your onsuccess handler on each Ajax request (and overwriting all values but the last), reusing the same transaction. Try moving this transaction code into the success callback for the AJAX request:

//Get Database 
 var transaction = db.transaction(["data"], "readonly");
 var objectStore = transaction.objectStore("data");
 var cursor = objectStore.openCursor();

That will create a closure and commit your delete transaction on each response. That means one transaction per AJAX request, and one onsuccess callback per AJAX request (with no redefining).

OTHER TIPS

The only solution I found worked with this was to send the Key via ajax to php then delete from that.

HTML

var passData = {     
                        .......
                        key: res.key,
                    };

.....

   $.ajax({
                       url: "yourscript.php",
                       type: "post",
                       data: {
                           "json": passData 
                       },

                       success: function(JsonData) {

                           jsonKey = JSON.parse(JsonData);


                           //Delete item once successfull 
                           var t = db.transaction(["data"], "readwrite");
                           var request = t.objectStore("data").delete(parseInt(jsonKey.key));
                           t.oncomplete = function(event) {
                            console.log('item deleted', jsonKey.key);
                           };



                       }

PHP

    $data = $_POST['json'];


    $returnKey =  json_encode(
                    array(
                            'key' => $data['key']
                    )
    );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top