I have made a simple script to call JSON file and show on the website.
Unfortunately it shows double of the result. The problem is caused by the pictures. If I remove them the text is shown only once as I want it.
Here is the script
$(function () {
$('#members p, #members p span, #main_content span').on('click', function () {
var attr = $(this).attr('data-number');
if (typeof attr !== typeof undefined && attr !== false) {
var number = $(this).data('number');
console.log(number);
$.ajax("members.json", {
dataType: 'json',
success: function (response) {
$(".images_ajax").css('display', 'block');
$(".images_ajax_sub").append(response[number].img + response[number].text);
}
}),
$(function () {
$('.close_ajax').click(function () {
$(".images_ajax_sub h1, .images_ajax_sub p, .images_ajax_sub .iMembers").remove();
$(".images_ajax").css('display', 'none');
})
})
}
})});
If I remove the image from the JSON file then I get only one undefined as the image is missing not two.
Here is the part of the JSON file
"name": {
"img": "<div class=\"iMembers\"><img src = \"../images/images/images_of_members/some.jpg\"></div>",
"text": "<p>some text</p>"
}
My best guess is that your AJAX call gets fired twice. Take a look at the DOM nodes that the click
handler is being bound to:
$('#members p, #members p span, #main_content span').on('click ...
^^^^^^^^^^ ^^^^^^^^^^^^^^^
Since you don't prevent event bubbling, a click on a span
triggers the bound event handler, then bubbles up the DOM and triggers again for the span
's parent node: p
. Thus, try binding to either or.