3

I'm using Yii2 framework for my project. I've a loop in my controller, and this is the code

detailController.php:

public function actionResult() {
    $connection = \Yii::$app->db;
    $searchModel = new HeaderSearch();
    $dataProvider = new ActiveDataProvider([
        'query' => Header::find()->
                where(['user_id' => Yii::$app->user->identity->id]),
        'pagination' => [
            'pageSize' => 24,
        ],
    ]);
    
    $val = base64_decode($val);
    $txt = base64_decode($txt);
    $arrayVal = explode(",", $val);
    unset($arrayVal[count($arrayVal) - 1]);
    $arrayHeader = explode(",", $txt);
    unset($arrayHeader[count($arrayHeader) - 1]);
    $headerArray = null;
    for ($i = 0; $i < count($arrayVal); $i++) {
        $headerArray[$arrayVal[$i]] = $arrayHeader[$i];
    }
    $userId = Yii::$app->user->id;
    $modelUser = User::find()->where(['id' => $userId])->one();
    $parentId = $modelUser->parent_id;
    $sql = $connection->createCommand("SELECT list_header FROM customize_header WHERE user_id=$userId");
    $modelData = $sql->queryColumn();
    $arrayData = json_decode($modelData[0]); //all data in array form
    $countData = count($arrayData); // count rows of data except header row

    $modelUser = User::find()->where(['id' => Yii::$app->user->id])->one();
    $data = CustomizeHeader::find()->all();
    $command = "DELETE FROM header WHERE user_id = '$userId'";
    $query = Yii::$app->db->createCommand($command)->execute();

    foreach ($arrayHeader as $value) {
        $az = preg_replace('/^([0-9]{1,2})(_.*)/i', "\\2", $value);
        $data = ltrim($az, '_');
        $command = "INSERT INTO header(nama_header, user_id, parent_id) VALUES('$data', '$userId', '$modelUser->parent_id')";
        $query = Yii::$app->db->createCommand($command)->execute();
    }
    $countHeader = count($arrayHeader);    //count of selected header
    $j = 0;
    $point = floor($countData / 4);
    $percent = 0;
    for ($k = $j; $k < $countData; $k++) { 
        if($k % $point == 0 && $k > 0){      //Special Condition
            $percent = $percent + 10;        // Special Variable
        }
        $keyData = array_keys($arrayData[$k]);
        $countKeyData = count($keyData);      
        for ($x = $k; $x <= $countData; $x++) {
            foreach ($arrayHeader as $key => $value) {
                $headerId[] = preg_replace('/^([0-9]{1,2})(_.*)/i', "\\1", $value);
            }
            $n[$k] = [];
            for ($a = 0; $a < $countHeader; $a++) {
                for ($b = 0; $b < $countKeyData; $b++) {
                    if ($headerId[$a] == $keyData[$b]) {
                        $n[$k][] = $arrayData[$k][$b];
                    }
                }
            }
        }
    }
      //some code
    return $this->render('index', [
                'searchModel' => $searchModel,
                'dataProvider' => $dataProvider,
                'userId' => $userId,
    ]);

In the code above, I've a condition if($k % $point == 0 && $k > 0) that I give comment tag as Special Condition that consist a variable $percent that I give comment tag as Special Variable. I want to send this variable(inc. value) to upload.js everytime the condition is true.

So the variable will be send to upload.js real-time during the action is proccessing.

upload.js:

function displayResult() {
$('#progress').show();
var x = document.getElementById('bootstrap-duallistbox-selected-list_CustomizeHeader[list_header][]');
if (x.length == 24) {
    var txt = "";
    var val = "";
    for (var i = 0; i < x.length; i++) {
        txt += x[i].text + ",";
        val += x[i].value + ",";
    document.getElementById("progress").innerHTML="<div style=\"width:'percent';background-color:#ddd;\">&nbsp;</div>"; //Here
    }
    window.location = 'result?txt=' + btoa(txt) + '&val=' + btoa(val);
} else {
    alert("At least 24 Headers!");
}
}

I use this script to show a progress bar in view.php, width of progress bar(line code that I've set comment tag as Here) depend on $percent that has been passed from controller to this script.

So how to passing variable from PHP Javascript real-time during an action is execute?

Any idea how to solved this? Thankyou :)

Community
  • 1
  • 1
Blackjack
  • 1,016
  • 1
  • 20
  • 51
  • in your code i don't see how you obtain the $dataProvider and which relation exist with the value in your loop and your dataProvider .. please expalin better – ScaisEdge Jan 13 '17 at 10:31
  • @scaisEdge, I'm sorry, I forgot to add notice as comment `some code`. I didn't add the code because it consist of more than 30 lines of code. Should I add the code? thanks – Blackjack Jan 13 '17 at 10:47
  • Yes add the code so i can take a look – ScaisEdge Jan 13 '17 at 10:49
  • @scaisEdge I've update the code, check the question. – Blackjack Jan 13 '17 at 11:01

2 Answers2

1

In this case you should pass the proper value in the return array and then manage a proper use in view
eg: assuming the value you need is in the $percent var

in Your controller

   return $this->render('index', [
                  'searchModel' => $searchModel,
                  'dataProvider' => $dataProvider,
                  'userId' => $userId,
                  'percent' => $percent
      ]);

the in in your view you could check for the proper use

.......

  <?php  

     if ( $percent > 0) {
      echo "<div>". $percent . "</div>";
     }
  ?>

 .....
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
  • Thanks, but I think if I use render to send the data, it will interrupt the action execution. I'm sorry, I've update the title in the first edit that I want to pass the data to javascript. How do you think about ajax? Someone told to use ajax to send data real-time, I've try some code but It didn't work. – Blackjack Jan 13 '17 at 11:31
  • for pass data to javascript instead of render you can use a return (or na echo) but these are sended where the action end. hope is clear otherwise let me kown your doubt – ScaisEdge Jan 13 '17 at 12:11
  • thanks for the learn. If I use return, doesn't it will interrupt the action? – Blackjack Jan 13 '17 at 12:26
  • Yes if you use return you end the action . If you need a ciclic communication between client and server (javascript to php) you should use eg: a separated (fast) action .. invoked by ajavx only for know the advancement of you process .. – ScaisEdge Jan 13 '17 at 12:34
  • separated action? How we can use ajax to get advancement of an action from controller? – Blackjack Jan 13 '17 at 13:54
  • Ok, I think a timer better than loop. I'll try, thanks for your suggestion :) – Blackjack Jan 13 '17 at 14:01
0
if ($percent) {
    return $this->render('index', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
        'userId' => $userId,
        'percent' => $percent
    ]);
}

return $this->render('index', [
    'searchModel' => $searchModel,
    'dataProvider' => $dataProvider,
    'userId' => $userId,
]);

i hole that would be useful for you.