0

I have the following code:

<h2 id="excTitle">
   <div id="titleText">
       <?=$exercises[$currentExc]?>
   </div>
</h2> 

The above code displays a title.

<button type="button" class="styled-button-10b" onClick="skipExc()">Skip</button>

The above code calls the below function, which should change the title.

//Skip to the next exercise
function skipExc()
{
    <?php
         $currentExc++;
    ?>

    $("#titleText").html('<?php echo $exercises[$currentExc]; ?>');
}

It actually works, but only once.

Let's say I have 5 different titles (5 items in my $exercises array), the code above only go from the first title to the second title and then stops updating.

I have tested and the function is called, but the title doesn't change.

Can anybody please help me with this? Thanks.

2
  • 5
    It works only once, as php is run before page load, so <?php echo $exercises[$currentExc]; ?> does not change once the page loads. You can either store $exercises as a javascript array, and increment through it, or you will need to use ajax to go back to the server/php to get the next value(s) Commented Dec 14, 2014 at 2:25
  • $exercises[$currentExc]; was processed in server and returned a single value when it's arriving at the client end. Commented Dec 14, 2014 at 2:30

1 Answer 1

2

You can encode your php array to json and then update the counter/index via javascript

var count = 0;
        
function skipExc() {
  var exercises = <?php echo json_encode($exercises); ?>;
            
  $("#titleText").html(exercises[count]);
        
  count++;
}
<h2 id="excTitle">
  <div id="titleText"></div>
</h2>
<button type="button" class="styled-button-10b" onClick="skipExc()">Skip</button>
<?php $exercises = array('a', 'b', 'c'); ?>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.