Lazy Load and ajax calls issue - javascript

I want to separate a list of 30 articles, into chunks of 5.
For this purpose, I wrote the following code:
private static function makeChunk($array = array(), $howMany = 5) {
$shortChunked = array_chunk($array, $howMany);
$count = count($shortChunked);
$html = '';
$i = 0;
foreach ($shortChunked as $key => $chunk) :
$class = '';
if ($key == 0)
$class = ' first active';
if ($key == ($count - 1) && $count>1)
$class = ' last';
$html .= '<div class="my-chunk chunk'.$class.'">';
foreach($chunk as $article) {
if ($i == 0) {
$img = '<img class="img-responsive" src="' . $article['image'] . '" alt="' . $article['imageAlt'] . '" />';
} else {
$img = '<img class="img-tab-ll img-responsive" src="' . get_template_directory_uri() . '/img/imageLoading.gif" data-src="' . $article['image'] . '" alt="' . $article['imageAlt'] . '" />';
}
}
$html .= '</div>';
$i++;
endforeach;
return $html;
}
This is working just fine, but Im considering also lazy loading the first chunk.
I noticed that if I also lazy load the first chunk, images are not showing up, unless I press the button to load the next series (next chunk), so it seems to me that Im missing something related to ajax/lazyload.
Any advises?

Related

Hello, i need to show a value from database constantly without reloading page

i have a table where i display a live price which comes from a cron file that updates every 30seconds or 1 minute, and i have a variable that is filled from that cron job, how do i display it in real-time and make the calculations with php without refreshing the page.
$sql = "SELECT * FROM open_trades WHERE user_id='$session->username' ORDER BY `close_time` DESC ";
$result = $db->prepare($sql);
$result->execute();
while ($row = $result->fetch()) {
if ($row["type"] == "Buy") {
$profit_c = (float) $row["volume"] * (float) $row["live_price"] - $row["cost"];
$fee = 4.9;
$profit = $profit_c * $row["laverage"] - $fee;
}
if ($row["type"] == "Sell") {
$profit_c = (float) $row["volume"] * (float) $row["live_price"] - $row["cost"];
$fee = 4.9;
$profit = $profit_c * $row["laverage"] - $fee;
$profit_sell = $profit * -1;
}
if ($row["type"] == "Buy") {
$profit_trd = $profit;
} else {
$profit_trd = $profit_sell;
}
if ($profit_trd >= 0) {
$col = "profit";
} else {
$col = "loss";
}
if ($profit_trd >= 0) {
$col_b = "#26b276";
} else {
$col_b = "#f73e4a";
}
$open_pl += $profit_trd;
$percentage = ((float) $profit_trd * 100) / (float) $row["cost"];
echo '<tr style="border-right: 2px solid ' . $col_b . ';" class="d-flex justify-content-between" >';
echo "<td>" . $row["time"] . "</td>";
echo "<td>" . $row["asset"] . "</td>";
echo "<td>" . $row["type"] . "</td>";
echo "<td>" . (float) $row["volume"] . "</td>";
echo "<td>1:" . $row["laverage"] . "</td>";
echo "<td>" . (float) round($row["cost"], 2) . '$</td>';
echo "<td>" . (float) $row["buy_price"] . '$</td>';
echo "<td>" . (float) $row["live_price"] . '$</td>';
echo '<td class="' . $col . '" >' . (float) round($profit_trd, 2) . '$</td>';
echo "<td>Close Trade </td>";
echo "</tr>"; }
the $row['live_price'] is the variable i need to get it on realtime everytime it updates from the cron job and also did the $profit_trd updates once it updates, or every PHP calculation requires reload?
Thanks and sorry for my amateur questions!?
You need to use XMLHttpRequest or Websocket to make asynchronus calls from your browser without reloading the page.
Please read MDN Web Docs for more information.
Here are a great comparison of this.

Why after AJAX post, the URL redirect to a URL with the POST params like GET params in this case?

