I have a problem with jQuery Ajax. I have a load function:
main file which load a first page to #my_div
ajax.php file to load next or prev page to #my_div.
I will add that this is a very simplified pattern, I ultimately have many functions and things. I present a basic problem here.
Main file:
<div>
<div id="my_div"></div>
<button id="prevstep">back</button>
<button id="nextstep">next</button>
</div>
<script>
jQuery("#my_div").load("http://localhost/ajax.php?section=page1");
</script>
ajax.php file:
<?php
if ($_GET["section"] == "page1") {
?>
<div>something part 1</div>
<script>
$("#prevstep").on("click", function() {
console.log("test1 back");
jQuery("#my_div").load("http://localhost/ajax.php?section=page0");
});
$("#nextstep").on("click", function() {
console.log("test1 next");
jQuery("#my_div").load("http://localhost/ajax.php?section=page2");
});
</script>
<?php
} elseif ($_GET["section"] == "page2") {
?>
<div>something part 2</div>
<script>
$("#prevstep").on("click", function() {
console.log("test2 back");
jQuery("#my_div").load("http://localhost/ajax.php?section=page0");
});
$("#nextstep").on("click", function() {
console.log("test2 next");
jQuery("#my_div").load("http://localhost/ajax.php?section=page2");
});
</script>
<?php
}
?>
Site working correctly (jquery library is correct, console doesn't return any errors), but when I switch between page1 and page2 - console return strange values after loading again the same page.
For example:
- Load main file, console nothing return - ok
- Click 'next' button, console return:
test1 next
- Click 'back' button (to back from page2 to page1), console return:
test1 back
test2 back
- Click again 'next' button (to go to page2), console return:
test1 next
test2 next
- Click again 'back' button (to back to page1), console return:
test1 back
test2 back
test2 back
test2 back
- Third time I click 'next' button, console return:
test1 next
test2 next
test2 next
test2 next
- Third time I click 'back' button, console return:
test1 back
test2 back
test2 back
test2 back
test2 back
test2 back
test2 back
test2 back
Scripts duplicate each time the next page loads again.
How to resolve this problem?
BTW. I using a jQuery v2.2.3.