1

I would like to implement the AutoSave functionality for my site.
I mean, I would want all the fields which are edited by the user throughout the site should be autosaved without any button clicks. So user can keep editing.

[site designed with: CodeIgniter and JQuery].

This feature, I am implementing as follows.

1.Created a Queue data structure in javascript and to which I am pushing all the changes made by user. So this is like an object holding all the user changes.

2.Then wrote a function to save the contents of this Queue to the database.

function start(){
 var changeData = dq.get();  //getting the data from Queue

  while(changeData !== undefined){
    $.ajax({
      type: 'POST',
      url: '/ci/ajax/insert/',
      data: {changeData},
      success: function(data, status, xml){
        alert('succefully inserted data -- '+data);
      }
    });
    changeData = dq.get();
  }

  setTimeout(function(){ start(); }, 5000);
};

start();

Here I am setting the interval as 5 sec.

The problem is that, I am making two or more changes within 5 sec, but, only the first change is getting updated. But I am getting the alert 2 or more times depending on changes I made.

Where I am going wrong?

Also suggest me the better ways of implementing the autosave feature.

Thanks!

Madhu Dollu
  • 434
  • 3
  • 6
  • 20
  • I believe that setTimeout() should be in callback - otherwise you could be calling one more async method before first one returns data. – OzrenTkalcecKrznaric Jun 30 '13 at 16:24
  • Here is the one of the solution I could find. http://stackoverflow.com/a/1060784/1841369 – Madhu Dollu Jul 07 '13 at 09:16
  • You are trying to handle concurrent ajax requests, while you should be preventing that. Easiest way to do it is send a request, wait for response, and when you get response schedule next request. Otherwise overlapping of requests may occur and you need queueing or some synchronization method to resolve that. – OzrenTkalcecKrznaric Jul 07 '13 at 10:34

1 Answers1

1

You should define the setTimeout in the success method it would be great because when your first request will be completed then generate the second request otherwise if you will not wait for the server response and sending the no. of requests it be increase the load on your server

function start(){
 var changeData = dq.get();  //getting the data from Queue

  while(changeData !== undefined){
    $.ajax({
      type: 'POST',
      url: '/ci/ajax/insert/',
      data: {changeData},
      success: function(data, status, xml){
  setTimeout(function(){ start(); }, 5000);// defines when first request is accomplished
        alert('succefully inserted data -- '+data);
      }
    });
    changeData = dq.get();
  }


};

start();
M Khalid Junaid
  • 63,861
  • 10
  • 90
  • 118