简体   繁体   中英

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

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 :)

Here is your solution

JavaScript Code:

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

PHP and HTML code:

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

when you pass the value to the javascript function through php you must pass the value in 'single quote' or "double quote" like onclick=con("'.$first.'","'.$last.'");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM