getting js to fire after a div has been populated dynamically - php

I am having a hard time getting the javascript to execute after the div #mcs4_container has been populated, it instead fires before any content has been loaded. This is a piece of a processing page from a .post(), so unfortunately I cannot put it on (window).load because the window is already loaded. mCustomScrollbar is a jquery plugin that adds a scrollbar to the content included in mcs4_container. Below is the relevant php:
echo
'<div id="reserveAPickupAppointmentForm6">';
if (mysql_num_rows($result) == 0) {
echo
'There are currently no appointments available online for this date. Please call or email the office to set up a custom time.';
}
else {
echo
'<div id="mcs4_container">
<div class="customScrollBox">
<div class="container">
<div class="content">';
while($row = mysql_fetch_array($result)) {
echo
'<div class = "hoverLive2 reserveAPickupAppointmentDateText reserveAPickupAppointmentButtonText">'
.$row["date"].
'</div>';
}
echo
'</div>
</div>
<div class="dragger_container"><div class="dragger"></div></div>
</div>
</div>';
echo
'</div>';
echo
'<script>
$("#mcs4_container").mCustomScrollbar("vertical",400,"easeOutCirc",1.05,"fixed","yes","yes",10);
</script>';
}

$.post('/whatev', function() {//this is your callback});
If you're using jQuery, the above should give you a callback that fires when your post request is filled.
Not 100% sure if that's what you want.

Related

how can i send and get messages from database using AJAX JQUERY

I'm building a website using PHP and AJAX JQUERY. And inside this website, there is texting system, like whatsapp, telegram ...etc.
and I'm wanna get all the messages from the database after the user send a message, using jQuery AJAX. so far I have been able to send the text to the database successfully but I fail when I try to get the messages.
I Have this following code when first the page is loaded:
<div class="messaging-frame">
<div class="Title-in-message">
<h4 class="title-message"><?php echo $index['Title'] ?></h4>
</div>
<div class="messaging-box" id="messages">
<?php
// THE MESSAGE FROM MESSAGE TABLE
foreach ($messages as $key => $value) {
if ($_SESSION['EmployeeNum'] === $value['Sender']) { ?>
<div class="row">
<div class="col" style="margin-bottom:15px">
<div class='sent'>
<p id='send-bubble'> <?php
echo $value['Message'] ?> </p>
</div>
</div>
</div>
<?php
} else { ?>
<div class="row">
<div class="col" style="margin-bottom:15px">
<div class='recived' id="recieved-bubble">
<p id='recived-bubble'><?php echo $value['Message'] ?></p>
</div>
</div>
</div><?php
}
}
?>
</div>\
Than this code in AJAX jQuery get executed when ever the user send a new message in messaging box:
$(document).ready(function() {
$('#sending_text').click(function() {
var report = $('#report_num').val()
var reportInt = parseInt(report);
var text = $('#text_sent').val();
var encodeText = encodeURIComponent(text);
$.ajax({
url: "<?php echo base_url() . 'DisplayTicket/sendNewText' ?> ",
type: "POST",
data: {
text: text,
reportNum: reportInt
},
success: function() {
$('#messages').load("<?php echo base_url() . 'DisplayTicket/getNewMessages' ?>", {reportNum: reportInt}, function() {
var texts = " <?php foreach ($messages as $k => $val) { if ($_SESSION['EmployeeNum'] === $value['Sender']) { ?>";
texts += " <div class='row'> <div class='col' style='margin-bottom:15px'> <div class='sent'>";
texts += "<?php echo $val['Message'] ?>";
texts += "</div> </div> </div>";
texts += "<?php } else { ?>";
texts += " <div class='row'> <div class='col' style='margin-bottom:15px'> <div class='recived' id='recieved-bubble'>"
texts += "<?php echo $val['Message'] ?>";
texts += "</div> </div> </div>"
texts += "<?php }
} ?>";
texts += "</div>";
$('#messages').html(texts);
})
},
});
});
})
Keep in mind that the $('#messages').html(texts);
is actually get executed but the newest messages in not added
I see you are using .load() method to fill the #messages .
Normally the first argument to this method is the response you wanna insert,and the this is just a callback after success, and you are using a php variable $messages instead of using the response from the request.
I see already 2 ways of doing this:
1 - remove the callback from load() and make sure the response is well written in html as youy want
2 - get rid of load() function, and call another ajax inside success of the first ajax to accomplish so.
The second method is just to make you understand what is wrong. So the best way to do it is to fix load() method accordingly

print the data on different pages in php using jquery

I have some data displayed on screen
php:
echo'
<script>
$(document).ready(function(){
window.print();
});
</script>';
$sql="SOME QUERY";
$result=$conn->query($sql);
if($result->num_rows>0)
{
while($row=$result->fetch_assoc())
{
echo'<div id="one">
....content....
</div>';
echo'<div id="two">
....content....
</div>';
}
}
now when the page loads the whole page displayed gets printed ( as the function suggest in jquery), but is it possible to print #one on page 1 , and #two on next page (no matter how much content is in these division)
Create a page class for your elements, and add a page-break after them using CSS, so each will be printed to a new page
#media print {
.page{page-break-after: always;}
}
And change the php code to:
while($row=$result->fetch_assoc())
{
echo'<div id="one" class="page">
....content....
</div>';
echo'<div id="two" class="page">
....content....
</div>';
}

