1

I am trying to pass a string into a javascript from PHP but am failing miserably. From testing I can see its the whitespace that is making my test fail. How do I encode to pass to javascript properly I tried %20 and a few more nothing seems to work.

Full Source

  <script async  src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">

function DemoOne(text) {
 $('#PageView').load('test.php?text=' + text);
}
</script>


<?php
$message="hello";

echo "  <a href=\"javascript:DemoOne('$message');\" ><input class='btn' type='button' value='Test'></a>     
<div id='PageView'></div>";

?>

Test Output test.php

<?php
echo $_GET['text'];
?>      

FOLLOW UP

Adding the code below still fails it seems only removing spaces will allow this above example to work.

a href=\"javascript:DemoOne(".htmlspecialchars(json_encode($message)).");\" ><input type='button' value='Submit'></a>   
<div id='PageView'></div>
1

1 Answer 1

2

It's got nothing to do with spaces. And you haven't given us the full code. I'm guessing that HTML is inside an echo? If so, you need to do this:

echo "<a href=\"javascript:DemoOne(".htmlspecialchars(json_encode($message)).");\" ><input type='button' value='Submit'></a>   
<div id='PageView'></div>";

i.e. json_encode any data that your pass to JavaScript. You also need to escape it for HTML since it's in an attribute as opposed to a <script> tag.


You also need to escape the query param for the URL.

I amended your code to fix the encoding issues:

  <script async  src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">

function DemoOne(text) {
 $('#PageView').load('test.php?text=' + encodeURIComponent(text));
}
</script>


<?php
$message="hello";

echo "  <a href=\"javascript:DemoOne(".htmlspecialchars(json_encode($message)).");\" ><input class='btn' type='button' value='Test'></a>     
<div id='PageView'></div>";

Alternatively, let jQuery do the escaping:

function DemoOne(text) {
 $('#PageView').load('test.php', {text:text});
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the help I amended above to add full source code it still fails however. If I make the $message ="hello" (no spaces will work fine) any other ideas where I am going wrong?
@CliveAtkins That's not the full code. How are you outputting that HTML? Paste the entire .php file if you're not sure.
@CliveAtkins Ah...okay, you also need to escape the URL param. You can do that in JS with encodeURIComponent. I added a full example to my answer.

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.