2

how to get a php values contain spaces with javascript? I have a php code below

<?php 
    $firstName = "my first name";
    echo "<input type='button' onclick=showFirstName(".$firstName.");>";
?>

and my script below

<script>
    function showFirstName(firstName){
    alert(firstName);
}
</script>

and that alert wont work, it is different if just like $firstName = "My". anyone have solution? Thankyou :)

2
  • 2
    wrap in quotes - ...onclick=showFirstName('".$firstName."');>"; Commented May 4, 2015 at 4:50
  • possible duplicate of pass string with spaces into javascript Commented May 4, 2015 at 4:52

4 Answers 4

1

Just add the 's properly. Try with -

echo "<input type='button' onclick=showFirstName('".$firstName."');>";
Sign up to request clarification or add additional context in comments.

1 Comment

Beat me to it, but yeah, missing single quotes so it's trying to do: showFirstName(my first name); - which won't work as "my first name" is not inside quotes.
1

You need to put single quotes when call showFirstName method

<?php 
    $firstName = "my first name";
    echo "<input type='button' onclick=showFirstName('".$firstName."');>";
?>

Comments

0

Try this,

<?php 
    $firstName = "my first name";
    echo "<input type='button' onclick='showFirstName(\"".addslashes($firstName)."\")'>"; 
?>

Comments

0

Put onclick function calling in double quotes like this:

$firstName = "my first name";
echo "<input type='button' onclick=\"showFirstName('$firstName');\">";

1 Comment

thankyou @Sanjay this work form me, I'm just missing the \" \" in the onclick function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.