i have read all the stackoverflow solutions but it didnt work.
i have some divs and when i click on them it should change and load different data from server via ajax. but whenever i click on it the page scroll to top. i have tried "return false" and preventDefault . here is my code:
$('.part').click(function(e) {
var _this = $(this);
if ($(this).attr('data-selected') == "") {
_this.html('');
var id = 76;
$.post('banners/bannerjs.php', {
'id': id
}, function(result) {
$(_this).append(result);
$(_this).attr('data-selected', 'selected');
});
} else if ($(this).attr('data-selected') == "selected") {
alert('salam');
}
return false;
});
and here is my html code:
<div class="part type<?php echo $w['TypeID']?>" style="" data-price="<?php echo $w['Price']?>" data-id="<?php echo $w['id']?>"
data-selected="<?php echo $selected?>" data-banner-selected="<?php echo $w['Display_Banner_Selected']?>"
data-banner="<?php echo $w['Display_Banner']?>">
<script type="text/javascript">
//jQuery.ajaxSetup({async:false});
if($('[data-id="<?php echo $w['id']?>"]').attr('data-selected') == "selected"){
var id = <?php echo $w['Display_Banner_Selected']?>;
}else{
var id = <?php echo $w['Display_Banner']?>;
}
$.post('banners/bannerjs.php', {'id': id}, function(result) {
$('[data-id="<?php echo $w['id']?>"]').append(result);
});
$('.<?php echo $banner['name'].$banner['id']?>').append('<div class="partPrice"><?php echo $w["Price"]?></div>');
</script>
<br>
</div>
Updated code:
<script
src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous"></script>
<script>
$(function(){
$(".part").click(function(e) {
e.preventDefault(); //this disables the default behavior of the element
var _this = $(this);
if ($(this).attr('data-selected') == "") {
_this.html('');
var id = 76;
$.post('testy.php', {
'id': id
}, function(result) {
$(_this).append(result);
$(_this).attr('data-selected', 'selected');
});
} else if ($(this).attr('data-selected') == "selected") {
alert('salam');
}
return false;
});
})
</script>
<a class="part" data-selected="">Foo</a>
Try returning false after your post:
$('.part').click(function(e) {
var _this = $(this);
if ($(this).attr('data-selected') == "") {
_this.html('');
var id = 76;
$.post('banners/bannerjs.php', {
'id': id
}, function(result) {
$(_this).append(result);
$(_this).attr('data-selected', 'selected');
return false; //added this
});
} else if ($(this).attr('data-selected') == "selected") {
alert('salam');
return false; //added this
}
return false;
});