Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

209
Visualizações
How to insert Data into IndexedDB within an AJAX response?

lets say I have a the following code that creates the database OUTSIDE of my Ajax call:

// This works on all devices/browsers, and uses IndexedDBShim as a final fallback 
var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;

// Open (or create) the database
var open = indexedDB.open("MyDatabase", 1);

// Create the schema
open.onupgradeneeded = function() {
    var db = open.result;
    var store = db.createObjectStore("MyObjectStore", {keyPath: "id"});
    var index = store.createIndex("NameIndex", ["name.last", "name.first"]);
};

and then I want to store some data into this database within my Ajax call like so:

 $.ajax({
        url: "https://sometise.com,
        headers: {
            "Authorization": "TOKEN"
        },
        type: "GET",
        success: function (data) {

$(data).each(function (index, el) {

var myArray = {
            ID: el.id,
            Content: data
          }
///ADDING THE ABOVE ARRAY TO THE DATABASE LIKE SO HERE


open.onsuccess = function() {
    // Start a new transaction
    var db = open.result;
    var tx = db.transaction("MyObjectStore", "readwrite");
    var store = tx.objectStore("MyObjectStore");
    var index = store.index("NameIndex");

    // Add some data
    store.put({id: el.id, name: {first: myArray, last: "Doe"}});
    

    // Close the db when the transaction is done
    tx.oncomplete = function() {
        db.close();
    };
}


});


}

  });

but the above code doesn't do anything!

any pointers would be appreciated.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The open.onsuccess event gets fired only once. This should happen as soon as the DB is ready, which likely happens before the ajax call receives a response from the server. So the event gets fired before you attach the listener, meaning it never gets handled.

You have to store the onsuccess result outside of the ajax callback. Or you can use a promisified version of IDB like https://github.com/jakearchibald/idb and await it inside the ajax callback.

Edit: An example using promises, await and the idb library I mentioned above:

const db = openDB(…);

async function doPost() {
  const response = fetch('https://somesite.com')
  
  const tx = (await db).transaction("MyObjectStore", "readwrite");
  const store = tx.objectStore("MyObjectStore");
  const index = store.index("NameIndex");

  // Add some data
  await store.put(await response);
  await tx.done;
}

Should work like this, but I would recommend reading up about promises in general. Also consider using modern language features like const/let and fetch, they usually make live much easier.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda