2

I have following index.php file:

<html lang="en">
  <head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function(){
        var auto_refresh = setInterval(function (){
          //alert("abc");
          $('#mydiv').load('xyz.php').fadeIn("slow");
        }, 1000); 
      });
    </script>
  </head>
  <body>
    <div id="mydiv"> </div>
  </body>
</html>

In above file, I am trying to call my xyz.php file after 1 seconds. Its working fine. Following is my xyz.php file.

<?php
//echo rand();
$questions=array(
                 "Array Item 1",
                 "Array Item 2",
                 "Array Item 3");
?>

Earlier I was calling rand function, which was generating random number everytime when this file was called after every second. Now I have commented it out. My requirements have been changed. Now I want that when first time this file is called, Array Item 1 is echoed. 2nd time Array Item 2 is echoed. Similar Array Item 3 at third attempt. After this setInterval should not call this php file.

Here I need your help.

5 Answers 5

3

In JS:

var count = 0;

$(document).ready(function(){
var auto_refresh = setInterval(function (){
    $('#mydiv').load('xyz.php', {count: count}, function () {
        count = count + 1;

        //after three attempts it won't call php file.
        if (count > 2) {
            clearInterval(auto_refresh);
        }
    }).fadeIn("slow");
    }, 1000); 
});

In PHP:

<?php
$questions=array(
                 "Array Item 1",
                 "Array Item 2",
                 "Array Item 3");

if (isset($_POST["count"])) {
    echo $questions[intval($_POST["count"])];
}
?>
Sign up to request clarification or add additional context in comments.

5 Comments

count should start at 0 here, otherwise it will skip one iteration and will end in an undefined index warning, as PHP array keys start at 0, making $questions[0] == 'Array Item 1'. $questions[1] is actually 'Array Item 2'
ahh. ok. then start count from 0 in javascript. I updated my answer.
@user10 - Page is displaying blank. I put else in you php code and noticed that else part is executing which means isset($_GET["count"]) is not working in your code. Can you look into it?
change it to $_POST. i updated my answer. it is working perfectly good in my side. let me know, if you still have problem.
@user10 - I changed it to $_POST, it worked. Before your comment, I had changed it to $_REQUEST which was also working. Thanks for your solution :). I am accepting your answers and also upvoting :)
1

Well all of the above answers should work, but what is the use of calling the ajax 3 times? where your requirement is to show the result one by one in interval,

Here is the better solution,

in your .php file

<?php
//echo rand();
$questions=array(
                 "Array Item 1",
                 "Array Item 2",
                 "Array Item 3");

echo json_encode($questions); // here is the change
?>

and in the .html file

<html lang="en">
  <head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function(){
         $.getJSON( "xyz.php", function( data ) { 
            // using $.getJSON rather of $.load
        // note that you can use any of jquery ajax method. with required changes,  
        $('#mydiv').fadeIn("slow");

        $.each( data, function( key, val ) {
           setInterval(function (){
              $('#mydiv').append( val + "<br>"); // or whatever is your formatting 
               });      
        });
         });
      });
    </script>
  </head>
  <body>
    <div id="mydiv"> </div>
  </body>
</html>

Comments

0

on the second page you can use session

    session_start();
    if(!isset($_SESSION['count'])){
        $_SESSION['count']=0;
    }
    else
    {
        $_SESSION['count'] = $_SESSION['count'] +1;
    }

    $questions=array(
             "Array Item 1",
             "Array Item 2",
             "Array Item 3");
    $qcount=count($question);

    if($qcount< $_SESSION['count']){
        // NA
    }
    else{
        echo $question[$_SESSION['count']];
    }

I hope this will help you out ...

1 Comment

I would stay away from using session and rather use JS localstorage and send it as a query param. Best server design is one where the server is stateless.
0

Maybe you could use ajax:

    <html lang="en">
<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            var attemp_count = 0;

            var auto_refresh = setInterval(function() {
                $.ajax({
                    url: 'xyz.php',
                    type: 'POST',
                    data: {attemp_count: attemp_count++}
                }).done(function(data) {
                        console.group('Attemp ' + attemp_count);
                        console.log(data);
                        console.groupEnd();
                        $('#mydiv').text(data);
                    });
                if(attemp_count > 2) {
                    clearInterval(auto_refresh);
                }
            }, 1000);
        });
    </script>
</head>
<body>
<div id="mydiv"></div>
</body>
</html>

And php backend file:

<?php
//echo rand();
$questions = array(
    "Array Item 1",
    "Array Item 2",
    "Array Item 3"
);

if (array_key_exists('attemp_count', $_POST) && array_key_exists($_POST['attemp_count'], $questions)) {
    echo $questions[$_POST['attemp_count']];
}

If you use the session, you may experience problems with two tabs in the browser. In my case, you can avoid it, because Each tab will be run as a standalone application.

Comments

0

I'm so very slow.. but spent time working on it so might as well post it now..

<html lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        var counter = 0;
        var auto_refresh = setInterval(function (){         
            $.post( "xyz.php", { counter: counter } ).done(function(data){
                $('#mydiv').html(data);
            });;
            counter++;
            if (counter >= 3){
                clearInterval(auto_refresh);
            }
        },1000);
    });
</script>
</head>
<body>
    <div id="mydiv"> </div>
</body>
</html>

And the xyz.php

<?php
$counter = $_POST['counter'];
$questions=array(
                 "Array Item 1",
                 "Array Item 2",
                 "Array Item 3");
echo $questions[$counter];
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.