In the addonmodule Controller.php:
I append this order_detail function:
/**
* #param $vars
*/
public function order_detail($vars){
$modulelink = $vars['modulelink']; // eg. addonmodules.php?module=addonmodule
$version = $vars['version']; // eg. 1.0
$LANG = $vars['_lang']; // an array of the currently loaded language variables
$orderid = 28;//isset($_REQUEST['orderid']) ? $_REQUEST['orderid'] : '';
$sql = "SELECT tblhosting.id, tblhosting.regdate, tblhosting.domain, tblhosting.billingcycle, tblhosting.nextduedate, tblhosting.nextinvoicedate, tblhosting.termination_date, tblhosting.domainstatus, tblhosting.username, tblhosting.notes, tblhosting.dedicatedip, tblhosting.assignedips FROM tblhosting ";
// $sql .= "LEFT JOIN tblorders ON ";
// $sql .= "tblhosting.orderid = tblorders.id ";
$sql .= ("WHERE tblhosting.orderid = " . $orderid);
$tblhostings = Capsule::select($sql);
$table_tbody = "";
for($i = 0; $i < count($tblhostings); $i ++) {
$item = $tblhostings[$i];
$row = "<tr>";
$row .= ("<td><input type='text' id='tblhosting-id' name='id' class='form-control' readonly=\"readonly\" style='width:80px;' value='" . $item->id . "'></td>");
$row .= ("<td><textarea id='tblhosting-domain' name='domain' class='form-control' style='width:320px;'>" . $item->domain . "</textarea></td>");
//$row .= ("<td>" . $item->billingcycle . "</td>");
$row .= ("<td ><div style='width:80px;'>" . $item->nextduedate . "</div></td>");
$row .= ("<td ><div style='width:80px;'>" . $item->nextinvoicedate . "</div></td>");
//$row .= ("<td>" . $item->termination_date . "</td>");
//$row .= ("<td>" . $item->username . "</td>");
$row .= ("<td><textarea id='tblhosting-dedicatedip' name='dedicatedip' class='form-control' style='width:200px;'>" . $item->dedicatedip . "</textarea></td>");
$row .= ("<td><textarea id='tblhosting-assignedips' name='assignedips' class='form-control' style='width:200px;'>" . $item->assignedips . "</textarea></td>");
$row .= ("<td>" . $item->domainstatus . "</td>");
$row .= ("<td><div style='width:80px;'>" . $item->regdate . "</div></td>");
$row .= ("<td><textarea id='tblhosting-notes' type='textarea' name='notes' class='form-control' style='width:200px;'>" . $item->notes . "</textarea></td>");
$row .= ("<td> <button id='modify' type='submit' class='btn btn-warning'>modify</button> <button id='send-email' type='button' class='btn btn-success'>Send email</button> </td>");
$row .= "</tr>";
$table_tbody .= $row;
}
$div = "<div class='container'><div><h2>order ID: {$orderid} :</h2></div>";
$div .= "<div >";
$div .= "<form '><table class='table'>";
$div .= "<thead><tr>";
$div .= "<th>product ID</th>";
$div .= "<th>product name</th>";
//$div .= "<th>billingtype</th>";
$div .= "<th>nextdue</th>";
$div .= "<th>nextvoice</th>";
//$div .= "<th>terminate time</th>";
//$div .= "<th>username</th>";
$div .= "<th>dedicated IP</th>";
$div .= "<th>assigned IP</th>";
$div .= "<th>status</th>";
$div .= "<th>regdate</th>";
$div .= "<th>note</th>";
$div .= "<th>ope</th>";
$div .= "</tr></thead>";
$div .= "<tbody>";
$div .= $table_tbody;
$div .= "</tbody>";
$div .= "</table>";
$div .= "</div></div>";
$js = "<script>";
$js .= "
var origin_url = window.location.href;//\"http://192.168.33.10/whmcs-nlidc.com/whmcs/admin/addonmodules.php?module=addonmodule&action=order_detail&orderid=100\";
var url_array =origin_url.split(\"/admin/\")
var url = url_array[0] + \"/admin/api/admin_apis.php\";
jQuery(document).ready(function(){
$('#modify').click(function(){
//alert('modify');
var id = $('#tblhosting-id').val();
var domain = $('#tblhosting-domain').val();
var dedicatedip = $('#tblhosting-dedicatedip').val();
var assignedips = $('#tblhosting-assignedips').val();
var notes = $('#tblhosting-notes').val();
var params = {
admin_api:'update_tblhosting_support',
id: id,
domain: domain,
dedicatedip: dedicatedip,
assignedips: assignedips,
notes: notes,
}
$.post(url, params,function(data,status){
//alert(\"Data: \" + data + \"nStatus: \" + status);
var data_obj = JSON.parse(data);
if (status == 'url' && data_obj.status == 200) {
alert('update success');
alert(window.location.href(www.baidu.com);)
}else {
//alert('update fail');
}
});
})
});
jQuery(document).ready(function(){
$('#send-email').click(function(){
alert('send email');
})
});
";
$js .= "</script>";
$html = $div . $js;
return <<<EOF
$html
EOF;
}
}
I want to use this way to update the tblhosting entries. You see my jQuery code want to use post method to update the tblhosting entry.
when I click update button, it will execute the update url, but however it will redirect to this URL
http://192.168.33.10/whmcs/admin/addonmodules.php?id=28&domain=10.93.240.193-194(15M%29+HK-Z7-A15++E5-2650%282CPU%29%2F32G%2F500G+ssd%2F++&dedicatedip=10.93.240.193-194&assignedips=10.93.240.193%0D%0A10.93.240.194&notes=02442%2F66655%0D%0A10&intellisearch=1&token=ac271aed87528e68969608329e8a1f4d2a35c858&value=
As we know the ajax will not refresh a whole page, and will not redirect by default after request, why there goes different?
Who know the way to avoid the redirect?
I also tried use
window.location.href(origin_url);
to redirect to back after the wrong redirect, but it will not execute.

