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 world"; // fails
// $message="hellotom"; // works the spaces cause failure
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'];
?>
You can do something like this
<a href="DemoOne('<?php echo addslashes($message) ?>')">
<input class='btn' type='button' value='Test'>
</a>
Working Code (updated your script as well):
<script async src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
function DemoOne(text) {
$.ajax({
url: "test.php",
type: "GET",
data: {text: text}
}).done(function(data) { // data what is sent back by the php page
$('#PageView').html(data); // display data
});
}
<?php
$message="hello world"; // fails
// $message="hellotom"; // works the spaces cause failure
echo " <a href=\"javascript:DemoOne('$message');\" ><input class='btn' type='button' value='Test'></a>
<div id='PageView'></div>";
?>