Reputation: 235
I was just wondering if there is a better way to write down this PHP vars passed to a javascript function called inside a PHP print.:
while($nav = mysqli_fetch_array($nav_db)){
print '<li>
<a href="#" onclick="getProductPage('.$nav['id'].', \''.$name.'\')">
'.$nav['Data'].'
</a>
</li>';
}
where
$nav['id']
is an INTEGER so I don't need extra '' for the JS, and
$name
is not an INTEGER so I need those \' \' for the JS.
Especially this step:
getProductPage('.$nav['id'].', \''.$name.'\')
Thank you
Upvotes: 1
Views: 89
Reputation: 91744
You should use json_encode
to pass variables from php to javascript. That will make sure that there are no unescaped characters that can break your javascript.
So json_encode($name)
instead of $name
, etc.
For your example:
print '<li>
<a onclick="getProductPage(' . (int) $nav['id'].', ' . json_encode($name) . ')">
' . htmlspecialchars($nav['Data']) . '
</a>
</li>';
Upvotes: 1
Reputation: 101
have you considered using jquery and ajax send data to a php file and send back json_encode array to javascript?
example
after you send ajax call to php with datatype json, send back vars like this
$data['id'] = nav['id'];
echo json_encode($data);
or just $nav['id']
echo json_encode($nav)
in your javascript. on success, you can retrieve the id value like this
ajax{(
blah,
blah,
...
success(msg){
alert(msg.id)
}
})
you can access the var as an object the code above will alert the value of the id. you can assign msg.id to a javascript var or pass it to a function ...ect
Upvotes: 0
Reputation: 18833
<?php while($nav = mysqli_fetch_array($nav_db)): ?>
<li>
<a onclick="getProductPage(<?php echo $nav['id']; ?>, '<?php echo $name; ?>')">
<?php echo $nav['Data']; ?>
</a>
</li>
<?php endwhile; ?>
You should break out of PHP to write html. It is cleaner this way. Also, you had a rogue </span>
in there and no need for a <br>
in a <li>
menu.
Also, an a
tag should have an href
value in there, even if it is #
or javascript:void(0)
or something.
Upvotes: 3