Span click find the second div

I asked a previous question in this post :Jquery Span click find next div
In order to get the the first div after my span selector.
I used
$(element.parentNode.nextElementSibling).toggle();
in order to show/hide the first div "list-type-demandes"
now i need to toggle the second div "preview-checked-demandes" and i tried :
$(element.parentNode.nextElementSibling.nextElementSibling).toggle();
don't work. any idea ?
here my php/html code :
foreach ($unassociated as $key => $value){
//echo '<br/>';
echo '<label style="color: #1c5081">
<span id="open-list" name="open-list" class="open-list" onclick="openList(this)"><b>+</b></span>
<span id="close-list" name="close-list" class="close-list" onclick="closeList(this)" style="display: none"><b>-</b></span>
'.$key.'</label>';
echo '<div class="list-type-demandes" style="padding-left: 10px ; display: none">';
foreach ($value as $key1 => $value1) {
$appel_projet_type_demande = null;
if($appel_projet->getIdAp()){
$appel_projet_type_demande = Doctrine_Core::getTable('AppelProjetTypeDemande')->findOneByIdApAndIdTypeDemande($appel_projet->getIdAp(), $key1);
}
if ($appel_projet_type_demande) {
$checked = 'checked';
} else {
$checked = '';
}
//var_dump($key1 , $this->candidature->getIdAp() , $checked);
echo '<label style="display: inline"><input type="checkbox" class="checkbox_type_demande" data-appel-projet="' . $appel_projet->getIdAp() . '" name="appel_projet[type_demande_list][' . $i++ . ']" value="' . $key1 . '" id="appel_projet_type_demande_list_' . $key1 . '" ' . $checked . '> ' . $value1 . '</label><br/>';
}
echo '</div>';
//checked items preview
echo '<div class="preview-checked-demandes" style="padding-left: 10px ; display: block">';
foreach ($value as $key1 => $value1) {
$appel_projet_type_demande = null;
if($appel_projet->getIdAp()){
$appel_projet_type_demande = Doctrine_Core::getTable('AppelProjetTypeDemande')->findOneByIdApAndIdTypeDemande($appel_projet->getIdAp(), $key1);
}
if ($appel_projet_type_demande) {
$checked = 'checked';
} else {
$checked = '';
}
if($checked){
echo '<label style="display: inline"><input type="checkbox" class="checkbox_type_demande_preview" data-appel-projet="' . $appel_projet->getIdAp() . '" name="appel_projet[type_demande_list][' . $i++ . ']" value="' . $key1 . '" id="appel_projet_type_demande_list_' . $key1 . '" ' . $checked . '> ' . $value1 . '</label><br/>';
}
}
echo '</div>';
}?>
here my javascript :
function openList(element) {
$(element.parentNode.nextElementSibling).toggle();
$(element.nextElementSibling).toggle();
$(element).toggle();
}
function closeList(element) {
$(element.parentNode.nextElementSibling).toggle();
$(element.previousElementSibling).toggle();
$(element).toggle();
}
Solution - 1
DEMO
<script>
$( function() {
$('.action_list').click(function(){
// Hide and show the action_list list item
$(this).parent().find('.action_list').show();
$(this).hide();
//you can also use nextAll(). nextAll() returns all the next elements, eq(1) returns the second one amongst them.
$(this).parent().nextAll().eq(1).toggle();
});
} );
</script>
Solution -2
DEMO
You can also try the below solution. I added the details within the code.
<script>
$( function() {
$('.action_list').on('click', function(){
// Hide and show the action_list list item
$(this).parent().find('.action_list').show();
$(this).hide();
//On click of open-list and close-list class, getting the target to be toggled from data attribute
var target = $(this).data('target');
$('.'+target).toggle();
});
});
</script>
<?php
$i=1;
foreach ($unassociated as $key => $value){
//echo '<br/>';
/******************* Added details ************************************
1- Add class of div which you have need to toggle with data attribute
2- Add 'action_list' class in open-list and close-list item
**************** End details ******************************************/
echo '<label style="color: #1c5081">
<span id="open-list" name="open-list" data-target="target_'.$i.'" class="action_list open-list"><b>+</b></span>
<span id="close-list" name="close-list" data-target="target_'.$i.'" class="action_list close-list" style="display: none"><b>-</b></span>
'.$key.'</label>';
echo '<div class="list-type-demandes" style="padding-left: 10px ; display: none">';
foreach ($value as $key1 => $value1) {
$appel_projet_type_demande = null;
if($appel_projet->getIdAp()){
$appel_projet_type_demande = Doctrine_Core::getTable('AppelProjetTypeDemande')->findOneByIdApAndIdTypeDemande($appel_projet->getIdAp(), $key1);
}
if ($appel_projet_type_demande) {
$checked = 'checked';
} else {
$checked = '';
}
//var_dump($key1 , $this->candidature->getIdAp() , $checked);
echo '<label style="display: inline"><input type="checkbox" class="checkbox_type_demande" data-appel-projet="' . $appel_projet->getIdAp() . '" name="appel_projet[type_demande_list][' . $i++ . ']" value="' . $key1 . '" id="appel_projet_type_demande_list_' . $key1 . '" ' . $checked . '> ' . $value1 . '</label><br/>';
}
echo '</div>';
/******************* Added details *****************
Added - Add class target (target_'.$i.') to toggle on click of open-list and close-list
/******************* End details ************ */
echo '<div class="preview-checked-demandes target_'.$i.'" style="padding-left: 10px ; display: block">';
foreach ($value as $key1 => $value1) {
$appel_projet_type_demande = null;
if($appel_projet->getIdAp()){
$appel_projet_type_demande = Doctrine_Core::getTable('AppelProjetTypeDemande')->findOneByIdApAndIdTypeDemande($appel_projet->getIdAp(), $key1);
}
if ($appel_projet_type_demande) {
$checked = 'checked';
} else {
$checked = '';
}
if($checked){
echo '<label style="display: inline"><input type="checkbox" class="checkbox_type_demande_preview" data-appel-projet="' . $appel_projet->getIdAp() . '" name="appel_projet[type_demande_list][' . $i++ . ']" value="' . $key1 . '" id="appel_projet_type_demande_list_' . $key1 . '" ' . $checked . '> ' . $value1 . '</label><br/>';
}
}
echo '</div><div style="clear:both"></div>';
$i++;
}?>

