Search code examples
phpjavascriptundefined-function

Java Script Function is not Defined


I am getting the following error from the chrome developer tool

Uncaught ReferenceError: searchRequests is not defined searchProcess.php:174 onclick.

When I click on hyperlink produced from engine.php, I don't get the alert from the searchRequests function. I'm not sure what the problem is, I appreciate any advice given. Here is my code:

searchProcess.php

<?php
include '../include/engine.php';
?>

<html>
<head>
<script type="text/javascript" src="../jQuery.js"></script>
<script type="text/javascript">
$( document ).ready(function() {

    var instrID;
    var cat;

    $(window).load(function(){

    });

    var newheight = $(window).height();


    function searchRequests(instr)
    {

        alert("in searchResults");
        instrID = instr;
        alert(instrID);

    }

    });

</script>
</head>
<body>
<?php
    drawSearchResults($var1, $var2, $var3, $var3, $var4); 
?>
</body>
</html>

engine.php

<?php
function drawSearchResults($var1, $var2, $var3, $var4, $var5)
{
while($row = mysql_fetch_assoc($result))
{
    echo ("<tr>");
        echo ("<td id='InstrumentID'><a href='javascript:void(0);' onclick='searchRequests($row[InstrumentID])'>$row[InstrumentID]</a></td>");
    echo ("</tr>");
}
?>

Solution

  • The problem is that the function searchRequests is not in scope outside of the $(document).ready(). Move it outside of $(document).ready().

    In general you shouldn't embed your javascript in the html. Much nicer:

    $('#InstrumentID a').click(someFunctionThatIsInScope);
    

    And you can put that code in the $(document).ready() block. In addition the function you call will get an event object that you can use to get any values you might need from the markup.