0

I m new to CakePhp and JQuery. I am getting an error in using the cakephp code inside my JQuery.

My code

   <script type="text/javascript">
     $(document).ready(function(){
     var attributeid;var fieldname;
     $("#"+<?=$r['Attribute']['id'];?>).change(function () {

     fieldname=<?=$r['Attribute']['label'];?>; 
              alert(fieldname);//this show me that undefined 
             attributeid=<?=$r['Attribute']['id'];?>; 
             alert(attributeid);//But this works

    });//attribute change
});//ready function 

if I echoed ($r['Attribute']['label'];) this value is coming inside my <?php ?>. But not inside my JQuery.

Note :

attributeid=<?=$r['Attribute']['id'];?>; 
alert(attributeid);//But this works  


Error: 
Name is not defined
fieldname=name; 
alert(fieldname);
1
  • Can you view the source of the website after it's generated and paste in what shows up there? Commented Jun 11, 2009 at 10:28

1 Answer 1

10

You are not thinking about how this is translating over once the variables are echoed.

If you have a variable $x with the contents "test", doing this:

var x = <?=$myvar?>;

Will result in:

var x = test;

This is not valid (unless test is a variable) because you need quotations around it to make it a string:

var x = "<?=$myvar?>";

Which then results in the valid:

var x = "test";

The reason it works with the other variable is because you are echoing an ID, which is an integer:

var x = <?=$myid?>;

Would translate to:

var x = 5;

Which is perfectly valid.

All this being said, you should put all the stuff you want to send over to Javascript in an array and call json_encode on it to easily and safely print the values over. Without it, you have to worry above about escaping quotes in the string and such.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.