i want to use multiple select2 onchange function in a dynamic way

I want to put select2 function in my code but don't know where to put that .select2() function
i have this .append($(<?php echo json_encode($property_address1); ?>))
my model `
function property_address1()
{
$query = $this->db->query('SELECT host,price,city,property_thumbnail, apartments_type, contactnumber, contactperson,photographlinks,emailid, propertyaddress FROM tbl_contacts')->result();
$output = '<select id="neww" class="property_add_ form-control">';
foreach ($query as $row)
{
//echo $row->location;
$output .= "<option value='". $row->propertyaddress ."'";
$output .= " data-propertyaddress='" . $row->propertyaddress ."'" ;
$output .= " data-host_name='" . $row->host ."'" ;
$output .= " data-apartments_type ='" . $row->apartments_type."'" ;
$output .= " data-city ='" . $row->city."'" ;
$output .= " data-property_thumbnail='" . $row->property_thumbnail."'" ;
$output .= " data-price='" . $row->price."'" ;
$output .= " data-contactperson='" . $row->contactperson ."'" ;
// $output. = $row->pincode.", ".$row->city.", ".$row->location;
$output .= " data-photographlinks='" . $row->photographlinks ."'" ;
$output .= " data-emailid='" . $row->emailid ."'" ;
$output .= " data-contactnumber='". $row->contactnumber . "'>" ;
$output .= $row->host . ' , '.$row->propertyaddress . ' ,'.$row->price. ' ,'.$row->apartments_type. ' , '. $row->contactperson . ' , ' . $row->contactnumber. "</option>";
}
$output .= '</select>';
//var_dump($output);
return $output;
}`
my controller
public function test($id = null)
{
$this->layout->set(
array(
'property_address1' => $this->mdl_quotes->property_address1()
)
);
$this->load->model('mdl_quotes');
$this->layout->buffer('content', 'quotes/test');
$this->layout->render();
}
Dhaval Panchal check this updated screenshot
This is screenshot for better understanding.. please have a look Thanks
Insert CSS & JS file in your page then after JS file insert this code in your page.
<script type="text/javascript">
$(document).ready(function() {
$('#neww').select2();
});
</script>
To update options, see below code.
var option = new Option("text", "id");
$("#neww").append(option);
$("#neww").trigger("change");

