click event not call event after load `btn` with `ajax` - php

I have a page that loaded with ajax complete,
I have buttons on the page (load with ajax), so I want after click the button run an alert event,
I try bind,delegate,live,on Event to attach the Event to handler but no result.
I'm try add test btn manually and that call the event but the buttons that load via ajax not call Event.
My html code:
<body>
<a href='#' class='insert_cm'>test btn</a>
<div class="header"></div>
<div class="wrap">
<div class="rightmenu"></div>
<div class="content">
</div>
</div>
</body>
my JQuery code:
$(function(){
$(".header").load("header.html");
$(".rightmenu").load("sidebar.html");
$.ajax({
type:'POST',
url:'timeline.php',
success:function(data){
$(".content").html(data);
}
});
//insert comment after click the cm-btn
$( ".insert_cm" ).live( "click", function() {
alert( "User clicked on 'foo.'" );
})
});
and the php code:
<?php
include('db_inc.php');
include("myfunc.php");
$functionId=$_POST[functionId];
switch($functionId){
case "":
$music_query = $connection->query("SELECT * FROM music LIMIT 15") or die($connection->error);
while($music = $music_query->fetch_array()){
$music_id=$music['msuic_id'];
$music_thumb =$music['music_thumb'];
$music_name=$music['file_name'];
echo "<div class='music-item'>
<div class='music-avatar'>
<img src=admin/thumb/$music_thumb alt='avatar'>
</div>
<div class='music-post'>
<h3> $music_name <a href='#' class='like_music' >لایک</a></h3>
<p> $music_composer </p>";
$comment_query=$connection->query("SELECT * FROM comments where f_music_id = '$music_id'") or die($connection->error);
while($comments = $comment_query->fetch_array()){
$username = get_username($comments['f_user_id']);
echo "
<div class='username_comment'>
<h4> $username <span>:</span></h4>
$comments[comment];
</div>
";
}
echo "<textarea id='txt_cm' name='txt_cm'></textarea>
<a href='#' class='insert_cm'>insert comment</a>";
}
}
?>

always use $(document).on() for dynamically created element if you want to bind an event to them.
$(document).on("click", ".insert_cm", function() {
alert( "User clicked on 'foo.'" );
return false;
});
the event binder should sit on document level so that it recognize whenever there are more elements added to DOM
more info on $(document).on() : Is it possible to capture keydown globally on dynamically added text inputs?

Use .on() with updated syntax in the jQuery version > 1.8:
$(".content").on( "click",".insert_cm", function() {
alert( "User clicked on 'foo.'" );
})
Syntax:
$(selector/Closest parent).on(event,target,function(){});
That is called EventDelegation!
Where .content reffers to the closest parent element, you can also use document, document.body too.

Try:
$(document).on("click",".insert_cm",function() {
alert("User clicked on 'foo.'");
return false;
});

Related

How to stop a page that is refreshing every one second if the bootstrap modal is active or on show?

