tags:

views:

233

answers:

2

Hi ,

In my application , i am trying to use the Php variable in my JQUery . where $viewfields is an array that i retrieve from my cakephp controller. If i tried to use that one like below, i am getting error as for( in Array){\n

 for(<?=$viewfield;?> in <?=$viewfields;?>){}

Please suggest me. What to do so..

Note: i was previously using the above code like

  <?php foreach ($viewfields as $r): ?>
   <?php endforeach?>

It works good. But i thought of changing it like for() but its showing error why so??

A: 

Since $viewfields is a PHP object, you need to assert that its echoed representation is valid javascript. As such, you need to convert it into a string that is a valid JSON array/object. this page has a function for doing such a thing. Since you're not exposing the data of your array, it's hard to tell if the function given by the link is overly complex for your purposes or not. Lastly, make sure $viewfield is a valid javascript identifier (ascii string, doesn't begin with a number and so on).

Cide
A: 

As answered in your other question(s), PHP and Javascript just don't work together like this. You'll have to convert the PHP array to some Javascript type at the very least, for example using Cake's JavascriptHelper:

echo $javascript->value($myVar);

Look at the resulting HTML to verify the results.

Please make sure you understand what PHP is and what Javascript is. Your first and second constructs are for completely different purposes!

deceze