Reputation: 902
I'm using ajax post in jquery by which a portion of page is built. But the problem is that it is running only once. Here is my code below
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
var res;
function on(id){
var dat = '';
$.ajax({
url: 'ajax.php', //This is the current doc
type: "GET",
data: {a: id },
success: function(data){
res = data;
data += '<div class="white" id="white" style="display:none">';
var result = $.parseJSON(res);
$.each(result, function(k, v) {
//display the key and value pair
dat += "<a href = 'javascript:void(0);' onclick='on("+ k +")'>"+ v+"</a><br>";
});
document.write(dat);
}
});
}
</script>
</head>
<body>
<a href="javascript:void(0);" onclick="on(8);">Get JSON data</a>
</body>
</html>
After clicking on first time the page keeps on loading after showing the result. And after second click it shows error ReferenceError: on is not defined
.
In actual it should happen that on every click on href id is passed in jquery function and based on that sql queries are run which returns data and new page data is displayed.Everytime on href click this should happen.
Upvotes: 0
Views: 856
Reputation: 167182
You should really reconsider your event handling:
$(function() {
var res;
$(".getJson").click(function (e) {
e.preventDefault();
var dat = '';
var id = $(this).data(id);
$.ajax({
url: 'ajax.php', //This is the current doc
type: "GET",
data: {a: id},
success: function(data) {
res = data;
data += '<div class="white" id="white" style="display:none">';
var result = $.parseJSON(res);
$.each(result, function(k, v) {
//display the key and value pair
dat += "<a href = 'javascript:void(0);' onclick='on(" + k + ")'>" + v + "</a><br>";
});
$("#output").append(dat);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<a href="javascript:void(0);" data-id="8" class="getJson">Get JSON data</a>
<span id="output"></span>
Upvotes: 1