I have two php pages, first page is where I display the data from a MySQL database using Ajax that refreshes every 1 second, the second page contains the php code to fetch the data from the database wherein I have a bootstrap modal that shows the other information of every record.
First php page:
<div class = "container">
<div id = "show_MySql_table_data"></div>
</div>
<script>
//Ajax script for displaying the record every 1 second
var interval = 1000;
function displayData() {
$.ajax ({
url: "details_info.php",
type: "POST",
data: {},
dataType: "html",
success: function(data) {
$("#show_MySql_table_data").html(data);
},
complete: function (data) {
setTimeout(displayData, interval);
}
});
}
setTimeout(displayData, interval);
</script>
Second php page:
<?php
$cn = mysqli_connect("localhost","root","","testdb");
$sql = "SELECT * FROM tblsample";
$result = mysqli_query($cn,$sql);
if (mysqli_num_rows($result) > 0 ) {
while($rows = mysqli_fetch_array($result)) {
$name = $rows['Name'];
$address = $rows['Address'];
echo "<tr>";
echo "<td>" . $name . "</td>";
echo "<td>" . $address . "</td>";
echo "<td><button class = 'toggleDetailsModal btn btn-info'>More Info</button></td>";
echo "</tr>";
}
}
?>
<!-- Modal -->
<div class = "modal" id = "detailsModal">
<div class = "modal-dialog">
<div class = "modal-content">
<div class = "modal-header">
<h5 class = "modal-title">Details</h5>
<button class = "close" data-dismiss = "modal">×</button>
</div>
<div class = "modal-body">
More Information here....
</div>
<div class = "modal-footer">
<button class = "btn btn-danger btn-sm" data-dismiss = "modal">Close</button>
</div>
</div>
</div>
<script> //this is included in the second php page
$(".toggleDetailsModal").on("click", function(e) {
e.preventDefault();
$("#detailsModal").modal('show');
});
</script>
What's happening is when I click More Info button, the modal automatically close and my screen was grayed out.
How can I stop the automatic refreshing of the page (every 1 second) when I click the More Info button and if the Modal is active or in show mode?
Thank you in advance.
There are various ways to determine whether the modal is open or closed, one option is to hook into the bootstrap modal's events:
https://getbootstrap.com/docs/4.0/components/modal/#events
show.bs.modal
This event fires immediately when the show instance method is called. If caused by a click, the clicked element is available as the relatedTarget property of the event.
hide.bs.modal
This event is fired immediately when the hide instance method has been called.
Adding to your existing code:
var modalActive = false;
$("#detailsModal").on("show.bs.modal", function() {
modalActive = true;
});
$("#detailsModal").on("hide.bs.modal", function() {
modalActive = false;
});
function displayData() {
if (!modalActive) {
$.ajax ...
} else {
setTimeout(displayData, interval);
}
}

ajax and php and sql

I have a list of items on my page from a DB table
I am trying to change the glyphicon when checked
<div class="div1">
<span id=".<?php echo $row['id']; ?>" style="color:black;" class="glyphicon glyphicon-eye-open"> </span>
</div>
this is the script on the top of my page:
<script>
$(document).ready(function(){
$(".div1").click(function(){
$(".div1").load("clicked.php");
});
});
</script>
clicked.php looks like:
<span id="<?php echo $row['id']; ?>" style="color:black;" class="glyphicon glyphicon-ok"> </span>
The problom is the when I click on one item - all the items change there glyphicons
What am I doing wrong?
You just have to remove & add new class:
$(document).ready(function(){
$(".div1").click(function(){
$(this).children('span').removeClass('glyphicon-eye-open');
$(this).children('span').addClass('glyphicon-ok');
//Here you can add ajax call
});
});
There is no need to go all the way to the server to get a new span when all you are doing is removing a class and adding a new class to a span.
Also using the right scope, $(this) will stop it effecting all your div1 elements.
<script>
$(document).ready(function(){
$(".div1").click(function(){
//$(".div1").load("clicked.php");
$(this).children('span').removeClass('glyphicon-eye-open');
$(this).children('span').addClass('glyphicon-ok');
});
});
</script>
And to make the code toggle from one to another on each click
<script>
$(document).ready(function(){
$(".div1").click(function(){
if ( $(this).children('span').hasClass('glyphicon-ok') ) {
$(this).children('span').removeClass('glyphicon-ok');
$(this).children('span').addClass('glyphicon-eye-open');
} else {
$(this).children('span').removeClass('glyphicon-eye-open');
$(this).children('span').addClass('glyphicon-ok');
}
});
});
</script>

My jQuery .click function only works on the last div generated by a php function

