1

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

4
  • Have you considered using ajax ? Commented Jan 25, 2016 at 12:52
  • How could I use ajax to solve this? I want the variables from PHP, because in my actual webpage they are session variables Commented Jan 25, 2016 at 12:54
  • Update echo '<input type="button" value="Get Answer" onclick="con(".$first.", ".$last.")" />'; into echo "<input type='button' value='Get Answer' onclick='con(\"$first\", \"$last\");' />"; Commented Jan 25, 2016 at 13:00
  • Thank you! If you make that an answer, I'll mark it as solved. Worked perfectly! Commented Jan 25, 2016 at 13:11

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Your answer works perfectly! Thanks for the quick response.
0

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.'");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.