Best Way to update PHP Variable?

I am currently having some issues with updating a PHP variable without refreshing the page.
In my situation the code will count the products and if there are none it won't shoot anything out. If the quantity of $total is 1 or greater it will display the amount.
<?php
$total = count_products();
if ($total == 0) {
echo " ";
} else {
echo $total;
}
?>
Now what I am having trouble with is how to update that variable. If I were to add a product, I would not see the updated result until refreshing the page completely. Is there a nice way to update the $total without having to refresh the page?
You can try ajax to do that for you without refreshing page
Basic example here
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
<script type="text/javascript">
$(document).on("click", ".thebutton", function(e) {
e.preventDefault();
$("#result").load(location.href+ ' #my');
});
</script>
<button href="#" class="thebutton"> add product button</button>
<div id="result">
<div id="my">
<?php
//echo time for demonstration
echo date('a:i:s');
?>
<!-- lets say this is where you echo your total -->
<?php
$total = count_products();
if ($total == 0) {
echo " ";
} else {
echo $total;
}
?>
</div>
</div>
Hope this would be of some help to you

Hide a div in while user session exists

I have this problem: I can't find out how to hide a div that appears just when session begins. So I a have a X button for closing, and when the page is refreshed, the div appears again! But I don't want to stop the session.
My code:
<div id="got-points" style="display:<?php echo (isset($customer) && !empty($customer) && isset($customer['customer']) && !empty($customer['customer'])) ? 'block' : 'none'; ?>"> // Checks if session is active
<div class="got-points-bg" style="display: visible;">
<div class="got-points-box">
<img class="got-points-close" src="<?php echo base_url();?>static/images/i8.png" /> //Close Button
My text here
</div>
</div>
</div>
And js
<script>
$(document).ready(
function() {
$(".got-points-close").click(function() {
$(".got-points-bg").hide("fast");
});
});
</script>
If it is on refresh then it is easy; just do it in the PHP session; like this:
HTML:
<div id="got-points" style="display:<?php echo (isset($customer) && !empty($customer) && isset($customer['customer']) && !empty($customer['customer']) && empty($_SESSION['first_load'])) ? 'block' : 'none'; ?>"> // Checks if session is active
<div class="got-points-bg" style="display: visible;">
<div class="got-points-box">
<img class="got-points-close" src="<?php echo base_url();?>static/images/i8.png" /> //Close Button
My text here
</div>
</div>
</div>
and in your PHP before then (like on login/session start) - this will obviously need significant editing since you haven't included your PHP I can't guess it very well, but this should provide a starting point:
<?php
//load user check pseudo code
if !empty($_SESSION[user]) and whatever other checks... {
$_SESSION['first_load'] = False; //important line number 2
}
//login pseudo code to demonstrate placement within your code
if user & pass = valid {
$_SESSION['first_load'] = True; //important line number one
}
That is assuming you want th div output but not displayed on subsequent loads.
Interesting question, how about something like this?
<?php
if(isset($_SESSION['variable'])){
sleep(3); /* Duration(in seconds) div is displayed for */
echo
"<script>
$( document ).ready(function() {
$(".got-points-bg").hide("fast");
});
</script>";
}
?>
try this
<?php error_reporting(0); session_start(); if(empty($_SESSION['user'])) echo "<div id='togglediv'> My text here </div>"; ?>
hope it will work

