0

I have a JS function that is embedded inside of PHP. I declare the function first and then call it. I keep getting the error downloadCSV is not a function with the below code:

<?php
include_once "orders.php";
$body = "";
$body .= "<form method = 'post' action='" . $_SERVER['PHP_SELF'] . "'><input type='text' placeholder='begin date' name='begin_date'>
          <input type='text' name='end_date' placeholder='end date'><input type='submit' name='date_range'></form>";
if(isset($_POST['date_range']))
{
    $orders = new Orders();
    $body .= $orders->displayOrders($_POST['begin_date'], $_POST['end_date']);
    $head = '<script>
        //document.getElementById("downloadCSV").addEventListener("click", downloadCSV);
        function downloadCSV(x,y)
        {
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    console.log( this.responseText );
                }
            };
            xhttp.open("POST", "downloadcsv.php", true);
            xhttp.send();
        }
    </script>';
    $body .= "<form name='createCSV' id='createCSV'><input type='button' id='downloadCSV' value='download csv' onclick='downloadCSV(\"" . $_POST['begin_date'] . "\", \"" . $_POST['end_date'] . "\");' /></form>";
}

?>

<html>
<head>
<?php
echo $head;
?>
</head>
<body>
<?php

echo $body;

?>

</body>
</html>

I cannot figure out why I keep getting the error when I clearly declare the function before calling it

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
sjw0525
  • 329
  • 2
  • 17
  • 1
    Have you tried naming the function something different to your element ID? Element IDs kind of become global variables in some browsers. In any case, this doesn't seem to be a PHP or Ajax problem, so I think you can remove those tags from your question. – nnnnnn Oct 27 '17 at 02:24
  • What is the output of PHP? Your code _looks_ fine to a quick glance, but there's no substitute for the actual output. – hunteke Oct 27 '17 at 02:26
  • Can you post your code in the view-source mode of your browser? – Văn Quyết Oct 27 '17 at 02:27
  • @nnnnnn that was it. I renamed the id to something different than the function name and it works. Thanks! – sjw0525 Oct 27 '17 at 02:27
  • [This question](https://stackoverflow.com/questions/17586348/javascript-function-not-called-when-id-and-function-name-same) asks about function names being the same as IDs, but its answer doesn't provide any details. The linked duplicate has more information. – nnnnnn Oct 27 '17 at 02:32
  • why not just write your js in the html instead of php? That removes a whole part of your issue. – Daniel Tate Oct 27 '17 at 02:43

0 Answers0