Send extra data value with PHP/jQuery UI to ajax.php file - php
I am trying to send an extra $php_var with jQuery to an Ajax post function.
In the 1st $.ajax I have:
$('.ui-icon-closethick').click(function(e) {
e.preventDefault();
var parent = $(this).parent().parent();
$.ajax({
type: "POST",
url: "server_items_reorder.php",
data: 'id=' + parent.attr('id'),
success: function() {
parent.slideUp(300,function() {
parent.remove();
});
}
});
});
The data: 'id=' + parent.attr('id') needs a extra $php_var sent to the URL: server_items_reorder.php
A little further down in my code I have:
function savelayout(){
var positions = "";
var weight = 0;
var wb_name = "$wb_name";
$(".portlet").each(function(){weight++;positions+=(this.id + "=" + this.parentNode.id + "|" + weight + "&");});
$.ajax({
type: "POST",
url: "server_items_reorder.php",
data: positions
});
}
As you can see, I already tried there to add a $var called wb_name.
Full code here:
/************************************************************************/
/* WB_BlocksManager v1.0 */
/* Module for phpnuke 6.x and 7.x by Paulo FERREIRA */
/* Copyright (C) 2003 Paulo Ferreira */
/* Web: http://www.phpnuke-belgique.org/ */
/* Email: webmaster#phpnuke-belgique.org */
/* =====================================================================*/
/* James Johnston */
/* http://www.techknowpro.com */
/* =====================================================================*/
/* nono */
/* http://osc2nuke.org/ */
/* =====================================================================*/
/* PHP-NUKE: Web Portal System */
/* =====================================================================*/
/* */
/* Copyright (c) 2002 by Francisco Burzi */
/* http://phpnuke.org */
/* */
/* This program is free software. You can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 2 of the License. */
/************************************************************************/
if (!defined('ADMIN_FILE')) {
die('Access Denied');
}
global $prefix, $db, $admin_file, $wb_name;
$aid = substr($aid, 0, 25);
$row = $db->sql_fetchrow($db->sql_query('SELECT radminsuper FROM ' . $prefix . '_authors WHERE aid=\'' . $aid . '\''));
if ($row['radminsuper'] == 1) {
/*********************************************************/
/* Blocks_Manager Functions */
/*********************************************************/
function BlocksManager($wb_name) {
global $db, $prefix, $currentlang, $multilingual, $bgcolor2, $admin_file;
OpenHeader(_BLOCKMGR);
$wb_url="".$admin_file.".php?op=BlocksManager&wb_name=";
echo "<center><form action=\"".$admin_file.".php\" method=\"post\">\n"
._BLOCKMGR_MODULEDROP." <select name=\"wb_name\" size=\"1\" onChange=\"top.location.href=this.options[this.selectedIndex].value\">\n";
if (!isset($wb_name)) { $wb_name = "admin"; }
echo "<option value=\"".$wb_url."admin\""; if ($wb_name=="admin") { echo " selected"; } echo ">Admin</option>\n";
$result = $db->sql_query("SELECT mid, title, custom_title, active, view, inmenu FROM ".$prefix."_modules WHERE active=1 ORDER BY title ASC");
while(list($mid, $title, $custom_title, $active, $view, $inmenu) = $db->sql_fetchrow($result)) {
echo "<option value=\"".$wb_url.$title."\""; if ($wb_name==$title) { echo " selected"; } echo ">$custom_title</option>\n";
if (!isset($wb_name)) { $wb_name = $title; }
}
echo "</select>\n"
."</form>\n</center>\n";
echo "<br /><br />";
echo "<center><b>"._BLOCKMGR_ADDNEWBLOCK."</b></center>\n"
."<form name=\"BM_EDIT\" action=\"".$admin_file.".php\" method=\"post\">\n"
."<table width=\"80%\" align=\"center\">\n"
."<tr>\n";
//List all inactive Blocks for selected module
echo "<td align=\"center\" valign=\"top\">\n"
._BLOCKMGR_ACTIVE_BLOCKS."<br>\n"
."<select name=\"bida[]\" size=\"10\" multiple>\n";
$sql = "SELECT bid, title FROM ".$prefix."_blocks ORDER BY title ASC";
$result = $db->sql_query($sql);
while (list($bid, $title) = $db->sql_fetchrow($result)) {
$ii = 0; $wb_affiche = 1;
while ($ii < $i) { if ($wb_tabblocks[$ii] == $bid) { $wb_affiche = 0; } $ii++; }
if ($wb_affiche == 1) { echo "<option value=\"".$bid."\">$title</option>\n"; }
}
echo "</select><br>\n"
."<input type=\"submit\" value=\""._BLOCKMGR_ADD_BLOCK."\" onclick=\"document.BM_EDIT.op.value='BlocksManager_Add';\">\n"
."</td>\n";
//List all active Modules
echo "<td align=\"center\" valign=\"top\">"
.""._BLOCKMGR_MODULES."<br><select name=\"title[]\" size=\"10\" multiple>\n";
echo "<option value=\"admin\""; if ($wb_name=="admin") { echo " selected"; } echo ">Admin</option>\n";
$sql = "SELECT mid, title, custom_title FROM ".$prefix."_modules WHERE active=1 ORDER BY title ASC";
$result = $db->sql_query($sql);
while(list($mid, $title, $custom_title) = $db->sql_fetchrow($result)) {
echo "<option value=\"$title\"";
if ($wb_name==$title) { echo " selected"; }
echo ">$custom_title</option>\n";
if (!isset($wb_name)) { $wb_name = $title; }
}
echo "</select><br>"
."</td>\n";
//List all active Blocks for selected module
echo "<td align=\"center\" valign=\"top\">\n"
._BLOCKMGR_INACTIVE_BLOCKS."<br>\n"
."<select name=\"bidr[]\" size=\"10\" multiple>\n";
$sql = "SELECT b.bid, b.title FROM ".$prefix."_blocks b, ".$prefix."_blocks_manager m WHERE b.bid=m.bid AND m.title='$wb_name' ORDER BY title ASC";
$result = $db->sql_query($sql);
while(list($bid, $title) = $db->sql_fetchrow($result)) {
echo "<option value=\"$bid\">$title</option>\n";
}
echo "</select><br>\n"
."<input type=\"submit\" value=\""._BLOCKMGR_REMOVE_BLOCK."\" onclick=\"document.BM_EDIT.op.value='BlocksManager_Remove';\">\n"
."</td>\n"
."</tr>\n"
."</table>\n"
."<input type=\"hidden\" name=\"wb_name\" value=\"$wb_name\">\n"
."<input type=\"hidden\" name=\"op\" value=\"BlocksManager_Add\">\n"
."</form>\n";
?>
<style type="text/css">
body { font-size: 62.5%; }
label, input { display:block; }
input.text { margin-bottom:12px; width:95%; padding: .4em; }
fieldset { padding:0; border:0; margin-top:25px; }
h1 { font-size: 1.2em; margin: .6em 0; }
div#users-contain { width: 350px; margin: 20px 0; }
div#users-contain table { margin: 1em 0; border-collapse: collapse; width: 100%; }
div#users-contain table td, div#users-contain table th { border: 1px solid #eee; padding: .6em 10px; text-align: left; }
.ui-button { outline: 0; margin:0; padding: .4em 1em .5em; text-decoration:none; !important; cursor:pointer; position: relative; text-align: center; }
.ui-dialog .ui-state-highlight, .ui-dialog .ui-state-error { padding: .3em; }
.column { width: 170px; float: left; padding-bottom: 100px; }
.portlet { margin: 0 1em 1em 0; }
.portlet-header { margin: 0.3em; padding-bottom: 4px; padding-left: 0.2em; }
.portlet-header .ui-icon { float: right; }
.portlet-content { padding: 0.4em; }
.ui-sortable-placeholder { border: 1px dotted black; visibility: visible !important; height: 50px !important; }
.ui-sortable-placeholder * { visibility: hidden; }
</style>
<script type="text/javascript">
$(function() {
$(".column").sortable({
connectWith: '.column',
update: savelayout
});
$(".portlet").addClass("ui-widget ui-widget-content ui-helper-clearfix ui-corner-all delete")
.find(".portlet-header")
.addClass("ui-widget-header ui-corner-all")
.prepend('<span class="ui-icon ui-icon-wrench"></span>')
.prepend('<span class="ui-icon ui-icon-plusthick"></span>')
.prepend('<span class="ui-icon ui-icon-closethick"></span>')
.end()
.find(".portlet-content").toggle();
$(".portlet-header .ui-icon-plusthick").toggle(function() {
$(this).removeClass("ui-icon-plusthick");
$(this).addClass("ui-icon-minusthick");
$(this).parents(".portlet:first").find(".portlet-content").toggle();
}, function() {
$(this).removeClass("ui-icon-minusthick");
$(this).addClass("ui-icon-plusthick");
$(this).parents(".portlet:first").find(".portlet-content").toggle();
}
);
$('.ui-icon-closethick').click(function(e) {
e.preventDefault();
var parent = $(this).parent().parent();
$.ajax({
type: "POST",
url: "server_items_reorder.php",
data: 'id=' + parent.attr('id'),
success: function() {
parent.slideUp(300,function() {
parent.remove();
});
}
});
});
$(".column").disableSelection();
});
</script>
<div class="column" id="l">
<?php
$sql = "SELECT b.bid, b.bkey, b.title, b.url, m.bposition, m.weight, b.active, b.blanguage, b.blockfile, b.view FROM ".$prefix."_blocks b, ".$prefix."_blocks_manager m WHERE b.bid=m.bid AND m.title='$wb_name' AND m.bposition = 'l' ORDER BY weight";
$result = $db->sql_query($sql);
while(list($bid, $bkey, $title, $url, $bposition, $weight, $active, $blanguage, $blockfile, $view) = $db->sql_fetchrow($result)) {
?>
<div class="portlet" id="<?php echo $bid; ?>">
<div class="portlet-header" id="<?php echo $bid; ?>"><?php echo $title; ?></div>
<div class="portlet-content"><?php echo $title . '---(' . $view . ')'; ?></div>
</div>
<?php
}
?>
</div>
<div class="column" id="c">
<?php
$sql = "SELECT b.bid, b.bkey, b.title, b.url, m.bposition, m.weight, b.active, b.blanguage, b.blockfile, b.view FROM ".$prefix."_blocks b, ".$prefix."_blocks_manager m WHERE b.bid=m.bid AND m.title='$wb_name' AND m.bposition = 'c' ORDER BY weight";
$result = $db->sql_query($sql);
while(list($bid, $bkey, $title, $url, $bposition, $weight, $active, $blanguage, $blockfile, $view) = $db->sql_fetchrow($result)) {
?>
<div class="portlet" id="<?php echo $bid; ?>">
<div class="portlet-header"><?php echo $title; ?></div>
<div class="portlet-content"><?php echo $title . '---(' . $bposition . '---' . $wb_name .')'; ?></div>
</div>
<?php
}
?>
</div>
<div class="column" id="d">
<?php
$sql = "SELECT b.bid, b.bkey, b.title, b.url, m.bposition, m.weight, b.active, b.blanguage, b.blockfile, b.view FROM ".$prefix."_blocks b, ".$prefix."_blocks_manager m WHERE b.bid=m.bid AND m.title='$wb_name' AND m.bposition = 'd' ORDER BY weight";
$result = $db->sql_query($sql);
while(list($bid, $bkey, $title, $url, $bposition, $weight, $active, $blanguage, $blockfile, $view) = $db->sql_fetchrow($result)) {
?>
<div class="portlet" id="<?php echo $bid; ?>">
<div class="portlet-header"><?php echo $title; ?></div>
<div class="portlet-content"><?php echo $title . '---(' . $bposition . ')'; ?></div>
</div>
<?php
}
?>
</div>
<div class="column" id="r">
<?php
$sql = "SELECT b.bid, b.bkey, b.title, b.url, m.bposition, m.weight, b.active, b.blanguage, b.blockfile, b.view FROM ".$prefix."_blocks b, ".$prefix."_blocks_manager m WHERE b.bid=m.bid AND m.title='$wb_name' AND m.bposition = 'r' ORDER BY weight";
$result = $db->sql_query($sql);
while(list($bid, $bkey, $title, $url, $bposition, $weight, $active, $blanguage, $blockfile, $view) = $db->sql_fetchrow($result)) {
?>
<div class="portlet" id="<?php echo $bid; ?>">
<div class="portlet-header"><?php echo $title; ?></div>
<div class="portlet-content"><?php echo $title . '---(' . $bposition . ')'; ?></div>
</div>
<?php
}
?>
</div>
<script type="text/javascript">
function savelayout(){
var positions = "";
var weight = 0;
var wb_name = "$wb_name";
$(".portlet").each(function(){weight++;positions+=(this.id + "=" + this.parentNode.id + "|" + weight + "&");});
$.ajax({
type: "POST",
url: "server_items_reorder.php",
data: positions
});
}
</script>
<?php
CloseFooter();
}
function BlocksManager_Add($bid, $title) {
global $db, $prefix;
foreach($title as $tKey => $tValue) {
$sql = "SELECT MAX(weight) FROM ".$prefix."_blocks_manager WHERE title='$tValue'";
$result = $db->sql_query($sql);
list($weight, $bposition) = $db->sql_fetchrow($result);
foreach($bid as $bKey => $bValue) {
$weight++;
$db->sql_query("INSERT INTO ".$prefix."_blocks_manager VALUES ($bValue, '$tValue', 'l', $weight)");
}
BlocksManager_FixWeight($tValue);
}
}
function BlocksManager_Remove($bid, $title) {
global $db, $prefix;
foreach($title as $tKey => $tValue) {
foreach($bid as $bKey => $bValue) {
$db->sql_query("DELETE FROM ".$prefix."_blocks_manager WHERE bid='$bValue' AND title='$tValue'");
}
BlocksManager_FixWeight($tValue);
}
}
function BlocksManager_FixWeight($wb_name) {
global $db, $prefix;
$position[] = 'l';
$position[] = 'r';
$position[] = 'c';
$position[] = 'd';
$position[] = '';
foreach($position as $pKey => $pValue) {
$result = $db->sql_query("SELECT bid FROM ".$prefix."_blocks_manager WHERE title='$wb_name' AND bposition='$pValue' ORDER BY weight ASC");
$weight = 0;
while(list($bid) = $db->sql_fetchrow($result)) {
$weight++;
if ($pValue != '') : $db->sql_query("UPDATE ".$prefix."_blocks_manager SET weight='$weight' WHERE title='$wb_name' AND bid='$bid'");
else : $db->sql_query("UPDATE ".$prefix."_blocks_manager SET weight='$weight', bposition='l' WHERE title='$wb_name' AND bid='$bid'<br>");
endif;
}
}
}
function BlocksManager_BlockPosition($bid, $wb_name, $position) {
global $db, $prefix;
$db->sql_query("UPDATE ".$prefix."_blocks_manager SET bposition='$position' WHERE bid='$bid' AND title='$wb_name'");
BlocksManager_FixWeight($wb_name);
}
function BlocksManager_BlockOrder($wb_name, $weightrep, $weight, $bidrep, $bidori) {
global $db, $prefix;
$result = $db->sql_query("UPDATE ".$prefix."_blocks_manager SET weight='$weight' WHERE bid='$bidrep'");
$result2 = $db->sql_query("UPDATE ".$prefix."_blocks_manager SET weight='$weightrep' WHERE bid='$bidori'");
BlocksManager_FixWeight($wb_name);
}
function OpenHeader($title="") {
include("header.php");
GraphicAdmin();
title($title);
OpenTable();
}
function CloseFooter() {
CloseTable();
include("footer.php");
}
switch($op) {
case "BlocksManager":
BlocksManager($wb_name);
break;
case "BlocksManager_Add":
BlocksManager_Add($bida, $title);
Header("Location: ".$admin_file.".php?op=BlocksManager&wb_name=$wb_name");
break;
case "BlocksManager_Remove":
BlocksManager_Remove($bidr, $title);
Header("Location: ".$admin_file.".php?op=BlocksManager&wb_name=$wb_name");
break;
case "BlocksManager_BlockPosition":
BlocksManager_BlockPosition($bid, $title, $position);
Header("Location: ".$admin_file.".php?op=BlocksManager&wb_name=$title");
break;
case "BlocksManager_FixWeight":
BlocksManager_FixWeight($wb_name);
Header("Location: ".$admin_file.".php?op=BlocksManager&wb_name=$wb_name");
break;
case "BlocksManager_BlockOrder":
BlocksManager_BlockOrder ($title, $weightrep, $weight, $bidrep, $bidori);
Header("Location: ".$admin_file.".php?op=BlocksManager&wb_name=$title");
break;
}
} else {
echo "Access Denied";
}
The purpose of the code is to control a block system by modules. You can move/add/change/delete blocks by its module.
You need to mix your PHP inline with your AJAX request:
$('.ui-icon-closethick').click(function(e) {
e.preventDefault();
var parent = $(this).parent().parent();
$.ajax({
type: "POST",
url: "server_items_reorder.php",
data: 'id=' + parent.attr('id') + '&php_var=<?php echo $php_var; ?>',
success: function() {
parent.slideUp(300,function() {
parent.remove();
});
}
});
});
And for your second example:
function savelayout(){
var positions = "";
var weight = 0;
var wb_name = "<?php echo $wb_name; ?>";
$(".portlet").each(function(){
weight++;
positions += (this.id + "=" + this.parentNode.id + "|" + weight + "&");
});
$.ajax({
type: "POST",
url: "server_items_reorder.php",
data: positions
});
}
Do you mean
$.ajax({
type: "POST",
url: "server_items_reorder.php",
data: {'positions':positions, 'wb_name': wb_name}
});
?
Related
Dynamic search bar in jQuery with result display problems
I have a small question: I created a dynamic search bar until now it's ok. But the problem I have is that when I type the beginning of a letter or a number, I don't have a display limit it takes all the page someone already have a solution? Thanks a lot Here is the jQuery code: $(document).ready(function () { $('#search-stock').keyup(function (){ $('#result-search').html(''); var stock = $(this).val(); if (stock != "") { $.ajax({ type: 'GET', url: '../ajax/stock_search.php', data: 'stocks=' + encodeURIComponent(stock), success: function (data) { if (data != "") { $('#result-search').append(data); } else { document.getElementById('result-search').innerHTML = "" + "<div style='font-size: 20px; text-align: center; margin-top: 10px'> Aucun élement trouver</div>" } } }); } }); }); Here is the php <?php session_start(); include('../include/bdd.php'); if(isset($_GET['stocks'])){ $stock_aema = (string) trim($_GET['stocks']); $req = $bdd->prepare("SELECT * FROM stock_aema WHERE model LIKE :model LIMIT 10"); $req2 = $bdd->prepare("SELECT * FROM stock_aema WHERE id LIKE :id LIMIT 10"); $req3 = $bdd->prepare("SELECT * FROM stock_aema WHERE aema LIKE :aema LIMIT 10"); $req->execute(array('model' => "%$stock_aema%")); $req = $req->fetchAll(); foreach ($req as $r){ ?> <div style="margin-top: 20px ; border-bottom: 2px solid #ccc"> <?= $r['id'] . " " . $r['model']. " " . $r['aema']?> </div> <?php } $req2->execute(array('id' => "%$stock_aema%")); $req2 = $req2->fetchAll(); foreach ($req2 as $s){ ?> <div style="margin-top: 20px ; border-bottom: 2px solid #ccc"> <?= $s['id'] . " " . $s['model']. " " . $s['aema']?> </div> <?php } $req3->execute(array('aema' => strval("%$stock_aema%"))); $req3 = $req3->fetchAll(); foreach ($req3 as $x){ ?> <div style="margin-top: 20px ; border-bottom: 2px solid #ccc"> <?= $x['id'] . " " . $x['model']. " " . $x['aema']?> </div> <?php } } ?>
Infinite Scroll Pagination using PHP and jQuery returns only few posts and halts with a loader gif
I m trying to replicate code found online for Infinite scroll using PHP and JQuery. But unfortunately, there is a flaw in the code which makes it only to return 7 posts only and stops fetching other posts upon scrolling down leaving a loader gif at the bottom. Generally, I wouldn't have asked this question, but the code seems pretty nice (in laymans terms) which I presume will be very helpful for rookies like me in the community. Meanwhile will search other resources and try to answer it by myself. My code Goes as : Index.php <div class="post-wall"> <div id="post-list"> <?php require_once ('db.php'); $sqlQuery = "SELECT * FROM tbl_posts"; $result = mysqli_query($conn, $sqlQuery); $total_count = mysqli_num_rows($result); $sqlQuery = "SELECT * FROM tbl_posts ORDER BY id DESC LIMIT 7"; $result = mysqli_query($conn, $sqlQuery); ?> <input type="hidden" name="total_count" id="total_count" value="<?php echo $total_count; ?>" /> <?php while ($row = mysqli_fetch_assoc($result)) { $content = substr($row['content'], 0, 100); ?> <div class="post-item" id="<?php echo $row['id']; ?>"> <p class="post-title"><?php echo $row['title']; ?></p> <p><?php echo $content; ?></p> </div> <?php } ?> </div> <div class="ajax-loader text-center"> <img src="LoaderIcon.gif"> Loading more posts... </div> </div> <script type="text/javascript"> $(document).ready(function(){ windowOnScroll(); }); function windowOnScroll() { $(window).on("scroll", function(e){ if ($(window).scrollTop() == $(document).height() - $(window).height()){ if($(".post-item").length < $("#total_count").val()) { var lastId = $(".post-item:last").attr("id"); getMoreData(lastId); } } }); } function getMoreData(lastId) { $(window).off("scroll"); $.ajax({ url: 'getMoreData.php?lastId=' + lastId, type: "get", beforeSend: function () { $('.ajax-loader').show(); }, success: function (data) { setTimeout(function() { $('.ajax-loader').hide(); $("#post-list").append(data); windowOnScroll(); }, 1000); } }); } </script> getMoreData.php <?php require_once('db.php'); $lastId = $_GET['lastId']; $sqlQuery = "SELECT * FROM tbl_posts WHERE id < '" .$lastId . "' ORDER BY id DESC LIMIT 7"; $result = mysqli_query($conn, $sqlQuery); while ($row = mysqli_fetch_assoc($result)) { $content = substr($row['content'],0,100); ?> <div class="post-item" id="<?php echo $row['id']; ?>"> <p class="post-title"> <?php echo $row['title']; ?></p> <p><?php echo $content; ?></p> </div> <?php } ?> Any help is greatly appreciated.
I would set this up differently using classes and controllers etc, but as simple scripts, I might set it up something like: Create a file called getData.php with this content: <?php require_once('db.php'); if (! function_exists('getData')) { /** * #param int $offset * #param int $limit * #return array|null */ function getData($offset, $limit, $conn) { $offset = (int)$offset; $limit = (int)$limit; $sqlQuery = "SELECT * FROM tbl_posts ORDER BY id DESC LIMIT $limit OFFSET $offset"; $result = mysqli_query($conn, $sqlQuery); $rows = []; while ($row = mysqli_fetch_assoc($result)) { $rows[]= $row; } return $rows; } } Create another file called index.php with this content: <?php require_once ('getData.php'); $offset = (int)($_GET['offset'] ?? 0); $dataOnly = (int)($_GET['dataOnly'] ?? 0); $limit = 7; $rows = getData($offset, $limit, $conn); $offset+= $limit; $data = [ 'rows' => $rows, 'offset' => $offset, ]; $data = json_encode($data); // if this is an ajax call, stop here and just spit out our json if ($dataOnly) { echo $data; exit; } // otherwise, render the page $sqlQuery = "SELECT * FROM tbl_posts"; $result = mysqli_query($conn, $sqlQuery); $total_count = mysqli_num_rows($result); ?> <!DOCTYPE html> <html> <head> <script type="text/javascript" src="jquery-3.2.1.min.js"></script> <style type="text/css"> body { font-family: Arial; background: #e9ebee; font-size: 0.9em; } .post-wall { background: #FFF; border: #e0dfdf 1px solid; padding: 20px; border-radius: 5px; margin: 0 auto; width: 500px; } .post-item { padding: 10px; border: #f3f3f3 1px solid; border-radius: 5px; margin-bottom: 30px; } .post-title { color: #4faae6; } .ajax-loader { display: block; text-align: center; } .ajax-loader img { width: 50px; vertical-align: middle; } </style> </head> <body> <div class="post-wall"> <div id="post-list"> <input type="hidden" name="total_count" id="total_count" value="<?= $total_count ?>" /> <input type="hidden" name="offset" id="offset" value="<?= $offset ?>" /> </div> <div class="ajax-loader text-center"> <img src="LoaderIcon.gif"> Loading more posts... </div> </div> <script type="text/javascript"> $(document).ready(function(){ // load the initial rows on page load let initialData = <?= $data ?? '' ?>; if (initialData) { if (initialData.rows) { addrows(initialData.rows); $('.ajax-loader').hide(); } } windowOnScroll(); }); function windowOnScroll() { $(window).on("scroll", function(e){ if ($(window).scrollTop() == $(document).height() - $(window).height()){ console.log('test'); if($(".post-item").length < $("#total_count").val()) { let offset = $('#offset').val(); getMoreData(offset) } } }); } function getMoreData(offset) { $('.ajax-loader').show(); $(window).off("scroll"); let pageUrl = window.location.href.split('?')[0]; $.ajax({ url: pageUrl + '?dataOnly=1&offset=' + offset, type: "get", success: function (response) { response = JSON.parse(response); if (response.rows) { addrows(response.rows); if (response.offset) { $('#offset').val(response.offset); } $('.ajax-loader').hide(); } windowOnScroll(); } }); } function addrows(rows) { let postList = $("#post-list"); $.each(rows, function (i, row) { let rowHtml = '<div class="post-item" id="'+row.id+'"><p class="post-title">'+row.title+'</p><p>'+row.content+'</p></div>'; postList.append(rowHtml); }); } </script> </body> </html> Now, I cant test this locally so there might be an error or two in there, but that should give you the general idea. One thing im not 100% sure of is that if ($(window).scrollTop() == $(document).height() - $(window).height()){ condition. XSS warning You dont show how these "posts" get added to the database, presumably they come from user submissions on some other form. If that is the case, make sure that you understand what XSS vulnerabilities are and how to prevent them
I want make a OOP pagination for my articles
I want make a pagination for my articles.. Here is class: <?php class Mynews { public $conn; public function __construct() { $this->conn = mysqli_connect("localhost", "root", "", "mynews"); } public function readAllarticles() { $sql = "SELECT * FROM articles WHERE status='publish'"; $query = mysqli_query($this->conn, $sql); return mysqli_fetch_all($query, MYSQLI_ASSOC); } } $obj = new Mynews; ?> display post: <?php include('includes/crud.php'); foreach ($obj->readAllarticles() as $art) { extract($art); ?> <h3><?php echo $title; ?></h3> <p> <?php $post = explode(" ", $content); $slice = array_slice($post, 0, 10); echo implode(" ", $slice), '...'; ?> </p> <?php } ?> Now i want a function my class to make a pagination... and sorry for my bad eng.. :(
You use it: <?php class Pagination{ function Paginate($values,$per_page){ $total_values = count($values); if(isset($_GET['page'])){ $current_page = $_GET['page']; }else{ $current_page = 1; } $counts = ceil($total_values / $per_page); $param1 = ($current_page - 1) * $per_page; $this->data = array_slice($values,$param1,$per_page); for($x=1; $x<= $counts; $x++){ $numbers[] = $x; } return $numbers; } function fetchResult(){ $resultsValues = $this->data; return $resultsValues; } } // Sample Usage $pag = new Pagination(); $data = array("Hello","Rex","Prosper","Adrivan","Hehe"); $numbers = $pag->Paginate($data,2); $result = $pag->fetchResult(); foreach($result as $r){ echo '<div>'.$r.'</div>'; } foreach($numbers as $num){ echo ''.$num.''; } ?>
I use this and it works for me PHP function pagination_one($webpage, $total_pages,$page){ // Maximum number of links per page. If exceeded, google style pagination is generated $max_links = 6; $h=1; if($page>$max_links){ $h=(($h+$page)-$max_links); } if($page>=1){ $max_links = $max_links+($page-1); } if($max_links>$total_pages){ $max_links=$total_pages+1; } echo '<div class="page_numbers"> <ul>'; if($page>"1"){ echo '<li class="current">First</li> <li class="current">Prev</li> '; } if($total_pages!=1){ for ($i=$h;$i<$max_links;$i++){ if($i==$page){ echo '<li><a class="current">'.$i.'</a></li>'; } else{ echo '<li>'.$i.' </li>'; } } } if(($page >="1")&&($page!=$total_pages)){ echo '<li class="current">Next</li> <li class="current">Last</li>'; } echo '</ul> </div>'; } function pagination_one($webpage, $total_pages,$page){ // Maximum number of links per page. If exceeded, google style pagination is generated $max_links = 6; $h=1; if($page>$max_links){ $h=(($h+$page)-$max_links); } if($page>=1){ $max_links = $max_links+($page-1); } if($max_links>$total_pages){ $max_links=$total_pages+1; } echo '<div class="page_numbers"> <ul>'; if($page>"1"){ echo '<li class="current">First</li> <li class="current">Prev</li> '; } if($total_pages!=1){ for ($i=$h;$i<$max_links;$i++){ if($i==$page){ echo '<li><a class="current">'.$i.'</a></li>'; } else{ echo '<li>'.$i.' </li>'; } } } if(($page >="1")&&($page!=$total_pages)){ echo '<li class="current">Next</li> <li class="current">Last</li>'; } echo '</ul> </div>'; } // get the pagenum. If it doesn't exist, set it to 1 if(isset($_GET['pagenum']) ? $page = $_GET['pagenum']:$page = 1); // set the number of entries to appear on the page $entries_per_page = 6; // total pages is rounded up to nearest integer $total_pages = ceil($getresult/$entries_per_page); // offset is used by SQL query in the LIMIT $offset = (($page * $entries_per_page) - $entries_per_page); $sql = "SELECT * FROM articles WHERE status='publish' LIMIT $offset,$entries_per_page"; // do your query results pagination_one('articles.php', $total_pages,$page); and CSS .page_numbers { width:100%; background:#fff9f0; overflow:hidden; position:relative; padding:50px 0; } .page_numbers ul, .pagenums ul { clear:left; float:left; list-style:none; margin:0; padding:0; position:relative; left:50%; text-align:center; } .page_numbers ul li,.pagenums ul li { display:block; float:left; list-style:none; margin:1px; padding:0; position:relative; right:50%; background: #a8a189; width:25px; } .page_numbers ul li a, .pagenums ul li a { display:block; background: #fff; border: 1px solid #a8a189; padding:3px 6px; text-decoration: none; color: #7a7564; font:bold 11px arial, verdana,sans-serif; } .page_numbers li.current, .pagenums li.current{ width:50px; } .page_numbers a.current, .page_numbers li a:hover, .pagenums a.current, .pagenums li a:hover { background: #a8a189; color: #fff; }
Search Criteria in PHP
JAVASCRIPT function ShowContent(id) { if(id.length < 1) { return; } document.getElementById(id).style.display = "block"; } PHP $test = mysql_query('SELECT userid,testid,testname FROM test_table WHERE userid = 9 ORDER BY name'); TestName : <select> while($row=mysql_fetch_array($test)) { $testname = $row['testname']; $testid = $row['testid']; echo '<option value='.$testid.'>'.$testname.'</option> } </select> echo '<div id="testid" style="display:none;"> echo '<table> <tr><th>USERID</th</tr> <tr><th>TESTNAME</th></tr> <tr><th>MARKS</th></tr> publishtest = mysql_query('SELECT id,userid,publishtest,marks FROM publish_table WHERE userid= 9 GROUP BY id'); while($row=mysql_fetch_array($publishtest)) { $userid = $row['userid']; $testid = $row['id']; /*This is test id*/ $testname = $row['publishtest']; /* This is test name*/ $marks = $row['marks']; echo '<tr><td>'.$userid.'</td> <td>'.testid.'</td> <td>'.testname.'</td> <td>'.$marks.'</td> </tr> } echo '</table>'; echo '</div>'; I need when I select test from select tag, then div should be displayed of that testid. I want either in javascript, jquery
You can try this: JavaScript $('#showDivSelect').change(function (e) { var divId = $(this).children('option:selected').val(); $('#' + divId).css('display', 'block'); }); HTML <select id="showDivSelect"> <option id="o1">Div1</option> <option id="o2">Div2</option> </select> <div id="Div1"></div> <div id="Div2"></div> CSS #Div1 { width: 30px; height: 30px; background-color: red; display: none; } #Div2 { width: 30px; height: 30px; background-color: blue; display: none; } Here is working example: http://jsfiddle.net/ePSDu/
How do I pass variable from a form to javascript popup form?
I have a form with a button which opens a javascript/css popup window. On the popup window I have a textarea which will be used to add a comment to a database field. The problem is that I need to pass it a value from the main page (the one that calls the popup) which will identify which entry in the database to update. But I am stuck trying to get it to work. Here is my code. I need to have the variable sent to the update.php page. Please help. <?php ini_set('display_errors',1); error_reporting(E_ALL); if(isset($_GET['sort']) && isset($_GET['col']) ){ $order = $_GET['sort']; $column = $_GET['col']; } else{ $order = 'ASC'; $column = 'cron_id'; } $page = 'Testing Site'; require_once('includes/head.php'); require_once('includes/mysql.php'); require_once('includes/class.tdcron.php'); require_once('includes/class.tdcron.entry.php'); date_default_timezone_set('America/Los_Angeles'); $result = mysql_query("SELECT * FROM cron WHERE active=1 ORDER BY $column $order") or die (mysql_error()); mysql_close(); $pass = "<img src='images/Checked.png' alt='Pass' width='16' height='16'/>"; $fail = "<img src='images/Stop.png' alt='Failed' width='16' height='16'/>"; $warn = "<img src='images/Warning.png' alt='Warning' width='16' height='16' />"; $com = "<img src='images/pencil.png' alt='Warning' width='16' height='16' />"; echo "<div id='tableContainer' class='tableContainer'>"; echo "<table width='100%' border='0' padding='0' cellpadding='0' cellspacing='0' class='scrollTable'>"; echo "<thead class='fixedHeader'>"; echo "<tr>"; if ($order=="ASC") { echo "<th>Status</th>"; } else { echo "<th>Status</th>"; } echo '<th>Schedule</th>'; if ($order=="ASC") { echo "<th>Job</th>"; } else { echo "<th>Job</th>"; } echo '<th>Description</th>'; if ($order=="ASC") { echo "<th>Destination</th>"; } else { echo "<th>Destination</th>"; } echo '<th>Errors</th>'; if ($order=="ASC") { echo "<th>Job Type</th>"; } else { echo "<th>Job Type</th>"; } if ($order=="ASC") { echo "<th>Category</th>"; } else { echo "<th>Category</th>"; } if ($order=="ASC") { echo "<th>Last Ran</th>"; } else { echo "<th>Last Ran</th>"; } echo '<th>Next Run</th>'; echo '<th>Log</th>'; echo '</tr></thead><tbody class="scrollContent">'; while($row = mysql_fetch_array($result)){ if($row['ok'] == 1){$status = $pass;} elseif($row['ok'] == 0){$status = $fail;} else{$status = $warn;} echo '<tr>'; echo '<td> **<form name="frm_comment" action="" onsubmit="return false;" >' . $status . ' ' . '<input type="image" src="images/pencil.png" onclick="popup_show(\'popup\', \'popup_drag\', \'popup_exit\', \'mouse\', -10, -5);" width=\'16\' height=\'16\' /> </form>** </td>'; echo '<td>' . $row['schedule'] . '</td>'; echo '<td>' . $row['job'] . '</td>'; echo '<td>' . $row['description'] . '</td>'; echo '<td>' . $row['destination'] . '</td>'; echo '<td>' . $row['errormsgs'] . '</td>'; echo '<td>' . $row['jobtype'] . '</td>'; echo '<td>' . $row['catagory'] . '</td>'; echo '<td>' . date('D M d # g:i A', $row['ran_at']) . '</td>'; echo '<td>' . date('D M d # g:i A', tdCron::getNextOccurrence($row['mhdmd'])) . '</td>'; echo "<td><a href='log/" . $row['log'] . "' target='_blank' >View Log</a></td>"; echo '</tr>'; } echo '</tbody>'; echo "</table>"; echo "</div>"; // ***** Popup Window **************************************************** echo'<div class="sample_popup" id="popup" style="display: none;"> <div class="menu_form_header" id="popup_drag"> <img class="menu_form_exit" id="popup_exit" src="images/form_exit.png" alt="Close Form" /> Comments </div> <div class="menu_form_body"> <form name="up" action="update.php" onsubmit="return validateForm()" method="post" > <input type="hidden" name="' . $row['job'] . '" /> <table> <tr> <td><textarea class="field" onfucus="select();" name="comment" rows="8" cols="44"></textarea> </tr> <tr> <td align="right" ><br /><input class="btn" type="submit" name="submit" value="Submit" /></td> </tr> </table> </form> </div> </div>'; require_once('includes/footer.php'); ?> Javascript code start // Copyright (C) 2005-2008 Ilya S. Lyubinskiy. All rights reserved. // Technical support: http://www.php-development.ru/ // // YOU MAY NOT // (1) Remove or modify this copyright notice. // (2) Re-distribute this code or any part of it. // Instead, you may link to the homepage of this code: // http://www.php-development.ru/javascripts/popup-window.php // // YOU MAY // (1) Use this code on your website. // (2) Use this code as part of another product. // // NO WARRANTY // This code is provided "as is" without warranty of any kind. // You expressly acknowledge and agree that use of this code is at your own risk. // USAGE // // function popup_show(id, drag_id, exit_id, position, x, y, position_id) // // id - id of a popup window; // drag_id - id of an element within popup window intended for dragging it // exit_id - id of an element within popup window intended for hiding it // position - positioning type: // "element", "element-right", "element-bottom", "mouse", // "screen-top-left", "screen-center", "screen-bottom-right" // x, y - offset // position_id - id of an element relative to which popup window will be positioned // ***** Variables ************************************************************* var popup_dragging = false; var popup_target; var popup_mouseX; var popup_mouseY; var popup_mouseposX; var popup_mouseposY; var popup_oldfunction; // ***** popup_mousedown ******************************************************* function popup_mousedown(e) { var ie = navigator.appName == "Microsoft Internet Explorer"; popup_mouseposX = ie ? window.event.clientX : e.clientX; popup_mouseposY = ie ? window.event.clientY : e.clientY; } // ***** popup_mousedown_window ************************************************ function popup_mousedown_window(e) { var ie = navigator.appName == "Microsoft Internet Explorer"; if ( ie && window.event.button != 1) return; if (!ie && e.button != 0) return; popup_dragging = true; popup_target = this['target']; popup_mouseX = ie ? window.event.clientX : e.clientX; popup_mouseY = ie ? window.event.clientY : e.clientY; if (ie) popup_oldfunction = document.onselectstart; else popup_oldfunction = document.onmousedown; if (ie) document.onselectstart = new Function("return false;"); else document.onmousedown = new Function("return false;"); } // ***** popup_mousemove ******************************************************* function popup_mousemove(e) { var ie = navigator.appName == "Microsoft Internet Explorer"; var element = document.getElementById(popup_target); var mouseX = ie ? window.event.clientX : e.clientX; var mouseY = ie ? window.event.clientY : e.clientY; if (!popup_dragging) return; element.style.left = (element.offsetLeft+mouseX-popup_mouseX)+'px'; element.style.top = (element.offsetTop +mouseY-popup_mouseY)+'px'; popup_mouseX = ie ? window.event.clientX : e.clientX; popup_mouseY = ie ? window.event.clientY : e.clientY; } // ***** popup_mouseup ********************************************************* function popup_mouseup(e) { var ie = navigator.appName == "Microsoft Internet Explorer"; var element = document.getElementById(popup_target); if (!popup_dragging) return; popup_dragging = false; if (ie) document.onselectstart = popup_oldfunction; else document.onmousedown = popup_oldfunction; } // ***** popup_exit ************************************************************ function popup_exit(e) { var ie = navigator.appName == "Microsoft Internet Explorer"; var element = document.getElementById(popup_target); popup_mouseup(e); element.style.display = 'none'; } // ***** popup_show ************************************************************ function popup_show(id, drag_id, exit_id, position, x, y, position_id) { var element = document.getElementById(id); var drag_element = document.getElementById(drag_id); var exit_element = document.getElementById(exit_id); var width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth; var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight; element.style.position = "absolute"; element.style.display = "block"; if (position == "element" || position == "element-right" || position == "element-bottom") { var position_element = document.getElementById(position_id); for (var p = position_element; p; p = p.offsetParent) if (p.style.position != 'absolute') { x += p.offsetLeft; y += p.offsetTop; } if (position == "element-right" ) x += position_element.clientWidth; if (position == "element-bottom") y += position_element.clientHeight; element.style.left = x+'px'; element.style.top = y+'px'; } if (position == "mouse") { element.style.left = (document.documentElement.scrollLeft+popup_mouseposX+x)+'px'; element.style.top = (document.documentElement.scrollTop +popup_mouseposY+y)+'px'; } if (position == "screen-top-left") { element.style.left = (document.documentElement.scrollLeft+x)+'px'; element.style.top = (document.documentElement.scrollTop +y)+'px'; } if (position == "screen-center") { element.style.left = (document.documentElement.scrollLeft+(width -element.clientWidth )/2+x)+'px'; element.style.top = (document.documentElement.scrollTop +(height-element.clientHeight)/2+y)+'px'; } if (position == "screen-bottom-right") { element.style.left = (document.documentElement.scrollLeft+(width -element.clientWidth ) +x)+'px'; element.style.top = (document.documentElement.scrollTop +(height-element.clientHeight) +y)+'px'; } drag_element['target'] = id; drag_element.onmousedown = popup_mousedown_window; exit_element.onclick = popup_exit; } // ***** Attach Events ********************************************************* if (navigator.appName == "Microsoft Internet Explorer") document.attachEvent ('onmousedown', popup_mousedown); else document.addEventListener('mousedown', popup_mousedown, false); if (navigator.appName == "Microsoft Internet Explorer") document.attachEvent ('onmousemove', popup_mousemove); else document.addEventListener('mousemove', popup_mousemove, false); if (navigator.appName == "Microsoft Internet Explorer") document.attachEvent ('onmouseup', popup_mouseup); else document.addEventListener('mouseup', popup_mouseup, false); END Javascript CODE CSS Code Start div.sample_popup { z-index: 1; } div.sample_popup div.menu_form_header { border: 1px solid black; border-bottom: none; width: 400px; height: 20px; line-height: 19px; vertical-align: middle; background: url('../images/form_header.png') no-repeat; text-decoration: none; font-family: Times New Roman, Serif; font-weight: 900; font-size: 13px; color: #FFFFFF; /*#206040;*/ cursor: default; } div.sample_popup div.menu_form_body { width: 400px; height: 200px; border: 1px solid black; background: url('../images/form.png') no-repeat left bottom; } div.sample_popup img.menu_form_exit { float: right; margin: 4px 5px 0px 0px; cursor: pointer; } div.sample_popup table { width: 100%; border-collapse: collapse; } div.sample_popup th { width: 1%; padding: 0px 5px 1px 0px; text-align: left; font-family: Times New Roman, Serif; font-weight: 900; font-size: 13px; color: #004060; } div.sample_popup td { width: 99%; padding: 0px 0px 1px 0px; } div.sample_popup form { margin: 0px; padding: 8px 10px 10px 10px; } div.sample_popup input.field { width: 95%; border: 1px solid #808080; font-family: Verdana, Sans-Serif; font-size: 12px; } div.sample_popup input.btn { margin-top: 2px; border: 1px solid #808080; background-color: #DDFFDD; font-family: Verdana, Sans-Serif; font-size: 11px; } CSS CODE END
You're using a JS/CSS popup, so just pass $row['job'] in your call to popup_show() (assuming you are able to modify or overload that JS function), and then populate it in the hidden field of your popup HTML with Javascript. The way you're doing it now, you'd have to duplicate the block of Popup HTML once for each row in your resultset for it to work.