简体   繁体   中英

Delays/inconsistencies in AJAX refresh

I've been working on a web app that allows users to submit content and have that content, and today I've been seeing some unexpected results without making any significant changes.

The basic functionality of the app is that the user submits some POST data from a form on a web page index.php , whereupon a PHP script submit.php is run to add the data to a table in a database. Meanwhile, a Jquery function on index.php is refreshing the contents of a div with rows selected from the table by means of a script load.php , and the function is called once per second.

The problem is that today, suddenly, I'm seeing long (10-20 minute) delays between when the data is added to the table and when it shows up in the Jquery-refreshed div. Moreover, the div flickers back and forth between its existing contents and the new data set with the added values, as if it were alternating between the realtime results of load.php and a previous call to the same script.

I've checked the MySQL database before and after submit.php is called and I've verified that the data is being added instantaneously once it's submitted, so the problem has something to do with how the load.php script is called from Jquery.

This just started today. Strangely, I've been seeing this same behavior with another AJAX app that I built earlier to test the same I/O mechanism, and I haven't touched that app's code in over a week. My system administrator says there haven't been any changes to the server that would account for this.

I've posted all the code to provide all necessary information, but I think the problem is either in load.php or the javascript updateMyContent() in index.php .

index.php

<script language="JavaScript">

setInterval("updateMyContent();",1000);
$(function(){
    updateMyContent=function(){
        $('#refreshData').load("./module/load.php").fadeIn("slow");
    }
});

</script>

<script language="JavaScript">

$(document).ready(function(){
    $('#submitForm').on('submit',function(e){
        $.ajax({
            url:'./module/submit.php',
            data:$('#submitForm').serialize(),
            type:'POST',
            success:function(data){
                console.log(data);
                $("#success").show().fadeOut(5000);
                $('#textID').val('');
            },
            error:function(data){
                $("#error").show().fadeOut(5000);
            }
        });

        e.preventDefault();
    });
});

</script>



<div style="float: right;
        top: 0;
        " id="submitDiv">
    <form id="submitForm" action="" method="post">
        <textarea id="textID" type="text" name="content" rows=5></textarea>
        <input type="submit" value="send" name="submit"/>
    </form>
    <br>
    <span id="error" style="display: none; color:#F00">error</span>
    <span id="success" style="display:none; color:#0C0">success</span>
</div>
<div style="float: center;" id="refreshData"></div>

submit.php

<?php
    if(isset($_POST['content']))
    {
        $content=$_POST['content'];
        $dsn="mysql:host=someserver.net;dbname=thisdb;charset=utf8";
        $db=new PDO($dsn,'thisdb','password');
        $insertSQL="insert into submission (content) values (?)";
        $stmt=$db->prepare($insertSQL);
        $stmt->execute(array($content));
    }
    else
    {
        echo "FAIL!";
    }
?>

load.php

<?php
    try
    {
        $dsn="mysql:host=someserver.net;dbname=thisdb;charset=utf8";
        $db=new PDO($dsn,'thisdb','password');
        $PDOsql="select * from submission order by id desc";
        $stmt=$db->query($PDOsql);
        foreach($stmt->fetchAll(PDO::FETCH_ASSOC) as $resultRow)
        {
            printf("%s<br>",$resultRow["ID"]);
            printf("%s<br>",htmlspecialchars($resultRow["content"]));
        $stmt->closeCursor();
        }
    }
    catch(PDOException $ex)
    {
        echo "an error occurred!  ".$ex->getMessage();
    }
?>

The issue with it taking so long to return the Ajax response is probably that the table submissions has grown. Rather than each second loading all the submissions, append only new submissions to the div. Ie keep track of the last id received and use this in the query so the where clause is limited.

Moreover, the div flickers back and forth between its existing contents and the new data set with the added values, as if it were alternating between the realtime results of load.php and a previous call to the same script.

Ajax response can be cached by the browser just like anything else. To prevent that, you can:

  1. Put no-cache headers in the page that processes the request to prevent browser caching of the Ajax responses. IE is particularly stubborn and will require the most forceful headers.

  2. Add a parameter to your Ajax request that is a random number, to make every request unique.

  3. Tell JQuery to prevent caching (it just does #2 for you). Use $.ajaxSetup ({ cache: false }); or add the cache: false, attribute to each call to $.ajax

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM