joe martin
joe martin

Reputation: 93

Posting a javascript variable to PHP.

I have a javascript function to count the number of clicks. I wish to post the variable storing the count to PHP. I'm unsure why when I submit the form, the count is not echoed out. Below is the HTML file.

<html> 
<head>
<title> js php </title>
<script>
    var cnt=0;
    function CountFun(){
    cnt=parseInt(cnt)+parseInt(1);
    var divData=document.getElementById("showCount");
    divData.innerHTML="Number of Downloads: ("+cnt +")";//this part has been edited

    }
</script>
</head>
<body>

<div id="showCount"></div>
<form action "submitClicks.php"id="form">
    <input type="hidden" name="numberOfClicks" />
    <input type="button" id="btnClick" value="Click me" onclick="CountFun()"/>
    <input type="submit" value="Submit Clicks" />
</form>

</body>
</html>

Then this is my submit clicks page:

<?php
    $number_of_clicks = $_POST["cnt"];
    echo $number_of_clicks;
?>

Does this implementation look correct to you as when I click submit clicks, nothing happens. I'm expecting the number of clicks to be echoed.

Upvotes: 1

Views: 70

Answers (2)

Basem
Basem

Reputation: 261

Try this code:

<html> 
<head>
<title> js php </title>
    <script>
        var cnt=0;
        function CountFun(){
        cnt=parseInt(cnt)+parseInt(1);
        var divData=document.getElementById("showCount");
        divData.value=cnt;//this part has been edited
        document.getElementById("JustShow").innerHTML= cnt;
        }
    </script>
</head>
<body>


<div id="JustShow"></div>
<form action="submitClicks.php" id="form" method="post">
    <input type="hidden" id="showCount" name="cnt" value="0" />
    <input type="button" id="btnClick" value="Click me" onclick="CountFun()"/>
    <input type="submit" value="Submit Clicks" />
</form>

</body>
</html>

Upvotes: 0

Carson Crane
Carson Crane

Reputation: 1217

<form action "submitClicks.php"id="form">

Should be:

<form action="submitClicks.php" id="form" method="post">

And shouldn't you have something like:

In HTML:

<input id="count" type="hidden" name="cnt" value="">

In your Javascript CountFun function:

document.getElementById('count').value = cnt;

Upvotes: 1

Related Questions