After many ajax request the page is getting slower and can not be used

555 views Asked by At

I use this ajax script :

$.ajaxSetup ({
        // Disable caching of AJAX responses
        cache: false
    });

    function getRandomInt() {
      return Math.floor(Math.random() * Math.pow(10,6));
}

    $(document).ready(function(){

        $('#edit_in_buy_usd').click(function(){
            $.post("edit_id.php?rnd=" +getRandomInt(), 

                   {edit_id: $('#edit_in_buy_usd').val()}, 

                   function(data){

                  $('#id').html(data);

                }
            );

        });

});

after pressing the button, I create a variable that goes to edit_id.php ,performs certain processes and returns the result to the same Div with id="id". Everything works perfectly but ... after pressing the button about 30-40 times the page starts to work super slow. I read a lot of topics I added things but I do not have much experience in Ajax tehnique.... and can not handle it alone ... If you help me I will be very grateful to you .. thank you in advance!

2

There are 2 answers

3
Root On

Instead of retrieve all of table data from server script :

$('#id').html(data);

try to append just the new row data to table like this :

$("#id").append(data);

Server side script must return a value like this : <tr><td>test</td><td>test</td></tr>

1
Noé On

Well I know that this question was made a long time ago, but in case someone from now on is looking for some kind of answer. I just wanted to add that I read something on this site: https://www.phpclasses.org/blog/post/277-Fix-the-AJAX-Requests-that-Make-PHP-Take-Too-Long-to-Respond.html So that basically what it teaches is a way to optimize your web site in case you using PHP

In the case you're using PHP sessions, you have to use the function session_start(), so that when you call it, PHP loads the session file and serialize it to access the variables through $_SESSION, but it keeps the file blocked by the script.

So what the site suggests is that after you're done with your validations, use the session_write_close which will release the file.

The answer of why you should do that is because when you make simultaneous AJAX requests and you're using sessions to validate or whatever, the server will block the file until the script ends and then the next request will be executed.

So I would suggest to validate and release and in case that they're some data the you would like to use later, consider saving the value in a normal PHP variable rather than using the $_SESSION super array everytime.

This is just something that might increase the speed of your server responses and it's not intended to be the absolute answer to the asked question, I really hope it helps and that you find the best programming practices to speed up your site!