0

I am trying to build a social network site and in order for post's to keep on updating I've set an interval time of 20 seconds so it refreshes the page and show's new comments and or post's.

My problem now is that when a user is trying to input a comment in my form, the page is running through the interval and as soon as it hit's 20 seconds the page refreshes and the text input deleted.

I want to set the interval function so that it will start counting if no one had typed anything anywhere in the page for about 10 seconds.

I can't give an input ID since the comment's are bound to post's and by that do not have a static ID for reference.

Is there a way to do what I just described?

that's the code of the page I want to stop the interval temporarily:

<?php
session_start();
if(!isset($_SESSION['login_user'])){ // check whether a session is set or not
header('Location: registrationPage.php'); // Redirecting To Registration Page
}
include 'connectDB.php';

$FN = $_SESSION['login_user'];
$result = mysqli_query($conn, "SELECT concat(U.firstName,' ',U.lastname) as fullName FROM tblUser U  where U.userName='$FN'");
while($row = mysqli_fetch_array($result)){
     $UN    = $row['fullName'];
   }



    ?>

    <!DOCTYPE html>


    <html>
      <head>
        <meta charset="utf-8">
        <meta name="description" content="Main page">
        <meta name="author" content="Sorokina E. and Menaker T.">
        <title>Main page</title>
        <script type="text/javascript" src="../js/jquery.min.js"></script>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <href='https://fonts.googleapis.com/css?family=Tangerine' rel='stylesheet' type='text/css'>
        <!-- jQuery library -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
        <!-- Latest compiled JavaScript -->
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
        <script src="../files/connection.json"  type="text/jason"></script>
        <script src="../files/positions.json"  type="text/jason"></script>
        <script src="../files/messages.json"  type="text/jason"></script>
        <link rel="stylesheet" type="text/css" href="../css/mystyle.css">
        <script src="../js/typeahead.min.js"></script>
      </head>
      <body>



            <div class="row alignT bg_color7">
                  <div class="col-sm-1">
                    <a href="mainPage.php"><img class="img-responsive" src="../images/logo.gif" alt=""></a>
                  </div>

                  <div class="col-sm-1">
                    <?php
                  if(isset($_SESSION['login_user'])){
                              echo '<span >Welcome ' . $UN. '! </span>';
                            }
                    ?>
                  </div>

                  <div class="col-sm-1">
                      <a href="mainPage.php" data-toggle="tooltip" title="Home"><span class="glyphicon glyphicon-home"></span></a>
                  </div>

                  <div class="col-sm-1">
                    <a href="profilePage.php" data-toggle="tooltip" title="My profile"><span class="glyphicon glyphicon-user"></span></a>
                  </div>

                  <div  class="col-sm-1 " data-toggle="tooltip" title="My connections" >
                    <button id="NL" class="Tbutton " type="button">
                        <span  class="glyphicon glyphicon-globe " style="vertical-align:middle; " ></span>
                    </button>
                    <div id="NC" class="notificationContainer">
                    <div id="NT" class="notificationTitle">My friends:</div>
                        <div id="NB" class="notificationsBody forConnection">
                          <?php include ('selectAllFriends.php');?></div>
                          <div id="NF" class="notificationFooter"><a href="#">See All</a></div>

                    </div>
                  </div>

                  <div class="col-sm-2 ">
                    <span > <input id="search"  name="typehead" class="typeahead" data-provide="typeahead" placeholder="Search people" ></input></span>
                  </div>

                  <div class="col-sm-1 mm">
                    <span><input type="button" onclick="location.href = 'allUsersPage.php';" class="btn btn-info" value="All people" ></span>
                  </div>
                  <div  class="col-sm-1 " data-toggle="tooltip" title="My messages" >
                    <button id="NL1" class="Tbutton " type="button">
                        <span  class="glyphicon glyphicon-envelope" style="vertical-align:middle; " ></span>
                    </button>
                    <div id="NC1" class="notificationContainer">
                    <div id="NT1" class="notificationTitle">My Messages:</div>
                        <div id="NB1" class="notificationsBody forMessages">
                          <?php include ('selectAllMessages.php');?></div>
                          <div id="NF1" class="notificationFooter"><a href="#">See All</a></div>


                    </div>
                </div>


                  <div  class="col-sm-2 " data-toggle="tooltip" title="My notifications" >
                    <button id="NL2" class="Tbutton " type="button">
                        <span  class="glyphicon glyphicon-flag" style="vertical-align:middle; " ></span>
                    </button>
                    <div id="NC2" class="notificationContainer">
                      <div id="NT2" class="notificationTitle">My Notifications:</div>
                        <div id="NB2" class="notificationsBody forNotifications"></div>
                          <div id="NF2" class="notificationFooter"><a href="#">See All</a></div>
                    </div>
                  </div>


                  <div class="col-sm-1">
                    <a href="logout.php" data-toggle="tooltip" title="Log Out"> <span class="glyphicon glyphicon-log-out"></span></a>
                  </div>
            </div>



            <div class="row">
              <p class="alignW"><input  class=" col-sm-5" type="text" name="mind" id="textField9" placeholder="Share your mind">
                <span   class=" col-sm-1"></span>  <input type="button" id = "btn_submit" class="btn btn-info col-sm-1" value="Add post" ></p>

            </div>

          <div class="row" id="middle">
              <div class="col-sm-8" id="left">
                  <?php include ('selectAllPosts.php'); ?>
              </div>

              <div class="col-sm-4" id="right">
                  <?php  include ('select5Positions.php'); ?>
              </div>
          </div>




        <!--Footer-->
        <footer class="container-fluid text-center">
          <p  class="glyphicon glyphicon-copyright-mark"> &nbsp;Created by ... </p>
        </footer>



       <script>
       $(document).ready(function(){
         var timer = null;
         function autoRefresh_div()
          {

               $('#left').load("selectAllPosts.php");// a function which will load data from other file after x seconds

           }
           $(document.body).keydown(function(event){
             clearTimeout(timer);
             timer = setTimeout(setInterval(function(){ autoRefresh_div() }, 20000), 5000);

           });



           $("#btn_submit").click(function(){
             var userName='<?php echo $FN; ?>';
             var content = $('#textField9').val();
             var postData = '&uname='+userName+'&content='+content;
           $.ajax({
             url : "insertPost.php",
             type: "POST",
             data : postData,
             success: function(data,status, xhr){
               if(data==="You have successfully posted!"){
                   $('#textField9').val('');
                 }
                 if(data==="ERROR"){
                   $('#textField9').val('');
                 }
               }
            });
    });






           $('#search').typeahead( {
            name:'typehead',
            remote: 'selectAllUsers.php?query=%QUERY'
          });
          //search for all users and go to their pages
          $('#search').on('typeahead:selected', function(evt, item){
            window.location.href = "userPage.php?fullName="+item.value;
          });




          $.getJSON("../files/notifications.json",function(result){
              $.each(result, function (index, value) {
                  $(".forNotifications").append("<div class=\"divStyle1\">" +value.Notification + "</div>");
                });
            });


      $("#NL").click(function(){
            $("#NC2").hide();
            $("#NC1").hide();
        $("#NC").fadeToggle(300);
        return false;
      });
      $("#NL1").click(function(){
        $("#NC").hide();
        $("#NC2").hide();
        $("#NC1").fadeToggle(300);
        return false;
      });

      $("#NL2").click(function(){
        $("#NC").hide();
        $("#NC1").hide();
        $("#NC2").fadeToggle(300);
        return false;
      });

      $('#myButton').click(function (){
               $(this).hide();
           }
      );

    });

        </script>
      </body>
    </html>

