0

I have a variable named $path. I want to pass this variable from PHP to a javascript function.

<button onclick='myFunctionContact(\"" . $row1['id'] . "\")'>
    <img border='0' alt='Contacts' src='".$imgpth."peoplesmall.png'>
</button>
<script>
function myFunctionContact(id) {
    window.open('!!!$path should go here!!!'+id, '', 'toolbar=no,scrollbars=yes,resizable=yes,top=200,left=500,width=400,height=400');
}
</script>

How do I get the URL in path to display inside of the function, in the desired place?

I tried printing the variable into a javascript variable and then placing that variable into the function, but the popup window no longer works when I do that.

function myFunctionContact(id) {
    var test1 = <?php echo $path; ?>;
    window.open(test1 +id, '', 'toolbar=no,scrollbars=yes,resizable=yes,top=200,left=500,width=400,height=400');
 }  

I Know I am doing it wrong, but I have no idea how. Any advice would be greatly appreciated.

4
  • 1
    Are you printing the ; at the end of that echo? Commented Nov 17, 2016 at 22:37
  • That is a typo. I'll edit to fix it. Commented Nov 17, 2016 at 23:22
  • Possible duplicate of How to pass variables and data from PHP to JavaScript? Commented Nov 18, 2016 at 7:34
  • The path needs to be a quoted string. The end result of your echoed string has to, itself, contain quotes. Commented Nov 18, 2016 at 19:03

4 Answers 4

2

I think the problem is how you are echo the path:

Instead of:

var test1 = <?php echo $path; ?>

i think it should be

var test1 = <?php echo '"'.$path.'";'; ?>
Sign up to request clarification or add additional context in comments.

2 Comments

Is there a reason it works fine with var myValue = <?php echo json_encode($path); ?>; ?
json_encode return a string with the " (double quotes) character, thats whats missing in your code.
0

You can always use a hidden input field, and set it's value to whatever you need to be used in your JS code, then grab that value of in your JS, or maybe try an ajax call to get the value you need.

1 Comment

using a hidden input field is really bad practice. It works though.
0

json_encode() fixed the problem.

var myValue = <?php echo json_encode($path); ?>;

1 Comment

Json is not meant to encode values to be inputted into a javascript variable. json !== var
0

The path needs to be a quoted string. The end result of your echoed string has to, itself, contain quotes.

Assuming $path is a string, window.open is expecting a quoted string as the parameter.

function myFunctionContact(id) {
    window.open(' . $path . ' + id, '', 'toolbar=no,scrollbars=yes,resizable=yes,top=200,left=500,width=400,height=400');
}
</script>

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.