Reputation: 45
I need help to display content in a popup div using ajax when the element is clicked
<script type='text/javascript'>
$(document).ready(function() {
$('.myDiv').click(function() {
//Load a php file content from DB next to the clicked div
});
});
</script>
<div id="1" class="myDiv">Click me 1</div>
<div id="2" class="myDiv">Click me 2</div>
<div id="3" class="myDiv">Click me 3</div>
<div id="4" class="myDiv">Click me 4</div>
Thanks a lot
Upvotes: 1
Views: 274
Reputation: 167250
You can use something like this:
$(document).ready(function() {
$('.myDiv').click(function() {
// Uncomment the lines below to make the AJAX function work. For demo, I have just
// inserted a <span>.
// $.get("/url", function (res) {
$(this).append('<span>' + "This is AJAX Response." + '</span>');
// });
});
});
* {font-family: 'Segoe UI';}
.myDiv {cursor: pointer; position: relative;}
.myDiv span {position: absolute; margin-top: -15px; top: 50%; height: 20px; border: 1px solid #999; padding: 5px 10px; margin-left: 15px;}
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<div id="1" class="myDiv">Click me 1</div>
<div id="2" class="myDiv">Click me 2</div>
<div id="3" class="myDiv">Click me 3</div>
<div id="4" class="myDiv">Click me 4</div>
Update
If you wanna remove the previous <span>
s after an AJAX call, you can do so with the following script:
$(document).ready(function() {
$('.myDiv').click(function() {
// Uncomment the lines below to make the AJAX function work. For demo, I have just
// inserted a <span>.
// $.get("/url", function (res) {
$(".myDiv span").remove();
$(this).append('<span onclick="$(this).remove(); event.stopPropagation(); return false;">' + "This is AJAX Response." + '</span>');
// });
});
});
* {font-family: 'Segoe UI';}
.myDiv {cursor: pointer; position: relative;}
.myDiv span {position: absolute; margin-top: -15px; top: 50%; height: 20px; border: 1px solid #999; padding: 5px 10px; margin-left: 15px;}
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<div id="1" class="myDiv">Click me 1</div>
<div id="2" class="myDiv">Click me 2</div>
<div id="3" class="myDiv">Click me 3</div>
<div id="4" class="myDiv">Click me 4</div>
Upvotes: 2