I'm working on a portfolio for someone who isn't very technically proficient at the moment. He is going to need to regularly add new content to his portfolio, which means that either he is going to need to learn how to hard code new buttons, text, and pictures into his website, or I'm going to need to regularly do this for him.
My current design for the website includes a php script that automatically populates a navigation bar based on the contents of a directory. My goal is that when a user clicks on one of the navigation buttons, it will trigger an ajax event that calls a php script to load all of the images from that particular event into my main content div. Here is the script for the nav bar:
<div id="eventsbar">
<div id="eventslistleft">
<?php
$eventlist = preg_grep('/^([^.])/', scandir('events'));
foreach($eventlist as $i => $event){
if($i == 0 || $i % 2 == 0){
echo '<div class="eventbutton" id='.$event.'><img src="/events/'.$event.'/0.jpg"></div>';
}
}
?>
</div>
<div id="infobutton">
</div>
<div id="eventslistright">
<?php
$eventlist = preg_grep('/^([^.])/', scandir('events'));
foreach($eventlist as $i => $event){
if($i != 0 && $i % 2 != 0){
echo '<div class="eventbutton" id='.$event.'><img src="/events/'.$event.'/0.jpg"></div>';
}
}
?>
</div>
</div>
The rendered HTML:
<div id="eventsbar">
<div id="eventslistleft">
<div class="eventbutton" id="fifth"><img src="/events/fifth/0.jpg"></div>
<div class="eventbutton" id="fourth"><img src="/events/fourth/0.jpg"></div>
<div class="eventbutton" id="third"><img src="/events/third/0.jpg"></div></div>
<div id="infobutton"></div>
<div id="eventslistright">
<div class="eventbutton" id="first"><img src="/events/first/0.jpg"></div>
<div class="eventbutton" id="second"><img src="/events/second/0.jpg"></div>
</div>
</div>
And here is the script to call the image load function:
<script>
$(".eventbutton").click(function(){
alert("clicked");
currentevent = this.id;
$.ajax({
type: "GET",
url: "scripts/load.php",
data: "cevt="+currentevent,
success: function(msg){
$('#Content').html(msg);
}
});
});
</script>
For whatever reason, though, the click event only triggers when I click on the last navigation button. I suspect that the click event is not triggering at all because I do not see the alert that says "clicked" when I click any navigation buttons except for the one which is rendered last. Does anyone have experience with a similar issue? Any suggestions for what I can do to correct this problem?
if($i != 0 && $i % 2 != 0){
echo '<div class="eventbutton" id='.$event.'><img src="/events/'.$event.'/0.jpg"></div>';
}
Because all the the buttons are dynamically added to the form so the event should be attached to the parent.
$("#eventslistright .eventbutton").on( "click", function() {});
or
$( "body" ).on( "click", ".eventbutton" ,function(){});
If you add navigation button dynamically in page you should use
.on() Read more ... or .live() Until version 1.7 Read more ...
$("#eventsbar .eventbutton").on( "click", function() {
alert("clicked");
currentevent = this.id;
$.ajax({
type: "GET",
url: "scripts/load.php",
data: "cevt="+currentevent,
success: function(msg){
$('#Content').html(msg);
}
});
});
DEMO
If your code loads elements dynamically then method .click wouldn't work because it is declared for elements already existing during js loading. To add some click event action for js loaded elements you must use .on with parameter 'click'. Example above:
<script>
$(function(){
$("html").on('click','.eventbutton', function(){
var currentevent = $(this).attr('id');
alert(currentevent);
$.ajax({
type: "GET",
url: "scripts/load.php?cevt=" + currentevent,
success: function(msg){
$('#Content').html(msg);
}
});
});
});
</script>

Jquery - Open a new window with content from the current page

