Reputation: 8492
I have a website in which changes are very constant on the user side. So to prevent from submitting an ajax request for each user every 3-6 seconds, I want to wait for the user to finish the actions and then submit all to the server.
So, instead of submitting many very small ajax requests, I want to hold it and submit all at once, when the user is inactive (not changing anything) for 1 minute or so. (a bit like an autosave function)
The problem is, since the user can update different parts of the application I need to update different rows in one call, so how would I do this?
Since the POST variable needs an identifier, my first idea is to submit one array of id's and another array of data. Then on the backend rebuild the arrays, iterate, and saving data accordingly. But something tells me it's not the optimal approach, could you guys give me some tips on how to go about this?
Upvotes: 1
Views: 1252
Reputation: 350270
You could use setInterval
in combination with $.ajax
, like this:
function saveData() {
// Gather all the data you might want to post, in one object.
// This should happen dynamically, you add to the object as things
// are entered and need to be sent to the server.
// Some example data:
data = {
name: $('#name').val(),
age: $('#age').val(),
occupation: $('#occupation').val(),
list: [23, 1, 266, 34, 90],
words: ["this", "is", "some", "data"],
items: [{level: 11, width: 3}, {level: 22, width: 5}]
};
// If the data object is empty, it means there is nothing to save.
// Of course, with the above example data this condition is false:
if (!Object.keys(data).length) {
return; // nothing to do
}
// Post it
$.ajax({
url: 'script.php',
type: 'POST',
data: data,
}).done(function(response) {
alert(response);
// Mark that this data was sent, as you might not want to send it
// again the next round, unless the user changed some data.
data = {};
});
}
// Call the above function every 60 seconds.
setInterval(saveData, 60000);
The in PHP, you can access your data like this:
// Access the items passed:
$name = $_POST['name'];
foreach ($_POST["list"] as $number) {
//...
}
// ... etc
Upvotes: 1
Reputation: 1217
How about POSTing a JSON object that represents a DTO of for your page? So you'd be able to pack in all the data your backend should need for saving the state of that page in one object like:
{
'Attribute1' : 'Value1',
'Attribute2' : 'Value2',
'Attribute3' : 'Value3'
}
I'm not sure what your using to parse this on the server but almost any framework worth using can handle JSON with relative ease.
Upvotes: 0