0

I need to pass variables defined in PHP to a javascript function. The JS function needs to be called with a button onclick event.

<button type="button" style="width: 70px;" class="btn btn-light btn-sm Center"
                  onclick="<?php  echo '<script>purchase('{$user}','{$painting1_Title}','200')</script>'?>">Purchase</button>

I have tried different connotations of single and double quotes but am getting parsing errors:

Parse error: syntax error, unexpected '','' (T_CONSTANT_ENCAPSED_STRING), expecting ',' or ';' in /Applications/XAMPP/xamppfiles/htdocs/ProjectWebsite/Mainpage2.php on line 303

So my question is how to call a javascript function with PHP inside a onclick event?

dancingbush
  • 2,131
  • 5
  • 30
  • 66
  • 3
    Remove the script tag from `onclick` attribute. Then fix the quotation, and your code should work. – Teemu Apr 27 '20 at 08:51
  • You cannot call a JavaScript function from PHP. PHP composes the everything server-side, that result is then sent to the client (browser) and the client then interprets the received data. But there is never a direct interaction between server-side PHP and client-side JavaScript. – t.niese Apr 27 '20 at 09:02
  • You don't need those `script` tags and you need some correction with those quotes. You can check this [link](https://ideone.com/S9wayn) for an idea. – Sifat Haque Apr 27 '20 at 08:52

2 Answers2

2

You can always escape quotes inside of other quotes to prevent the nightmare of quote nesting.

"This is how you would \"fix\" certain \"quotation issues\""

My take is to use single quotes escaped inside of double quotes, even though usually single quotes work within double quotes.

"This is how you would \'fix\' certain \'quotation issues\'"

Joel Hager
  • 2,990
  • 3
  • 15
  • 44
1

I guess you want a result that looks something like this:

<button type="button" style="width: 70px;" class="btn btn-light btn-sm Center" onclick="purchase('user','painting_title','200')">Purchase</button>

You've some errors in your escaping and you should not use script tags, try this one:

<button type="button" style="width: 70px;" class="btn btn-light btn-sm Center"
                  onclick="<?php echo "purchase('" . $user . "','" . $painting1_Title . "','" . 200 . "')"; ?>">Purchase</button>
mikaelwallgren
  • 310
  • 2
  • 9