Hans Ullrich
Hans Ullrich

Reputation: 185

Change value in PHP using Javascript

I am getting an Array out of a database and want to display it. This is my approach so far:

for ($i = 0; $i < count($results); $i++)
{
 $output .= "<tr>
 <td>".$results[$i]."</td>
 </tr>";
}
print_r($output);

This works fine but the values inside the array look like this: "6.212,50"

So they are strings but I need to unformat them to do further calculations for that I use numeral.js which works like this:

numeral().unformat('6.212,50') //outputs 6212.50

How can I run this inside the PHP loop? I already tried this:

for ($i = 0; $i < count($results); $i++)
{
 $output .= "<tr>
 <td><script>numeral().unformat('$results[$i]')</script></td>
 </tr>";
}
print_r($output);

But that displays nothing.

Upvotes: 1

Views: 45

Answers (2)

William
William

Reputation: 751

The script is run on the client side, and script tags don't return something into the table. They just execute the JavaScript and think that it is done.

Another thing is that html is just text. If you parse the float and write it to the table, the content will still be strings.

If you want to do calculations on the client side, you write a Javascript that finds the values, parses them into floats, and stores them inside the script for calculation.

If you want to print the sum or something, then set the content of some html tag to the sum. But it will be set to its string value.

If you only want to parse the number to get rid of some dots, I suggest writing a php function and parse it on the server before writing it to the view.

Upvotes: 2

georoot
georoot

Reputation: 3617

that is because the javascript is interpreted but is nowhere displaying it.try this

for ($i = 0; $i < count($results); $i++)
{
  $output .= "<tr><td><script>document.write(numeral().unformat('".$results[$i]."'));</script></td>
</tr>";
}

document.write will print the result in javascript.

Upvotes: 3

Related Questions