Arthur Walker
Arthur Walker

Reputation: 125

Passing a PHP variable into a Javascript funtion

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.

Upvotes: 0

Views: 77

Answers (4)

ppovoski
ppovoski

Reputation: 4773

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>

Upvotes: 0

Arthur Walker
Arthur Walker

Reputation: 125

json_encode() fixed the problem.

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

Upvotes: 0

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.'";'; ?>

Upvotes: 2

Saleh Al Eit
Saleh Al Eit

Reputation: 1

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.

Upvotes: 0

Related Questions