Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I pass a string as a parameter in a Javascript function?

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.

like image 477
unwise guy Avatar asked Feb 24 '26 01:02

unwise guy


2 Answers

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.

like image 67
Yogesh Suthar Avatar answered Feb 25 '26 14:02

Yogesh Suthar


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...

like image 34
gcsforum Avatar answered Feb 25 '26 15:02

gcsforum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!