Justi Srilazs Justi Srilazs - 1 year ago 45
Javascript Question

Why am I unable to assign a list like this to a jquery variable?

Why am I unable to assign a php variable like this to jquery?

So if my php variable was

$amounts = 2,4,5
and when I echo it is
why is it not the same when I pass it to a
variable like this:

var amountFinal = <?php echo $amounts; ?>;

If I just do:

alert(JSON.stringify(<?php echo $amounts; ?>));, it prints `2`

All I want to do is pass
to amountFinal.

How do I do this? I am new to programming

ALSO, in php how do I break
into just

Answer Source

Your $amounts is a string with commas in it so you need to make the javascript code legal and wrap it in quotes. Also as its a string and not valid JSON change the alert also.

var amountFinal = "<?php echo $amounts; ?>";

I dont understand what you mean by you second question?

ALSO, in php how do I break 2,4,5 into just 2, 4, 5?

Do you mean you want to make it into an array or you want to add some spaces?

To make 2,4,5 into 2 4 5 you can do

$originalString = '2,4,5';
list($one,$two,$three) = explode(',', $originalString);
echo $one;
echo $two;
echo $three;

Or add them to an array

$originalString = '2,4,5';
$array = explode(',', $originalString);