Syncing LocalStorage and SQL Database – Implementation Guide

javascriptPHPsql

I have made a simple web app, which runs completely offline – all data is saved in HTML5's localStorage. Now, I want the data to get synced with the server, so that the user is able to use the app on multiple devices at a time.

What I have done so far is:

  1. For each operation the user performs, a log entry is added.
  2. When the user is online, all logs are transferred from localStorage to PHP through AJAX.
  3. Corresponding changes are made in the SQL Database.
  4. All logs are deleted from the localStorage.

So, all the localStorage data is getting "backed up" on the server properly.

Anyhow, changes made from one device is not being reflected to the other device and vice-versa, to do this, we would have to get some data from SQL to the localStorage.

Now, my question is as to what will be the appropriate and best way to do this?

After the four steps above, do I

  1. Clear all localStorage data and save the SQL data into localStorage.
  2. Keep a log of changes made in the database, and do them on the localStorage.
  3. Any other approach.

Also, what about timestamps? What if there are conflicts?

Best Answer

It will depend on who is considered the "master" in your application, the client device or the server? If it's the client, you'll want to do a combination of #1 and #2: Push up any writes to the server, then pull down any changes made on the server side. If the server is master, do the opposite.

As for conflicts, you might want to look at how CouchDB handles that. It keeps both copies and marks them as conflicted for the application level to sort out. How you handle them is pretty highly dependent on what you're storing and what your business rules are.

Related Topic