How to load content with PHP $_SERVER['PHP_SELF'] and href

Hello everyone I need some help with this:
I´m a total noob in php and javascript and I´m facing a little problem here , I´m working with a website that displays a list on the left side and then when I do a click on an element it shows a subelement then when I do a click on the subelement it displays a table that contains info stored in a mysql database, it works flawlessly but the data shown sometimes displays like 5000 rows so it's annoying to be scrolling all the way down 5000 rows, so I decided to paginate the results to be able to just show like 100 elements per page.
Now when I click on the link to show the next 100 rows it takes me to another page and my menu on the left disappears!
I´m using something like this to navigate through the results:
$centerPages = "";
$sub1 = $pn - 1;
$sub2 = $pn - 2;
$add1 = $pn + 1;
$add2 = $pn + 2;
if ($pn == 1) {
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
$centerPages .= ' ' . $add1 . ' ';
}
else if ($pn == $lastPage) {
$centerPages .= ' ' . $sub1 . ' ';
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
}
else if ($pn > 2 && $pn < ($lastPage - 1)) {
$centerPages .= ' ' . $sub2 . ' ';
$centerPages .= ' ' . $sub1 . ' ';
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
$centerPages .= ' ' . $add1 . ' ';
$centerPages .= ' ' . $add2 . ' ';
}
else if ($pn > 1 && $pn < $lastPage) {
$centerPages .= ' ' . $sub1 . ' ';
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
$centerPages .= ' ' . $add1 . ' ';
}
My guess is that because the next and back links are an <a href> tags it loads a new page showing the next 100 rows.
How can I prevent that??
I tried to use a jquery adding a preventDefault(); to those <a href="' . $_SERVER['PHP_SELF'] tags, it worked but now nothing happend on those links xD.
Help me please.
Thanks in advance.
I hope that this example helps you. Its not refreshing the url. So your menu link be opened
you can create pagination link like this
$results = mysqli_query($connecDB,"SELECT COUNT(*) FROM paginate");
$get_total_rows = mysqli_fetch_array($results); //total records
//break total records into pages
$pages = ceil($get_total_rows[0]/$item_per_page);
//create pagination
$pagination = '';
if($pages > 1)
{
$pagination .= '<ul class="paginate">';
for($i = 1; $i<$pages; $i++)
{
$pagination .= '<li>'.$i.'</li>';
}
$pagination .= '</ul>';
}
?>
and here is script for pagination
$(document).ready(function() {
$("#results").load("fetch_pages.php", {'page':0}, function() {$("#1-page").addClass('active');}); //initial page number to load
$(".paginate_click").click(function (e) {
$("#results").prepend('<div class="loading-indication"><img src="ajax-loader.gif" /> Loading...</div>');
var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]); //clicked_id[0] holds the page number we need
$('.paginate_click').removeClass('active'); //remove any active class
//post page number and load returned data into result element
//notice (page_num-1), subtract 1 to get actual starting point
$("#results").load("fetch_pages.php", {'page': (page_num-1)}, function(){
});
$(this).addClass('active'); //add active class to currently clicked element
return false; //prevent going to herf link
});
});
and here fetching Pages
<?php
include("config.inc.php"); //include config file
//sanitize post value
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
//validate page number is really numaric
if(!is_numeric($page_number)){die('Invalid page number!');}
//get current starting point of records
$position = ($page_number * $item_per_page);
//Limit our results within a specified range.
$results = mysqli_query($connecDB,"SELECT id,name,message FROM paginate ORDER BY id DESC LIMIT $position, $item_per_page");
//output results from database
echo '<ul class="page_result">';
while($row = mysqli_fetch_array($results))
{
echo '<li id="item_'.$row["id"].'">'.$row["id"].' <span class="page_name">'.$row["name"].'</span><span class="page_message">'.$row["message"].'</span></li>';
}
echo '</ul>';
?>

Categories