nainy
nainy

Reputation: 540

Yii: best practices to pass data from php to JS

My question is, what are the best practices of passing the data from my server side to my client side?

For example, I have a cartId on my server side which I need to pass on to the client side.

How do I best do that? Right now it's done via the main layout:

<script type='text/javascript'>
    (function() {
         if (window.cart) {
             cart.id = <?php echo Yii::app()->getUser()->getCartId() ?>;
         }
    })();
</script>

However, that seems like a bad thing to do. Will appreciate any feedback.

Upvotes: 2

Views: 1514

Answers (5)

Rogin Thomas
Rogin Thomas

Reputation: 772

The best option is to make AJAX calls to a PHP page which performs some action, and returns data. Once that PHP has all the data it needs to return, I echo the data (as an array) in JSON format. Eg:

info.php

die (
json_encode(
    array(
        "id" => "27"
        "name" => "rogin",

    )
)

);

Then, you can use javascript to fetch the data into a json object.

JS

$.getJSON(
'info.php?',   
function(jsonObject) { 
    alert(jsonObject.name); 
});

Upvotes: 1

Ruprit
Ruprit

Reputation: 743

In php file write this YII code

YII Code

Yii::app()->clientScript->registerScript("cartid",Yii::app()->getUser()->getCartId());

SCRIPT

(function() {
if (window.cart) {
    cart.id = cartid;
}
})();

Upvotes: 2

Glitches
Glitches

Reputation: 752

It's best practice to not write PHP in your JavaScript for one. Instead, take the data from PHP and pass it to json_encode (http://php.net/json_encode) and echo it out. You can read that straight into a variable if you like but it would be better to use ajax so it's asynchronous thus better page load.

Upvotes: 1

Kokizzu
Kokizzu

Reputation: 26848

If you just want to prevent javascript syntax highlighting error, quoting would do just fine.

(function() {
     var the_id = +'<?php echo Yii::app()->getUser()->getCartId() ?>';
     //           ^ + to convert back to integer
     if (window.cart) {
         cart.id = the_id;
     }
})();

Or if you like you could add it to an element:

<div id='foo' style='display:none'><?php echo Yii::app()->getUser()->getCartId() ?></div>

Then parse it later

<script>
  (function() {
     var the_id = +($('#foo').html()); // or parseInt
                                       // or JSON.parse if its a JSON
     if (window.cart) {
         cart.id = the_id;
     }
  })();
</script>

Upvotes: 0

Arunprasanth K V
Arunprasanth K V

Reputation: 21931

  1. Use AJAX to get the data you need from the server.
  2. Echo the data into the page somewhere, and use JavaScript to get the information from the DOM.
  3. Echo the data directly to JavaScript.

With AJAX, you need two pages, one is where PHP generates the output, and the second is where JavaScript gets that output:

get-data.php

/* Do some operation here, like talk to the database, the file-session
 * The world beyond, limbo, the city of shimmers, and Canada.
 * 
 * AJAX generally uses strings, but you can output JSON, HTML and XML as well. 
 * It all depends on the Content-type header that you send with your AJAX
 * request. */

echo json_encode(42); //In the end, you need to echo the result. 
                      //All data should be json_encoded.
index.php (or whatever the actual page is named like)
<script>
    function reqListener () {
      console.log(this.responseText);
    }

    var oReq = new XMLHttpRequest(); //New request object
    oReq.onload = function() {
        //This is where you handle what to do with the response.
        //The actual data is found on this.responseText
        alert(this.responseText); //Will alert: 42
    };
    oReq.open("get", "get-data.php", true);
    //                               ^ Don't block the rest of the execution.
    //                                 Don't wait until the request finishes to 
    //                                 continue.
    oReq.send();
</script>

The above combination of the two files will alert 42 when the file finishes loading.

Upvotes: 1

Related Questions