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.)
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.