Syntax error, unexpected '(', expecting variable (T_VARIABLE) or '{' or '$'

Hello,

I wonder why I get this error message:
syntax error, unexpected ‘(’, expecting variable (T_VARIABLE) or ‘{’ or ‘$’

Rp. <div id="total"></div>

<script>

	$("#total").html({<?php number_format($("#subtot").val(), 0, '', '.'); ?>});

</script>

Thanks.

I’m not sure you can stick $("#subtot").val() into your PHP code there - remember the PHP code runs on the server when it is drawing the page, so the value substitution won’t be happening. I am no Javascript expert, but I think that’s the issue.

1 Like

droop is correct. you cant use php to format a javascript value, because they run at different times. PHP runs on the server, during page load. Javascript runs in the browser, during page view.

Javascript does have similar functions; check out Number.toFixed and .toLocaleString

I tried this.

Rp. <div id="total"></div>

<script>

	$subtot = $("#subtot").val();

	$("#total").html($subtot.toLocaleString());

</script>

and it shows nothing.

What’s #subtot ?

<script>

	$subtot = $("#subtot").val();

	alert($subtot);

	$("#total").html($subtot.toLocaleString());

</script>

The value of $subtot is 200000

Your browser might not have a Locale set. Try forcing one ie: $subtot.toLocaleString("en-US")

You may also need to force $subtot to a Number first, because it wont convert a string by default.

image

Rp.

<script>

	$subtot = $("#subtot").val();

	alert($subtot);

	$("#total").html($("#subtot").val().toLocaleString("en-US"));


</script>

The result is: Rp. 100000

There is no Rp. 100,000 or Rp. 100.000 (this is what I actually expected Indonesian Rupiah)

So you’re doing a currency in particular. Okay, well, toLocaleString has more help there, too.

Let’s first get your number to be… a number. .val() will return a string.

	$subtot = $("#subtot").val();

=>

	$subtot = Number($("#subtot").val());

Now to get fancy with toLocalString.

$subtot.toLocaleString("id-ID",{ style: "currency", currency: "IDR" })

image

or if you want it as a whole number… $subtot.toLocaleString("id-ID",{ style: "currency", currency: "IDR", maximumFractionDigits: 0 })

1 Like

Is it possible to erase the:

Rp 100.000,00 into Rp. 100.000 ?

Yeah, thats the last line i put in there. set the maximumFractionDigits to 0 and it will chop off the sen.

Thanks. and I have another question about date function. Is it okay if I post it here?

I just get a reply for new comers that each post is open for further discussion, therefore I think I just post my other question:

<?php date("M D, Y"); ?>

I expected a result like: August 5, 2022

My current code did not show anything.

note: anyone is welcome to answer.

you forgot to tell php to echo the result.

There is a shorthand for that: <?= which means “start a PHP block, and echo whatever comes out”

1 Like