Ajax call every minute using jQuery

As of these days most social networking sites are using this event to load most recent posts every second without refreshing page, stream and tweets like Facebook, Google+ and Twitter, it loads in the top part of the page. they are using latest technology like node.js and many more to reduce server load. you can also do same using a AJAX for your own purpose.

You may also like How to Interval Timer Countdown using setTimeout() and How to get Page Loading Time using PHP.

JQuery Code

<script type="text/javascript">
    var i = 60;
    var myVar;
    function onTimer() {
        $('#mycounter').html(i);
        $('#timer_count').val(i);
        i--;
        if (i < 0)
        {
            getQuizinformation();
        } else
        {
            myVar = setTimeout(onTimer, 1000);
        }
    }
    onTimer();

    function getQuizinformation()
    {
        var formData = new FormData();
        var contact = $('#QuestionQuiz').serializeArray();
        $.each(contact, function (key, input) {
            formData.append(input.name, input.value);
        });

        $.ajax({
            type: 'POST',
            url: "submitquiz.php",
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            dataType: 'JSON',
            success: function (data) {
                i = 60;
                clearTimeout(myVar);
                onTimer();
                if (data.studentflag == 1)
                {
                    alert(data.message);
                }
            }
        });
    }
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *