4

I have some id (primary keys from database) with the next format: 2019/34. I show this code in a table where i can see it normally. The problem comes when i try to send this variable in PHP to a javascript method. As im using a slash in the id, when i send the php variable as parameter of the javascript method, it makes the count. It divides 2019 and 34 when i want to send the parameter 2019/34.

I have tried to parse the actual php string variable to string before send it through the parameter.

I have tried to send the parameter using quotes but it makes the count too.

I have even tried to separate the id (2019 and 34), send them to the javascript method using two parameters and making again the complete string in the method. But when i use the explode method (explode("/",$id)), it makes the count again.

echo "<td><a href='javascript:newConcepto(".$id.")'></a></td>"
Expected object sended: "2019/34".  
Actual object sended:   "59.3823529" (The division of 2019 and 34).
Qirel
  • 25,449
  • 7
  • 45
  • 62
wasanga7
  • 242
  • 1
  • 3
  • 17
  • 1
    You can use `` within the echo. But I really recommend to use a templating engine to handle it. Or send it via ajax like [in this post](https://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript) – KarelG May 16 '19 at 07:12
  • Maybe you can convert the `$id` with the `strval($id)` method. This converts the `$id` to a string. – Refilon May 16 '19 at 07:17

2 Answers2

4

When you don't put the variable in quotes (from a JavaScript perspective), it assumes that you're doing math - as 2019 / 34 is a mathematical equation. Wrap it in quotes, and it becomes a string instead! To avoid collision with the href attribute, use doublequotes there - and to avoid conflict with the PHP double quotes, escape them.

echo "<td><a href=\"javascript:newConcepto('$id')\"></a></td>";

PHP variables are parsed within double quotes, so you don't need to concatenate the value either, you can do it all inline. There's nothing wrong with doing it either though, by doing newConcepto('".$id."').

Qirel
  • 25,449
  • 7
  • 45
  • 62
-1

Try this

echo "<td><a href='javascript:newConcepto('".$id."')'></a></td>"