user2624583
user2624583

Reputation: 54

How to pass javascript variables to php variables with yii

First: I KNOW this is a duplicate. I am creating this because none of the answers to all the other questions satisfy me. I have a very particular situation where I'm using yii and tryi I can't send it through ajax because the php and javascript are on the same page on the same page.

Basically what I'm asking is if you have a page that uses yii and chart js, and you need to render a page that requires two arguments from the clicked bar, which is represented by activeBars[0]:

<script>
    canvas.onclick = function(event) {
        var activeBars = getBarsAtEvent(event);
        <?php $controller->functionThatRendersView($arg1 /**(activeBars[0].value*/,$arg2 /**(activeBars[0].label*/); ?>
    }

I don't care if it will render automatically, that is another problem. I just need to get those arguments to the php.

Thanks.

Also, if it helps, I am passing those two values to javascript through php for loops:

labels: [<?php for ($i=1;$i<=$numberIssues;$i++) {
            echo $i . ",";
        }?>],

The problem with grabbing $i and putting it into the label argument is that I don't know which bar label is the clicked one, I need javascript to pass the clicked bar values back to php.

Upvotes: 0

Views: 1041

Answers (2)

user2624583
user2624583

Reputation: 54

I found an answer to my question! I'm just doing this for anyone else who is stumbling:

To pass javasctipt variable var jsInteger = 5; to php you type (in javascript):

window.location.href = "yourPhpFile.php?phpInteger="+jsInteger;

You access the variable in php like so:

$phpInteger = $_GET['phpInteger'];

This will require a page refresh, and will redirect you to the php file.

Upvotes: 1

David Knipe
David Knipe

Reputation: 3444

Explain to us again why you can't use ajax. You say "because the php and javascript are on the same page". That's not what ajax is - you need a different URL for the ajax request, and a separate PHP file or something to handle it.

Without ajax it's impossible for javascript to send information to PHP, because the PHP runs on the server before the javascript runs on the client. Unless of course you want to do a complete page refresh, which is slower and generally worse from the user perspective.

Upvotes: 2

Related Questions