Thank you.

Tom

Shadow
  • 33,525
  • 10
  • 51
  • 64
Tom
  • 343
  • 3
  • 12
  • 1
    Run the interval faster, like one second, and update a counter. When the counter gets to 20, reload. Make a global "keypress" event handler, and whenever there's a keypress set the counter back to zero. – Pointy Feb 04 '17 at 15:15
  • 2
    Refreshing the page seems like a bad idea for this use case. Have you considered using Ajax to get the new posts every X seconds? It would make your requests smaller so the server has less work to do. – bassxzero Feb 04 '17 at 15:17
  • the interval is a requirment from me. – Tom Feb 04 '17 at 15:19
  • @Tom no one said to remove it – bassxzero Feb 04 '17 at 15:20
  • your idea's are nice but I am quite a novice and a bit clueless as to how to make what you said happen.. – Tom Feb 04 '17 at 15:23
  • bassxzero is right, this is an extremely poor design. Keep the interval but dont refresh the page, refresh the content in a div on the page using ajax ;) – Wesley Smith Feb 04 '17 at 15:23
  • Here is a good start http://stackoverflow.com/questions/18490026/refresh-reload-the-content-in-div-using-jquery-ajax – Wesley Smith Feb 04 '17 at 15:24
  • 1
    @Tom I also just noticed you don't have an `exit();` after your `header('Location: registrationPage.php');`. ALWAYS put and exit after a redirect using header. – bassxzero Feb 04 '17 at 15:25

1 Answers1

0

There are multiple ways you could do this either by making an AJAX Request to retrieve new data or even use Websockets (Which is the most efficient). However, the simplest approach to fixing your problem would be to create a timer via JS when the page loads.

<!-- Element -->
<input type="text" data-ui="post"/>

<!-- Script -->
<script>
$(document).ready(function(){

    var timer = null;

    function startTimer() {
        timer = setInterval(function() {
            window.location.reload();
        }, 1000);
    }

    // Stop timer by clearing with interval when
    // the user focuses on the element
    $('[data-ui]').on('focus', function() {
        clearInterval(timer);
    });

    // Start the timer once the user has blurred away from
    // the element
    $('[data-ui]').on('blur', function() {
        startTimer();
    });

    // Start the timer as the page has finished loading
    startTimer();

})
</script>

The basically stops the window location.reload timer once the user has focused an element that has a [data-ui] attribute tag attached to it. Another method would be to save your inputs content with LocalStorage and reinsert the content into the input box once the page has reloaded.

Let me know if you need a jQUERY'less version.

Win
  • 5,498
  • 2
  • 15
  • 20