how to save data on javascript form

I have those 2 function on JS :

<script>
    function inc(elem)
    {
        elem.value++; 
    }
    function dec(elem)
    {
        if(elem.value>1)
        {
            elem.value--;
        }
    }
</script>

And this form in html:

<form method="POST" action= "tameio.php"  >
<input type="hidden" value="0" id="counter" name="counter">
<input type = "submit" value = "NextPage" name = "submit" onClick="inc(document.getElementById('counter')); ">
<input type = "submit" value = "PreviousPage" name = "submit" onClick="dec(document.getElementById('counter'));">
</form>

And here is the php :

<?php
if(isset($_POST['submit']))
{
    echo $_POST['counter'];
    if($_POST['submit'] == 'NextPage'){
    ...
        }
}
?>

So the problem is that after i click NextPage button, 0 goes 1 but it is not stored in the form so it goes 0 again on html . If i reclick it it is going to send 1 again. Should I use ajax instead ?

Upvotes: 0

Views: 620

Answers (2)

Nils
Nils

Reputation: 446

There is no need to do any of that,

<form method="POST" action= "tameio.php"  >
<input type="hidden" value="<?=$current_page?>" id="counter" name="counter">
<input type = "submit" value = "NextPage" name = "submit" onClick="inc(document.getElementById('counter')); ">
<input type = "submit" value = "PreviousPage" name = "submit" onClick="dec(document.getElementById('counter'));">
</form>

And in PHP:

<?php
if(isset($_POST['submit']))
{
    if($_POST['submit'] == 'NextPage')
    {
        $current_page = $_POST['counter'] + 1;
    } else {
        $current_page = $_POST['counter'] - 1;
    }
} else {
    $current_page = 1;
}
// Fetch the page data based on the current page
...

?>>

But I would recommend you do this with a GET instead of a post.

<a href="tamieo.php?page=<?=$current_page - 1?>">Previous Page</a> |
<a href="tamieo.php?page=<?=$current_page + 1?>">Next Page</a>

And in PHP:

<?php

    if(isset($_GET['page']) && $_GET['page'] > 0)
        $current_page = (int) $_GET['page'];
    else
        $current_page = 1;

Upvotes: 1

Suresh Kamrushi
Suresh Kamrushi

Reputation: 16076

Try like this-

<script>
    function inc(elem)
    {
        document.getElementById('counter').value = elem.value +1; 
    }
    function dec(elem)
    {
        if(elem.value>1)
        {
            document.getElementById('counter').value = elem.value -1;
        }
    }
</script>

Upvotes: 0

Related Questions