-2

I am trying to increment php variable after some action happens in javascript. The problem is that the variable will increment only once (from 0 to 1). After that it stays as 1. I would like it to increment to 2 and so on after the action in JS is finished. Here is my code:

<script>
         // create youtube player
            var player;
        //$array = just an array of strings
        //$array_position = position in array
            <?php $array_position = 0; ?> 
            function onYouTubePlayerAPIReady() {
                player = new YT.Player('player', {
                width: '640',
                height: '390',
                videoId: '<?php echo $array[$array_position];?>',
                events: {
                          onStateChange: onPlayerStateChange
                        }
                });
            }
    // when video ends the $array_poisition should increment everytime
            function onPlayerStateChange(event) {      
                if(event.data === 0) { 
                    <?php
                        $array_position++;
                    ?>
                //change the id of the video
            player.loadVideoById('<?php echo $array[$array_position];?>');
                }
            }
</script>

Thanks for any advice.

Adam Šulc
  • 526
  • 6
  • 24
  • You can't mix Javascript and PHP in that way, since JS is running in your browser and PHP on the server. – Erik Kalkoken Feb 04 '18 at 11:40
  • 2
    PHP is executed on the server, before the browser interprets the JavaScript. Anything outside the `` is just sent to the browser by the server without further consideration, whereas the code inside the PHP tags is executed by the server. The Javascript code is ignored by the server, it just sees ``, ``, and `` and executes these exactly as one would expect. – 11684 Feb 04 '18 at 11:40
  • How many times is tht function getting called? – Arunkumar Srisailapathi Feb 04 '18 at 11:41
  • If you want to update data on the server from JS you need to make a server call, e.g. with AJAX – Erik Kalkoken Feb 04 '18 at 11:41
  • Well then, thanks. Can you give me some example how can I do this in javascript? I just want some variable to increment everytime when function onPlayerStateChange(event) is triggered. – Adam Šulc Feb 04 '18 at 11:43
  • 2
    Possible duplicate of [What is the difference between client-side and server-side programming?](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – Teemu Feb 04 '18 at 11:44
  • Look into [AJAX](https://www.w3schools.com/js/js_ajax_intro.asp). That is the standard way of communicating between JS and PHP. – Erik Kalkoken Feb 04 '18 at 11:45
  • @ErikKalkoken Yes, however in this case I think the whole array could be client-side, making AJAX overkill; echoing the array with json_encode when the page is requested should make it possible to handle the increments in JS. – 11684 Feb 04 '18 at 11:47
  • @AdamŠulc Echo the array in PHP in a JS variable (`var array = echo json_encode($array); ?>;` and have a pure JS variable `var array_position = 0;` which you increment without PHP (`array_position++;` and `player.loadVideoById(array[array_position]);`). – 11684 Feb 04 '18 at 11:49
  • @11684 yes, if all logic concerning increment and working with the increment is done in JS, that would work of course. – Erik Kalkoken Feb 04 '18 at 11:52
  • Have you considered client-side [localStorage](https://www.w3schools.com/html/html5_webstorage.asp) for Javascript? Or do you need it in php, server-side? – Savvas Radevic Feb 04 '18 at 11:55
  • @11684 That looks good to me, just one more question, since Im not really good with JS. Do I just put this into videoID? So it will look like this: videoId: array[array_position], – Adam Šulc Feb 04 '18 at 11:57
  • @AdamŠulc yes, syntactically that is correct. However I don't know either what's in the array or what the YouTube API expects. – 11684 Feb 04 '18 at 12:00
  • @11684 In array is a series of video ID's (mgJ8BZi3vTA) for example. In array in this case are 5 different ID's. Youtube API expects to get one of these ID's. videoId: array[array_position] Should be first ID in array. However it doesnt seem to work for me. – Adam Šulc Feb 04 '18 at 12:05
  • @11684 Nevermind, managed to make it work, there was just a stupid syntax error made by me in a different part of the script. By the way its working just as I wanted, so thank you a lot. – Adam Šulc Feb 04 '18 at 12:15
  • @AdamŠulc Do you know how to use the developer tools present in most browsers? – 11684 Feb 04 '18 at 12:17
  • @11684 Yes, I do. – Adam Šulc Feb 04 '18 at 12:22

2 Answers2

1

First thing you should do is to read something about differences between server-side and client-side programming.

As teemu suggest or here is nice explanation.

Important note is that php code is executed before the html and javascript. And its not executed again until the server is requested for it.


Example

The best i think is not to combine php and javascript together. So for easy example your code may look like this:

index.htm (or w/e)

<script type="text/javascript">
var array_position = 0; // init position
var video_id = 0; // init video_id

 // create youtube player
var player;
// $array = just an array of strings
// $array_position = position in array
function onYouTubePlayerAPIReady() {
    player = new YT.Player('player', {
        width: '640',
        height: '390',
        videoId: video_id,
        events: {
            onStateChange: onPlayerStateChange
        }
    });
}

// when video ends the $array_poisition should increment everytime
function onPlayerStateChange(event) {
    if (event.data === 0) {
        // make ajax request
        ajaxRequest();
    }
}

// make ajax request to change array position and video_id
function ajaxRequest() {
    $.ajax({
        url: "getVideoId.php",
        type: "post",
        data: {position: array_position},
        success: function (load) { // IF AJAX IS SUCCESS ->
            array_position++;
            //change video_id
            video_id = load;
            //change the id of the video
            player.loadVideoById(video_id);
        }
    });
}

Important note that ajax is called with jquery so you surely want to link it.

getVideoId.php

   <?php
      // Whatever array of whatever values
      $array = [1,2,3,4,5,6,7,8,9,10];
      // Echo it out
      echo $array[$_POST['position']];

Addition

You will sure want to edit this code for your needs. Add some conditions or add error handle to ajax request.

Other approach can be to load array with Video IDs to javascript on script load and then it could be just js script without ajax request.

-1

You can use Php-to-Js Youtube plugin for php. Or You should send a javascript request to server before you increment it

requestJs->server(increment(array_position))