I'm trying to call the Javascript function It's working if I use in Html
<input type="button" value="Click Me" onclick="$.notify('Error: Sign in before Join.', 'error');" class="nk-btn">
But I wanna use that code in Php echo"" but doesn't work
echo" <input type='button' value='Click Me' onclick='$.notify('Error: Sign in before Join.', 'error');' class="nk-btn"> "
because of Using Single quotes insted of Double:
How to call js function in another way??
3 Answers 3
You can use \ to escape quotes in php.
echo "<input type='button' value='Click Me' onclick=\"$.notify('Error: Sign in before Join.', 'error');\" class=\"nk-btn\">"
Your problem is that you are using the same quotes for your onclick and inside the $.notify
The same with the class
Comments
you can do it like
echo "<input type='button' value='Click Me' onclick='$.notify('Error: Sign in before Join.', 'error');' class='nk-btn'>"
or
echo "<input type='button' value='Click Me' onclick='$.notify('Error: Sign in before Join.', 'error');' class=\"nk-btn\">"
Comments
Instead of messing around with escaping quotes in the string, just close the PHP block, write the HTML and open a new PHP block again after it, if needed:
// Some PHP
?>
<input type="button" value="Click Me" onclick="$.notify('Error: Sign in before Join.', 'error');" class="nk-btn">
<?php
// More PHP
This will not only free you from escaping the quotes, but most IDE's can syntax highlight the HTML as well (which helps with readability and debugging)
However
A better way would probably be not to have the onclick attribute on the element at all but rather register an even listener directly in js.
echoto output the element with the onclick method does not work, not that they are trying to call a PHP function from JS.echostatement - or use HEREDOC syntax if you like... but I'd be amazed if there's not a functional duplicate for this on SO already tbh.?>, write your HTML and then when you're done, start the PHP block again<?phpand you won't need to care about escaping the quotes.