How To Detect a Button Click in the Expanded Accordion Row

I have an accordion which gets populated based on a dropdown selection. In the 'details' section of each accordion row, I have a button which simply hides the entire accordion and shows a div (which is hidden by default). The div contains the same details as the row selected as well as some additional fields to allow a request be submitted for that item. The first accordion row works fine but when I click on any other row, nothing happens.
I'm assuming this is because the buttons are named the same in each row. I can easily add the row identifier to the end of the button name to differentiate each but I can't figure out how to detect which is selected in my jQuery.
The page works as follows: When a dropdown selection is made, I pass it's value to a SQL statement. Then I loop through each database row and populate my accordion control. Each row can be expanded to show a details section which contains a button used to show the hidden div. When the button is clicked, I use jQuery to pass those values to labels in the hidden div.
<div class="accordion" id="accordion2">
<?php
if (isset($_GET['src'])) {
// SQL stuff here
$group = null;
while ($row = odbc_fetch_array($db)) {
if ($row['Name'] != $group) {
echo "<div class='accordion-heading'>";
echo "<a class='accordion-toggle' data-toggle='collapse'
data-parent='#accordion2' href='#", $row['Number'],"'>
<button id='buttonAccordionToggle'
data-target='#", $row['Number'],"'>", $row['Name'],"</button></a>";
echo "</div>";
echo "<div id='", $row['Number'],"' class='accordion-body collapse'>";
echo "<div class='accordion-inner'>";
echo "<div class='control-group' style='min-height: 50px'>";
echo "<div class='row-fluid show-grid'>";
echo "<div class='span12'>";
echo "<div class='span1'>";
echo "<label>Name:</label>";
echo "</div>";
echo "<div class='span11'>";
echo "<label id='labelAccordionName'>",
$row['UserName'],"</label>";
echo "</div>";
echo "</div>";
echo "<div class='span12'>";
echo "<a id='select' class='btn'>Select</a>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "</div>";
$group = $row['Name'];
}
}
}
?>
</div>
<div id="divDetails" style="display: none;">
<label>Name:</label>
<label id="labelName"></label>
<a id="close" class="btn">Close</a>
</div>
<script>
// Hide the accordion and show the hidden div
$('#select').click(function() {
$('#accordion2').hide();
$('#divDetails').show();
// Pass the label value from the accordion row to the hidden div label
$('#labelName').html($('#labelAccordionName').html());
});
// Hide the div and show the accordion again
$('#close').click(function() {
$('#accordion2').show();
$('#divDetails').hide();
});
// Only allows one row to be shown at a time
$('.accordion-toggle').click(function() {
var $acc = $('#accordion2');
$acc.on('show', '.collapse', function() {
$acc.find('.collapse.in').collapse('hide');
});
});
$(document).ready(function(){
// On dropdown change, pass in value to populate accordion/details
$('#dd').change(function() {
var r = $(this).val();
location.href = "test.php?src=" + r;
});
});
</script>
I know I can add an identifier to the Select button like below but I don't know how to catch that using jQuery:
echo "<a id='select", $row['Number'],"' class='btn'>Select</a>";
Again, the first row works exactly how it should but nothing happens when I click the Select button on any of the other rows.
You can't duplicate element id's. You already have a class of btn on the element, so just bind the event handler to that instead:
$('a.btn').click(function() {
...
});
edit
In order to get the relevant label text, you'll have to traverse the DOM using this (which refers to the clicked btn).
First, make sure you're not duplicating the id of the label element, change:
<label id='labelAccordionName'>
to
<label class='labelAccordionName'>
Then, you should be able to use the following (in your a.btn click handler):
$(this).parent().prev().find('.labelAccordionName').html();

Categories