-1

can anyone help me...my script function automatically updates what's inside the output of my textboxes from the database if I change the values in the table in the database without refreshing the page or clicking the button again to execute the script.

After a seconds later my page is lagy. I can't move my mouse freely. Is there any way how to automatically update data in my textboxes using javascript if I change the values in my table in my database?

current script:

$(document).ready(function(){
    var timer ;
    $('#send_search_form').click(function(event){
        event.preventDefault();
        $(".search_form_input").val('');
        $(".empty_batchcode").html("Doesn't exist!");
        clearInterval(timer);
        updateTextboxes();
    });

    function updateTextboxes(){
        $.ajax({
        url:"search.php",
        type:"GET",
        data: { term : $('#query').val() },
        dataType:"JSON",
        success: function(result) {

            var ii = 1;
            for (var i = 0; i < result.length; i++) { 
                $('#funiq_id').html(result[i].value).show();
                $('#t_region').val(result[i].region).show();
                $('#t_town').val(result[i].town).show();
                $('#t_uniq_id').val(result[i].uniq_id).show();
                $('#t_position').val(result[i].position).show();
                $('#t_salary_grade').val(result[i].salary_grade).show();
                $('#t_salary').val(result[i].salary).show();
                $('#id'+ii+'').val(result[i].atid).show();
                $('#aic'+ii+'').val(result[i].atic).show();
                $('#name'+ii+'').val(result[i].atname).show();
                $('#other_qual'+ii+'').val(result[i].other_sum).show();
                $('#interview'+ii+'').val(result[i].interview_sum).show();
                ii++;
            }

            if(timer == 1){ // if timer has been cleared
                timer = setInterval(updateTextboxes,1000); // <-- change 1000 to the value you want
            }
        }


        });

        timer = setInterval(updateTextboxes,1000);
    }
});      

search.php code:

<?php