I'm trying to create a 'print' button to open a new window and display a PHP Variable in it.
The code below is looped through the PHP script as many times as there are tickets, however I can't seem to get the correct number to display when the window opens (the number that displays in the print link is correct - but when the new window is opened it's incorrect).
<script type='text/javascript'>
jQuery(function($) {
$('a.new-window').click(function(){
var recipe = window.open('','PrintWindow','width=600,height=600');
var html = '<html><head><title>Print Your Ticket</title></head><body><div id="myprintticket">' + $('<div />').append($('#ticket').clone()).html() + '</div></body></html>';
recipe.document.open();
recipe.document.write(html);
recipe.document.close();
return false;
});
});
</script>
Print <?php echo $EM_Booking->get_spaces() ?>
<div style="display:none;">
<div id="ticket"><?php echo $EM_Booking->get_spaces() ?>
</div>
</div>
why not try something like this:
<a href="#" class="new-window">Print <?php echo $EM_Booking->get_spaces() ?>
<div class="ticket" style="display:none">
<?php echo $EM_Booking->get_spaces() ?>
</div>
</a>
<script>
jQuery(function ($) {
$('a.new-window').click(function () {
var btn = $(this),
ticket = btn.find('.ticket').html(),
recipe = window.open('','PrintWindow','width=600,height=600'),
html = '<html><head><title>Print Your Ticket</title></head><body><div id="myprintticket">' + ticket + '</div></body></html>';
recipe.document.open();
recipe.document.write(html);
recipe.document.close();
return false;
});
});
</script>
But much better solution would be to give a button a unique ID, and onclick open an existing (php-generated) page from the server passing that ID, e.g. /getBooking.php?id=123 and that page would output whatever's needed.

Loading Content using Ajax with PHP Include

I have a PHP page which has a div, the div has a PHP includes which includes this file:
<?php
include('mySql.php');
include('Classes.php');
$targetPage = "blogOutput.php";
$noOfPosts = getNumberOfPosts();
$adjacents = 3;
?>
<link rel="stylesheet" type="text/css" href="Styles/Miniblog.css" />
<script src="Scripts/jQuery.js"></script>
<script type="text/javascript">
var page = 1;
$(".Button").click(onClick());
$(document).ready(onClick());
function onClick() {
alert('called');
$("#posts").load("miniBlog.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Error!: ";
alert(msg);
}
});
page++;
}
</script>
<div class="PostTitle">
<h2>What's New!?</h2>
</div>
<div id="posts">
</div>
<a class="BlogButton" href="">Next</a>
I need the function "onclick" to be called without refreshing the page and resetting the "page" variable in javascript. So far, all I've been able to do is make it run the script once. I think that's wrong too, because it's not loading any content. Here's the page:
<?php
echo "I'm here!";
if (isset($_POST['offset'])) {
$offset = $_POST['offset'];
$posts = getPosts($offset);
}
?>
<div class="BlogPost">
<h3><?php echo $posts[0]->Title; ?></h3>
<p><?php echo $posts[0]->Body; ?></p>
<p class="Date"><?php echo $posts[0]->Date; ?></p>
</div>
<div id="divider"></div>
<div class="BlogPost">
<h3><?php echo $posts[1]->Title; ?></h3>
<p><?php echo $posts[1]->Body; ?></p>
<p class="Date"><?php echo $posts[1]->Date; ?></p>
</div>
So, to clarify: I'm not sure why my ajax call isn't working, and I don't know how to load just the div content and not refresh the entire page. Thanks!
You are not able to see content loaded by AJAX because the page is reloading as soon as you click the anchor. Disable the anchor event by using preventDefault() and this should fix it.
<script type="text/javascript">
var page = 1;
$(document).on('click','.BlogButton',function(e){
// stop page from reloading
e.preventDefault();
$("#posts").load("miniBlog.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Error!: ";
alert(msg);
}
});
page++;
});
</script>
Don't call the function in the click method parameter. You have to put the reference to the handler function.
var handler = function onClick () {...}
$("whatever").click(handler);
Change your code to
var page = 1;
$(document).ready(function(){
$(".Button").click(onClick);
onClick();
};
Use this instead of your code
var page = 1;
$(document).on('click','.Button',function(){
$("#posts").load("miniBlog.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Error!: ";
alert(msg);
}
});
page++;
});
Content dose not look too huge.Can't you just hide div (with content already present in it)& show it onclick.

Categories