Henrique Van Klaveren Henrique Van Klaveren - 8 months ago 36
jQuery Question

How update DATA on realtime without click or submit

I need update data in table without a action send click or submit. For example, when i change input value, i would like save in real time this changes in the database.

My question is, how i can compare if have changes in the form?
I read this post, Submitting data without clicking a submit button, but here, the function is executed every 5s, and i need save just only have changes.


<form id="formos" method="">
Status:<input type="text" class="form-control uppercase" form="">


$(window).bind('beforeunload', function(e){
if($('#formos').serialize()!=$('#formos').data('serialize'))return true;
else e=null; // i.e; if form state change show box not.


The way I do it is like this. I send the data via ajax on keystroke. But I do it with a timeout of 300ms so that it won't send on each keystroke only when they stopped typing.

I then check on the server side if there was a change, if not I do nothing, if there was already an entry I update, if there was no entry I insert. Simple.

If you are having trouble with the code I can provide some.


<input type="text" id="test_1" />
<input type="text" id="test_2" />


        var elem = $(this);
        $(this).data('timer', setTimeout(function(){
            sendValue(elem.attr('id'), elem.val());
        }, 300));
        sendValue($(this).attr('id'), $(this).val());

function sendValue(key, value) {
    $.post('path/to/script.php', {key: key, value: value}, function(data, result){
        if(result == 'success') {
            console.log('Data was sent');
        } else {
            console.log('AJAX post failed');


$key = $_POST['key']; //just remember never to just receive input from a user, first check if it is something valid and not something trying to hack you
$value = $_POST['value'];
//then check if there is a difference of value to what you had
//insert or update in your db accordingly
die(); //die if you are using a controller within a framework, if you do not it will send back all the other stuff with it

I hope this helps.