Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a PHP variable as a parameter using HTML onClick

I looked through many similar examples, but I could not make this work.

So, I have this:

echo('<td colspan="3" style="background-color:#005673; text-align:right; padding: 4px 0px;">
      <button class="btnTrack" onClick="trackIt(' . $name . ')" >Track It!</button></td>');

That code is inside a for, so the variable $name will be different depending where I am at.

I am not trying to make things complicates, so first, I am just trying to pass that parameter to the function trackIt (I actually need to pass 2 of them.)

Then, I have a simple script (just to see if it will work):

<script>
//After you click on Track It

function trackIt(param) 
{
   alert("Hi!");
   alert(param);
}

</script>

However, it does not work.

If my onClick function is just onClick="trackIt()", then it works fine and I can alert "Hi!" by removing the parameter.

Thanks for the help! =]

like image 884
Felipe Avatar asked Apr 07 '26 11:04

Felipe


2 Answers

Try this..

echo('<td colspan="3" style="background-color:#005673; text-align:right; padding: 4px 0px;">
  <button class="btnTrack" onclick="trackIt(\'' . $name . '\')" >Track It!</button></td>');

Note: you have to use your way if the input parameter is a numeric value..


You are printing HTML as,

<td colspan="3" style="background-color:#005673; text-align:right; padding: 4px 0px;">
<button class="btnTrack" onclick="trackIt(test)" >Track It!</button></td>

But because the function trackIt needs a string as the input parameter, you have to print this..

<td colspan="3" style="background-color:#005673; text-align:right; padding: 4px 0px;">
<button class="btnTrack" onclick="trackIt('test')" >Track It!</button></td>

As you are using ' as boundaries to define strings in PHP, you have to escape it using \' in order to make ' character part of the string.

like image 86
Sampath Liyanage Avatar answered Apr 09 '26 00:04

Sampath Liyanage


The reason this doesn't work is due to the fact that you're passing an unencapsulated string as an argument in your HTML, however, it's being interpreted as a javascript variable, such as:

Uncaught ReferenceError: ValueOf$name is not defined

' Or if the variable contains spaces or special characters:

 Uncaught SyntaxError: Unexpected identifier

To resolve this, you should encapsulate your string with quotations.

"trackIt(\'' . $name . '\')"

If you're using an integer, string encapsulation is not required.

jsFiddle examples

like image 39
Ohgodwhy Avatar answered Apr 08 '26 23:04

Ohgodwhy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!