2

I have some images on a page and when clicking one of them, POST data is sent, the page refreshed and a Javascript variable is incremented. My question is how do I get the JS variable NOT to reset to the value I initiated it to when the page is reloaded? I have earlier also tried saving the variable using localstorage, but the variable is still reset - which is logical as I have the initialisation in the same document, but I don't know how I could do otherwise.

I am new to Javascript and would like to keep things as simple as possible (and get a dummy reply if I may).

Below is my code, with the relevant Javascript at the start of the body (also have some irrelevant php in separate document):

<?php
$subtest_nr = "7";
$counter = 0;
require_once('php.php');
?>

<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link rel="stylesheet" href="styles.css">
<script src="jquery-3.1.1.min.js"></script>
<script src="scripts.js"></script>
</head>

<body>
<script>
var counter = 0;
$(document).ready(function(){
    $("img").click(function(){
        counter += 4;
        $("#test").text(counter); //for testing
    });
    $("#test").text(counter); //for testing
});

jQuery(function($) {
    // Hide / suppress the submit button
    $('input[type="submit"]').closest('div').hide();
    // Bind to change event for all radio buttons
    $('input[type="radio"]').on('change', function() {
        // Submit the form ("this" refers to the radio button)
        $(this).closest('form').submit();
    });
});
</script>

<div class="main">
    <div id="test"></div>
    <?php $data = getData($subtest_nr); ?>
    <form id="myform" method="post">
    <div class="four_images">
            <div class="flex-item">
                <input type="radio" name="image" value="7.11" id="alt1" class="hidden">
                <label for="alt1"><img src="images/<?php echo $data[$counter+0]; ?>"></label>
            </div>
            <div class="flex-item">
                <input type="radio" name="image" value="7.12" id="alt2" class="hidden">
                <label for="alt2"><img src="images/<?php echo $data[$counter + 1]; ?>"></label>
            </div>
            <div class="flex-item">
                <input type="radio" name="image" value="7.13" id="alt3" class="hidden">
                <label for="alt3"><img src="images/<?php echo $data[$counter+2]; ?>"></label>
            </div>
            <div class="flex-item">
                <input type="radio" name="image" value="7.14" id="alt4" class="hidden">
                <label for="alt4"><img src="images/<?php echo $data[$counter+3]; ?>"></label>
            </div>
            <div>
                <input type="submit" name="save" value="Save Image Selection">
            </div>
    </div>
    </form>
</div>

</body>
</html> 

I can add that I want to keep the page refresh because later on I want to pass the incremented variable on to php without having to post it using Ajax or such like. (Hoping this will make things simpler for me as a beginner.)

4
  • 1
    You would need to use localStorage to hold a value and you read it when the page initializes or even better, have PHP hold the value and write it to the page Commented Oct 3, 2016 at 18:26
  • 1
    You are on the right track using localStorage, all you need to do is check if it exist before initialization to it's starting value so it's not reset. You can also use a session in PHP. Commented Oct 3, 2016 at 18:27
  • @SpencerWieczorek Ah, of course! Thanks! Will try this. Commented Oct 3, 2016 at 18:28
  • @epascarella How do I make PHP hold it? The thing is, I actually want the counter as a PHP variable later on, so maybe this would be a good solution for me. Commented Oct 3, 2016 at 18:31

2 Answers 2

2

Here is a pretty basic example of how you could use localStorage and set up simple session getters/setters to manipulate the data over page refreshes.

function setSessionItem(name, value) {
    var mySession;
    try {
        mySession = JSON.parse(localStorage.getItem('mySession'));
    } catch (e) {
        console.log(e);
        mySession = {};
    }

    mySession[name] = value;

    mySession = JSON.stringify(mySession);

    localStorage.setItem('mySession', mySession);
}

function getSessionItem(name) {
    var mySession = localStroage.getItem('mySession');
    if (mySession) {
        try {
            mySession = JSON.stringify(mySession);
            return mySession[name];
        } catch (e) {
            console.log(e);
        }
    }
}

function restoreSession(data) {
    for (var x in data) {
        //use saved data to set values as needed
        console.log(x, data[x]);
    }
}



window.addEventListener('load', function(e) {
    var mySession = localStorage.getItem('mySession');
    if (mySession) {
        try {
            mySession = JSON.parse(localStorage.getItem('mySession'));
        } catch (e) {
            console.log(e);
            mySession = {};
        }
        restoreSession(mySession);
    } else {
        localStorage.setItem('mySession', '{}');
    }

    setSessionItem('foo', Date.now()); //should change each time

    if (!mySession.bar) {
        setSessionItem('bar', Date.now()); //should not change on refresh
    }
}, false);
Sign up to request clarification or add additional context in comments.

2 Comments

Would you mind commenting this and also describing how it should be called in my script?
Anytime you set the counter you should also save the value value to local storage using the setSessionItem method. When the page refreshes the restoreSession method should be called. Inside of this method you can set define logic to use the values saved before the refresh however you like. You can also use the getSessionItem to get a single item/value from the session object you saved.
1

You can store the variable prior execution of the post request into localStorage and read the counter variable from the localStorage when the page loads. localStorage Browser Support

Or you can send the counter variable as an URL parameter, and set the counter via PHP.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.