0

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'];
?>   
1
  • Just out of interest, why are you trying to put a clickable anchor link around a button? That does not make much sense to me Commented Apr 6, 2016 at 1:10

1 Answer 1

1

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>";

?>

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

Comments

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.