2

I have the following code in php:

<?php
$apples = 123123;
echo "<td>
         <input type='button' onclick='confirmation($apples)' value='ac/in'>
      </td>";

echo('<script type="text/javascript">
           function confirmation(test) {
              var answer = confirm("Are you sure?")
              if (answer){
                  alert(test);
                  $.get("/index.php?f=func_name_to_call", 
                  {name: "John", hobby: "Programming"}, function(data) {});
              }
           }
</script>');
?>

If $apples is a number then the parameter gets passed correctly; however when it is a string, the function confirmation() is broken. Any ideas? Thanks in advance.

1
  • 1
    If you send a string, it must be treated like so. Quote it. Commented Jan 23, 2013 at 5:21

3 Answers 3

7

If you want it to pass argument as string use the below edited code

echo "<td><input type='button' onclick='confirmation(\"$apples\")' value='ac/in'></td>";

Just use \ for escaping the double quotes,and it will be considered as a string.

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

2 Comments

Alternatively, you could use json_encode($apples). It will quote the variable for you if it is a string. As well as let you pass more complicated data structures (such as an associative array) into javascript.
It will also escape the string for you as well.
2

Yes you have to use escape character \" \" in calling confirmation function because you pass integer in a integer type parameter which is without double quotes.therefore it converts the string into integer...

Comments

1
<?php
$apples = 123123;
?>
<td>
    <input type='button' onclick='confirmation(<?php echo $apples?>)' value='ac/in'>
</td>

<script type="text/javascript">
    function confirmation(test) {
        var answer = confirm("Are you sure?")
        if (answer){
            alert(test);
            $.get("/index.php?f=func_name_to_call", 
            {name: "John", hobby: "Programming"}, function(data) {});
        }
    }
</script>

you'll run into the trouble of converting all those ' into " since your echoing them by php, just an advice dont echo them, use the html markup and just escape your php

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.