if (isset($_GET['term'])) {

    $q = $_GET['term'];
    mysql_connect("localhost", "root", "");
    mysql_select_db("klayton");
    $query = mysql_query
("
SELECT DISTINCT 
ROUND((SELECT SUM(t2.inttotal)
 FROM app_interview2 AS t2 
 WHERE t2.atic = t.atic)/7,1)
 AS interview_sum,

ROUND((SELECT SUM(o2.ototal)
 FROM other_app2 AS o2 
 WHERE o2.oaic = t.atic)/7,1)
 AS other_sum,

atid,
atic,
atname,
region,
town,
uniq_id,
position,
salary_grade,
salary
FROM app_interview2 AS t
WHERE uniq_id = '$q'
GROUP BY t.atname HAVING COUNT(DISTINCT t.atic) ");

    $data = array();

    while ($row = mysql_fetch_array($query)) {
        $data[] = array(
            'value' => $row['uniq_id'],
            'atid' => $row['atid'],
            'atic' => $row['atic'],
            'region' => $row['region'],
            'town' => $row['town'],
            'uniq_id' => $row['uniq_id'],
            'position' => $row['position'],
            'salary_grade' => $row['salary_grade'],
            'salary' => $row['salary'],
            'atname' => $row['atname'],
            'other_sum' => $row['other_sum'],
            'interview_sum' => $row['interview_sum']
        );
    }

    header('Content-type: application/json');
    echo json_encode($data);

}

?>
user3311499
  • 69
  • 1
  • 1
  • 11
  • I have changed your question's php to a much easier version. You will have to change your query to only select the info if a change has occured. Then: `json_encode('changesOccured'=>, mysql_num_rows($query)!==0, 'info'=>$data);` – Martijn Feb 21 '14 at 10:22
  • And change the front from `result[i].value` to `result.items[i].value`. And now I've helped you enough :) Good luck – Martijn Feb 21 '14 at 10:23
  • @Martijn dude its better to change ur answer than changing my post =.= – user3311499 Feb 21 '14 at 11:08
  • @Martijn its annoying – user3311499 Feb 21 '14 at 11:12

2 Answers2

2

You are setting more and more setIntervals inside setIntervals and never clearing them. Remember, each setInterval call results in function running multiple times, once every N milliseconds. As the time passes, the amount of running code increases exponentially, which causes lag.

Consider using setTimeout instead. Also, setTimeout or setInterval? might be a good read.

The documentation on the above methods: https://developer.mozilla.org/en/docs/Web/API/window.setTimeout https://developer.mozilla.org/en/docs/Web/API/window.setInterval

Community
  • 1
  • 1
Oleg
  • 9,341
  • 2
  • 43
  • 58
2

Two things I have noticed. The first is the setInterval(). Every loop-illiteration it starts another timer. 1sec = 1 interval, 2sec=2, 3sec=4(!), 4sec=8(!!). So after a few seconds, your browser's going crazy. Use setTimeout() instead :)

Number two is saving the DOMreference. Every illiteration you select the id's and set a new value. Every second jQuery finds the elements. It's better to save them first, and then use the saved reference. I've done both:

var $funiq_id         = $('#funiq_id'),
    $t_region         = $('#t_region'),
    $t_town           = $('#t_town'),
    $t_uniq_id        = $('#t_uniq_id'),
    $t_position       = $('#t_position'),
    $t_salary_grade   = $('#t_salary_grade'),
    $t_salary         = $('#t_salary');


function updateTextboxes(){
    $.ajax({
        url:"search.php",
        type:"GET",
        data: { term : $('#query').val() },
        dataType:"JSON",
        success: function(result) {
            if(result.changedOccured){ // make php send if there are changes (true/false)
                var ii = 1;
                var resultLength = result.length;// Out of the loop will improve a tiny bit
                for (var i = 0; i < resultLength; i++) { 
                    $funiq_id.html(result[i].value).show(); // reference
                    $t_region.val(result[i].region).show(); // reference
                    $t_town.val(result[i].town).show(); // reference
                    $t_uniq_id.val(result[i].uniq_id).show(); // reference
                    $t_position.val(result[i].position).show(); // reference
                    $t_salary_grade.val(result[i].salary_grade).show(); // reference
                    $t_salary.val(result[i].salary).show(); // reference
                    $('#id'+ii+'').val(result[i].atid).show();
                    $('#aic'+ii+'').val(result[i].atic).show();
                    $('#name'+ii+'').val(result[i].atname).show();
                    $('#other_qual'+ii+'').val(result[i].other_sum).show();
                    $('#interview'+ii+'').val(result[i].interview_sum).show();
                    ii++;
                }
            }
        }
    }


    if(timer == 1){ // if timer has been cleared
        timer = setTimeOut(updateTextboxes,1000); // <-- change 1000 to the value you want
    }
}

Small note: Saving the DOM references into variables need to happen at the bottom of the page, or on a $(document).ready(). The elements have to exists before you can select them


For better performance, make php send wether or not something has changed. If something has, do the code you have now. If no changes, DONT UPDATE THE ELEMENTS. It's a waste of power to change something from 'abc' to 'abc'.

Martijn
  • 15,791
  • 4
  • 36
  • 68
  • does this code can automacialy update whats inside my textbox if i change the value in my database? – user3311499 Feb 21 '14 at 09:03
  • This works exactly the same as your code, but without the `setInterval()`-problem, and more efficient. – Martijn Feb 21 '14 at 09:11
  • On a sidenote: I dont think you need to update this info every seconds. Once per 10seconds should probally be more then enough (allthough I dont know the exact situation, but once per sec per user gets heavy fast) – Martijn Feb 21 '14 at 09:12
  • @user3311499 still the same its starts to lagg if i change the values in database. – user3311499 Feb 21 '14 at 09:21
  • If it lags only after it changes values, something else is wrong. Also, im going to add a small piece of info to my post, important to read – Martijn Feb 21 '14 at 09:24
  • the lagging issue is my problem in my post =.= – user3311499 Feb 21 '14 at 09:30
  • Yes I know. And I gave four options to decrease the lag (significantly!). I dont know your code, apart from this snippet. Might not even be this. The 4 tips I gave should fix the lag. If not, try to be more exact. You could remove the timeoutfunction and see if it keeps lagging. If so, it's not the interval. If not, it's the interval. – Martijn Feb 21 '14 at 09:39
  • make php send wether or not something has changed. If something has, do the code you have now. If no changes, DONT UPDATE THE ELEMENTS. – user3311499 Feb 21 '14 at 09:46
  • yea...but im asking how to do it? cause im still new a newbie – user3311499 Feb 21 '14 at 09:52
  • With my answer you should be able to do it. Im going to give you one tip: `array('changedOccured'=>true, 'items'=>$yourItems)`. – Martijn Feb 21 '14 at 09:56