Search code examples
javascriptphpstringquotesquoting

Using PHP variables as parameters for JavaScript function


I'm having a bit of trouble working with the quotations for this. So, let's make an example of sending two strings we want concatenated through variables, and then running them through a JavaScript function to concatenate them (I understand that this is very basic in PHP and I know how to do it, I'm just using this example for the sake of simplicity).

JavaScript Code:

function con(first, last) {
    answer = first+last;
    alert(answer);
    return;
}

HTML and PHP:

<?php
    $first = "Butter";
    $last = "Last";
    echo '<input type="button" value="Get Answer" onclick="con(".$first.", ".$last.")" />';
?>

This code above does not work, how can I make it work?

Thanks all


Solution

  • If you have a look at the html that that's generating it will be something like this:

    <input type="button" value="Get Answer" onclick="con(".$first.", ".$last.")" />
    

    Which as you can see is not correct.

    There are a couple of issues with your code, first of all, variables names, like $first won't get evaluated to their value if they are inside single quotes.

    Try:

    echo '<input type="button" value="Get Answer" onclick="con("'.$first.'", "'.$last.'")" />';
    

    This will output :

    <input type="button" value="Get Answer" onclick="con("Butter", "Last")" />
    

    which is still not correct, as you're not passing the arguments to your javascript function correctly.

    Try:

    echo '<input type="button" value="Get Answer" onclick="con(\''.$first.'\', \''.$last.'\')" />';
    

    which should output

    <input type="button" value="Get Answer" onclick="con('Butter', 'Last')" />
    

    that hopefully works :)