I have made the demo below to simplify my big problem, when enter "first input", click submit, click returned"first input", it alert once. However,refresh, when enter "first input",submit, then enter "second input",submit, click "first input", browser alert TWICE when intended to run once. What's the problem? How to fix this?
Html file (index.php)
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<input id="inputtext" type="text">
<button id="submit">Submit</button>
<div id="returned_result"></div>
<script>
$("#submit").click(function(){
var content=$("#inputtext").val(); //get the value of input field
$.post("testclick2.php", {content:content}, function(result){
$("#returned_result").prepend(result);
});
$("#inputtext").val(""); //clear the input area
})
</script>
testclick2.php
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<?php
$content=$_POST["content"];
echo "<div class=\"content\">".$content."</div>"."<br>";
?>
<script>
$(".content").click(function(){
alert("clicked");
})
</script>
Try to remove your listener before you add it:
$("#submit").off('click');
$("#submit").click(function(){...}
And
$(".content").off('click');
$(".content").click(function(){...}
You are getting two alerts because you are returning twice the click
handler with the .post
response.
Basically with each additional submit you will get an additional alert.
Remove your click
handler from the POST
response and attach the event to the body
so it can handle dynamically added elements.
add this into your main <script>
section:
$('body').on('click', '.content', function() {
alert("i've been clicked once");
});
and your php
file will be only this:
<?php
$content=$_POST["content"];
echo '<div class="content">' . $content . '</div>' . '<br>';
?>
without the need to load jquery
or outputting any javascript