Hello,

I get this error message: syntax error, unexpected '(', expecting variable (T_VARIABLE) or '{' or '$'

When running this code:

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

<script>

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

</script>

`

Any idea why?

AdamFriska commented: You can use AJAX for this kind of situtation +0

$("#subtot").val() is javascript but you are attempting to pass it into a php function. Php doesn’t know what to do with it.

Hi,

Do you still need help with this? I'm a bit confused what you're trying to do because it looks like you're trying to use PHP's number_format() on a Javascript value, which isn't something you can do.

The double quotes in Javascript $("#subtot").val() in the PHP are causing that error. They have to be quoted \". However there is more to extracting the number from Javascript into PHP.

You have to separate the PHP and Javascript so you evaluate the Javascript

<?php $x = (int)\"".$("#subtot").val()."\"; ?>

and pass it to

<?php number_format($x, 0, '', '.'); ?>

so

<?php $x = (int)\"".$("#subtot").val()."\"; number_format($x, 0, '', '.'); ?>

Just use Javascript number format function e.g. Intl.NumberFormat rather than trying to get data from Javascript to PHP to use PHP number_format.

I don't think that wwwalker's solution will work. You can't really combine PHP and javascript in that way because PHP is executed at the server level, before sending the HTTP resource to the web browser, and the Javascript is executed after the web browser has parsed the HTML on the webpage.

For example, suppose the end-user wants to fetch this PHP page. The web server then processes the PHP code. When it finishes processing all the PHP code, it sends the final HTML that the PHP generated to the web browser. But, while it's processing, when it comes to trying to figure out $("#subtot").val(), then there's not really anything it can do with that. The PHP code hasn't generated any HTML yet, and, subsequently, no HTML was sent to the web browser yet, and, subsequently, the end-user's web browser has not yet received, never mind parsed, the HTML, so there's no concept yet of some HTML entity with ID subtot.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.