user1540714
user1540714

Reputation: 2089

JavaScript and PHP in code - whats the difference?

I have this code in my JavaScript part:

var opConfig = new Product.Options(<?php echo $this->getJsonConfig(); ?>);

The PHP call returns me some string, to make it easy, lets say the string is abcd. So this code results in:

var opConfig = new Product.Options(abcd);

Now, some lines later, I have this code:

this.opConfig = new Product.Options(opconfig);

The opconfig variable has the same string abcd, but the results are different, this.opConfig does not look like it looked before. So is there a difference in how I use the string as param? Something I am missing? For me, it should always be the same call, namely:

new Product.Options(abcd)

Ideas?

Addition: The full call in the JS code looks like that:

var opConfig = new Product.Options({"16":{"26":{"price":5,"oldPrice":5,"priceValue":"5.0000","type":"fixed","excludeTax":5,"includeTax":5},"28":{"price":8,"oldPrice":8,"priceValue":"8.0000","type":"fixed","excludeTax":8,"includeTax":8},"27":{"price":10,"oldPrice":10,"priceValue":"10.0000","type":"fixed","excludeTax":10,"includeTax":10}},"14":{"price":0,"oldPrice":0,"priceValue":"0.0000","type":"fixed","excludeTax":0,"includeTax":0},"15":{"price":0,"oldPrice":0,"priceValue":"0.0000","type":"fixed","excludeTax":0,"includeTax":0}});

The param reaches the called function as object, no idea why. Calling it the other way, the same string seems to reach it as string. Can anybody help?

Upvotes: 0

Views: 138

Answers (4)

Koti
Koti

Reputation: 131

Change the below line

var opConfig = new Product.Options(<?php echo $this->getJsonConfig(); ?>);

to

var opConfig = new Product.Options('<?php echo $this->getJsonConfig(); ?>');

Upvotes: 0

kante
kante

Reputation: 229

I can see you're missing quotes:

var opConfig = new Product.Options('<?php echo $this->getJsonConfig(); ?>');

Upvotes: 0

nnnnnn
nnnnnn

Reputation: 150080

If you have new Product.Options(abcd) then abcd is a variable name, not a string. You need to add quotes so that it ends up as new Product.Options('abcd'):

var opConfig = new Product.Options('<?php echo $this->getJsonConfig(); ?>');
// OR
var opConfig = new Product.Options("<?php echo $this->getJsonConfig(); ?>");

Either way you need to be sure your PHP output escapes any characters that might "break" the string literal, e.g., single-quotes (in the first one) or double-quotes (in the second one), or newlines (in either).

Upvotes: 0

Curtis
Curtis

Reputation: 103388

Change to:

var opConfig = new Product.Options('<?php echo $this->getJsonConfig(); ?>');

opconfig is a string variable, so its fine passing that as a parameter.

Whereas your PHP code will render:

var opConfig = new Product.Options(abcd);

abcd is not a string variable. Therefore you need to put this in speech marks so that it becomes a string object. Your output would now be:

var opConfig = new Product.Options('abcd');

Upvotes: 2

Related Questions