'Not able to call a JavaScript function from PHP code?
How do I call a JavaScript function from href tag in html? I've created a few tabs and when a user clicks on one of them the href along with JavaScript function should get called.
<?php if($order == 1){ ?>
<li class="cat-one">
<a href="javascript:void(0)" onclick="loadProducts(<?php echo $categoryId ?>)">
<?php echo $categoryName ?>
</a>
</li>
<?php } ?>
This is my JavaScript:
function loadProducts($categoryId)
{
alert("Hello World!");
return false;
}
Why doesn't the alert trigger in my function? I am running 2 jQueries on the same page.
Solution 1:[1]
Try:
<script type="javascript" >
function loadProducts(categoryId)
{
alert("Hello World!" + categoryId);
return false;
}
</script>
And also:
<a href="#" onclick="loadProducts(<?php echo $categoryId ?>); return false;" >
<?php echo $categoryName ?>
</a>
Solution 2:[2]
I just checked the JavaScript, you make a mistake while declaring script tag, the correct code is below
<script type="text/javascript" >
function loadProducts($categoryId)
{
alert("Hello World!");
return false;
}
</script>
Solution 3:[3]
From your script above I really don't see nothing wrong with the JavaScript. Try debugging your PHP first to see if the expected value like ($categoryId) is exactly what you expect to be.
Your are missing something also from the script tag
<script type="text/javascript">
// Your script goes here...
</script>
Solution 4:[4]
May be your php script has some errors, Try this example also.
<html>
<body>
<script type= "text/javascript">
function loadProducts(catid){
alert(""Hello World!"+catid);
return false;
}
</script>
<?php if($order == 1){ ?>
<li class="cat-one">
<a href="javascript:void(0)" onclick="loadProducts(<?php echo $categoryId ?>)"><?php echo $categoryName ?> </a>
</li>
</body>
</html>
Solution 5:[5]
From what I can tell without actually running this code, you can fix a few semi-colons on lines 3 and 4, change the href, and put the parameter for loadProducts in quotes. Try this:
<?php if($order == 1){ ?>
<li class="cat-one">
<a href="#" onclick="loadProducts('<?php echo $categoryId; ?>')">
<?php echo $categoryName; ?>
</a>
</li>
<?php } ?>
Let me know if it works out for you.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Sumair Zafar |
| Solution 3 | Robert Wilson |
| Solution 4 | Anish |
| Solution 5 | theEdgeOfChaos |
