I'm trying to pass a variable from JS to PHP but so far no luck. I've been searching here for solution, but it seems that nothing helps..
Ok, I have php file with pagination:
$pagination .= '<li>'.$i.'</li>';
Paginate_click launches js function:
$(".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("views/fetch_articles.php", {'page':(page_num-1)}, function(){
$(window).scrollTop(0);
});
$.post('views/articles_list.php', {'page':(page_num)});
$(this).addClass('active'); //add active class to currently clicked element (style purpose)
return false; //prevent going to herf link
});
In php file I need information which page of pagination I'm currently on so I want to retrieve page_num value back to my php. I tried this:
$.post('views/articles_list.php', {'page':(page_num)});
And in php:
$page_number = $_POST["page"];
I tried also many other options, but nothing helps. I thought it will be easier :/
As you probably noticed there's another php file (fetch_articles.php) and in this case $_POST["page"]; works. But for articles_list.php I can't use load function.
EDIT: What I want and entire code.
I have simple and nice pagination. The only problem is that it has no option for prev/next and it shows all the buttons. It's a problem when you have a lot of pages. So my idea is to shrink it down and instead of heaving 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,15,16,17,18,19 and so on I want this:
prev,1,2,3...67,68,next. To do this I need to pass to my php file an information about actual page. With this variable I can calculate everything and organize my pagination with for/if/else statements.
The code.
articles_list.php:
<?php
include("../config/connection.php");
include('../config/css.php');
$results = mysqli_query($dbc_connection,"SELECT COUNT(*) FROM articles");
$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
if($pages > 1)
{
$pagination = '';
$pagination .= '<ul class="paginate">';
for($i = 1; $i<=$pages; $i++)
{
$pagination .= '<li>'.$i.'</li>';
}
$pagination .= '<li>'.$page_number.'</li>'; // only to check if variable is passed
$pagination .= '</ul>';
}
?><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="js/jquery-1.9.0.min.js"></script>
<script type="text/javascript" src="js/pagination.js"></script>
</head>
<body>
<?php $page_number = $_POST["page"];
echo $page_number; // only to check if variable is passed ?>
<div id="results"></div>
<?php echo $pagination; ?>
</body>
</html>
pagination.js:
$(document).ready(function() {
$("#results").load("views/fetch_articles.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("views/fetch_articles.php", {'page':(page_num-1)}, function(){
$(window).scrollTop(0);
});
$.post('views/articles_list.php', {page:page_num}, function(data){});
$(this).addClass('active'); //add active class to currently clicked element (style purpose)
return false; //prevent going to herf link
});
});
fetch_articles.php:
<?php
include("../config/connection.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.
$result = mysqli_query($dbc_connection,"SELECT * FROM articles ORDER BY id DESC LIMIT $position, $item_per_page");
//output results from database
while($row = mysqli_fetch_array($result))
{
?>
<h2><?php echo $row['title']; ?></h2>
<p><i><?php echo 'By '.$row['author']; ?></i></p>
<p><?php echo $row['header']; ?></p>
Read<br>
<hr>
<?php
}
?>
Try removing the parenthesis around page_num:
$.post('views/articles_list.php', {'page':page_num});
You didn't said in which one of the requests you can't get the value you're trying to pass. So, I'm guessing it is in the first one:
$("#results").load(...);
The problem here is that you're using the .load() method, which is equivalent to .get(). So, when you try, in the PHP file to get $_POST["page"], it will not be there, because it is actually in the $_GET array.
I may be missing something here, but couldn't you just append a query string to the url manually?
$.post('views/articles_list.php?pn=' + page_num);
Then in your fetch_articles.php you just pull it off with
$page_number = $_GET["pn"];
If that fails you can always use a cookie.
Instead of
$.post('views/articles_list.php', {'page':(page_num)});
try
$.post('views/articles_list.php', {page:page_num}, function(data){
console.log(data);
},'json');
And also double check if 'views/articles_list.php' is the correct path. If you were using Chrome, kindly read the parsing via right click -> inspect elements -> Network.
Addition(After posted your edit code) :-
Please remove the Doctype and HTML and leave something like this.
<?php
include("../config/connection.php");
include('../config/css.php');
$results = mysqli_query($dbc_connection,"SELECT COUNT(*) FROM articles");
$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
if($pages > 1)
{
$pagination = '';
$pagination .= '<ul class="paginate">';
for($i = 1; $i<=$pages; $i++)
{
$pagination .= '<li>'.$i.'</li>';
}
$pagination .= '<li>'.$page_number.'</li>'; // only to check if variable is passed
$pagination .= '</ul>';
}
//Assuming you're doing ajax here. so either pagination or page number posting back? if both try below.
$page_number = $_POST["page"];
echo json_encode(array("pagination"=>$pagination,"pageNumber"=>$page_number));
?>
Hope it helps.
Related
I have the following problem on my wordpress project :
I have 2 div call "div_sc_1" and "div_sc_2" which are hidden on my page.
I want to show them with a jQuery function .show() if they are not "checked". "Checked" status is writen in my db.
With my actual code, If only div_sc_1 or div_sc_2 is not "checked", everything is allright BUT if both of the 2 divs are not checked, only one is displaying and I don't understand why.
This is my code :
foreach($list_id_scores as $scores){
$id_s = $scores->id_score;
$checked = $wpdb->get_var( "SQL query for 'checked' status");
if($checked == "1"){
echo " score n°".$id_s." is over<br />";
}else{
$div_id = "div_sc_".$id_s;
echo $div_id; /// this echo show me that my loop is working
?>
<script>
var div_sc = <?php echo json_encode($div_id); ?>;
jQuery(document).ready(function(){ jQuery("#"+div_sc).show(); });
</script>
<?php
}
}
What is the problem for you ? Thanks for your time
You're defining a global variable div_sc multiple times. All <script> tags share the same scope, so only one value is retained. The .ready() handler only executes after all variables have been defined (and the rest of the page has finished loading), not in between.
It might be better to do this instead:
<script>
jQuery(document).ready(function(){
<?php
foreach($list_id_scores as $scores){
$id_s = $scores->id_score;
$checked = $wpdb->get_var( "SQL query for 'checked' status");
if($checked == "1"){
echo " score n°".$id_s." is over<br />";
}else{
$div_id = "div_sc_".$id_s;
echo $div_id; /// this echo show me that my loop is working
?>
jQuery("#"+<?php echo json_encode($div_id); ?>).show();
<?php
}
}
});
</script>
I have a 'display all' functionality on my site. Currently there are 7 sub-folders that are iterated through to display categories. (Empty folders are not shown, and more sub-folders may be added).
I don't want to set a limit [of images] per page, i just want to show all of the images for each folder on a different page.
Despite extensive googling and experimenting, the best i could come up with was a number of html pages being displayed, all appended one to the other, on one long page. (ugh!) I've been at it now since last night so i'm a bit fed up.
I have stripped back my displayall.php to it's basic functionality. Here's what it looks like at the moment (with no pagination):
<!doctype html>
<html>
<head>
<meta charset='utf-8'>
<link rel='stylesheet' type='text/css' href='css/bootstrap_combined.css'>
<link rel='stylesheet' type='text/css' href='css/style.css'>";
<title>Gallery Display</title>
</head>
<body>
<div id="wrapper">
<header>
<h1>The Ultimate Gallery Compiler</h1>
<div id='menu'><a class='head' href='index.html'>Upload Photo</a> <a class='head' href='gallery.html'>Browse Gallery</a></div>
</header>
<!---end header-->
<div id='content'>
<h2>Gallery: All Images</h2>
<?php
//$pages = isset($_GET['page'])?intval($_GET['page']-1):0; //get page
//$pageno = $_REQUEST['page'];
//compile an associative array
$subfolder= array('Fashion/LifeStyle'=>'1', 'Music/Video'=>'2','Sport/Leisure'=>'3','Electronics/Technology'=>'4','Pets/Animals'=>'5','Health/Beauty'=>'6','Other'=>'7' );
$carray=count($subfolder);
// iterate through the sub directories, and count them
$files = "images/*/*";
$sub=0;
foreach(glob($files) as $file)
{
$sub++; //total number of images
}
foreach ($subfolder as $subf=>$value)
{
$folder = "images/".$value."/";
$link = 'displayall.php?'.$value;
$mykey= $subf;
$counter = 0;
// Open the appropriate subfolder, and display its contents.
if ($dir = opendir($folder)) {
$images = array();
while (false !== ($file = readdir($dir))) {
if ($file != "." && $file != "..") {
$counter++;
$images[] = $file;
}
}
closedir($dir);
}
//don't show empty categories
if ($counter!== 0){
echo "<input type='hidden' id='current_page'/>";
echo "<input type='hidden' id='show_per_page' />";
echo "<h3>Category: ".$mykey."</h3><br>"; //display heading
echo "<h4>There are " .$sub. " photos in the <a href='gallery.html'>Gallery</a> to date</h4>"; //display total overall
echo '<div id="multi">';
foreach($images as $image) {
echo '<span class="gallery"><img src="';
echo $folder.$image;
echo '" alt="" width="200" height="auto" /></span>'; //show images
}
echo '</div>';
//$num= $pages +1;
echo "<br><strong>".$counter. " photos</strong><br>"; //display total per category
echo "<span id='pageNo'>Page Number: ".$value."</span><br>";
echo "Next";
echo "<br><br><hr><br>"; //put space and a line between the categories
};
//$pageno++;
}
?>
<footer>
<p class='foot'>© Copyright 2015-2016 MMA2 Rachel Gallen, Ysabel Pheifer and Rebecca Merrigan.</p>
</footer>
</div>
</body>
</html>
(It can be viewed here)
Any help on the pagination would be appreciated. All the tutorials seem to be either mysql related or dealing with a single array. V frustrating!
(open to php, jquery, javascript or bootstrap solutions!)
Thanks and happy chrimbo
Rachel
edit: former edit removed
Your page is looping through all the subfolders, it looks like an attempt was made to only display subfolder being specified by the querystring parameter page. This can be accomplished with a minor edit to your PHP:
<?php
$pages = isset($_GET['page'])?intval($_GET['page']):1; //get page
//$pageno = $_REQUEST['page'];
//compile an associative array
$subfolder= array('Fashion/LifeStyle'=>'1', 'Music/Video'=>'2','Sport/Leisure'=>'3','Electronics/Technology'=>'4','Pets/Animals'=>'5','Health/Beauty'=>'6','Other'=>'7' );
$carray=count($subfolder);
// iterate through the sub directories, and count them
$files = "images/*/*";
$sub=0;
foreach(glob($files) as $file)
{
$sub++; //total number of images
}
$value = $pages;
$folder = "images/".$value."/";
$link = 'displayall.php?page='.$value + 1;
//$mykey= $subf;
$arrayKeys = array_keys($subfolder);
$mykey = $arrayKeys[$value];
$counter = 0;
// Open the appropriate subfolder, and display its contents.
if ($dir = opendir($folder)) {
$images = array();
while (false !== ($file = readdir($dir))) {
if ($file != "." && $file != "..") {
$counter++;
$images[] = $file;
}
}
closedir($dir);
}
//don't show empty categories
if ($counter!== 0){
echo "<input type='hidden' id='current_page'/>";
echo "<input type='hidden' id='show_per_page' />";
echo "<h3>Category: ".$mykey."</h3><br>"; //display heading
echo "<h4>There are " .$sub. " photos in the <a href='gallery.html'>Gallery</a> to date</h4>"; //display total overall
echo '<div id="multi">';
foreach($images as $image) {
echo '<span class="gallery"><img src="';
echo $folder.$image;
echo '" alt="" width="200" height="auto" /></span>'; //show images
}
echo '</div>';
//$num= $pages +1;
echo "<br><strong>".$counter. " photos</strong><br>"; //display total per category
echo "<span id='pageNo'>Page Number: ".$value."</span><br>";
echo "Next";
echo "<br><br><hr><br>"; //put space and a line between the categories
};
//$pageno++;
?>
Summary of Changes:
I un-commented the $pages variable so it pulls from the query string parameter.
It also looks like you tried to send that query string via the $link variable, but the format was not correct. I updated that to $link = 'displayall.php?page='.$value + 1;
Finally, I removed the for loop and set $value to the current $page parameter so only one subfolder would be shown on a page.
Changes Made After Edit #1
The ternary operation on $pages was setting the value to 0, resulting in the error when looking for /images/0/. Changed to $pages = isset($_GET['page'])?intval($_GET['page']):1;
Added an array to handle the keys from the associative array, since the querystring is using integer values instead of category names.
$arrayKeys = array_keys($subfolder);
$mykey = $arrayKeys[$value];
You might want take a long hard look at passing string values instead of integer values to $page. It'll make for better SEO, better folder names, and removes the need to have an associative array to map the integers to a category name and back again.
Final Notes:
This certainly has room for expansion, you might consider error checking to make sure the value is inbounds and the folder is valid. Previous and next links, and quick navigation to a specific page number might also be useful.
Hope that helps!
I have a dynamic site that loads only the body when a usr clicks a page. I am trying t change the title tag, but am getting no luck.
HTML:
<head>
// Title tag is contained in the php file
<?php include (BASEPATH . "includes/widgets/pageTitle.php"); ?>
</head>
JavaScript/jQuery:
$(document).on('click', 'a', function(e) {
// Page url of destination
var pageurl = $(this).attr('href');
var baseurl = "http://localhost/offstreams/";
// prevent page from loading
e.preventDefault();
// Empty info inside the body class and reload new info
// THIS WORKS PERFECTLY
$('.body').empty().load(pageurl + " > .body > *");
//!!!!!!!!!!!!!!!!!!!!!
// THIS IS THE PROBLEM
//!!!!!!!!!!!!!!!!!!!!!
$('title').empty().load(pageurl + "> title > *");
// Push the URL state
if(pageurl!=window.location){
window.history.pushState({path:pageurl},'',pageurl);
}
//stop refreshing to the page given in
return false;
}
});
A Snippet of PHP code:
//Band page title tag
if (isset($_GET['member']) && isset($_GET['edit']) && isset($_GET['band'])){
$band_id = $_GET['band'];
$sql = "SELECT `band_name` FROM `bands` WHERE `band_id` = '$band_id'";
$query = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($query)){
$band_name = $row['band_name'];
echo "<title>" . $band_name . " | " . "Offstreams</title>";
}
An example output on actual load would be Count to Four | Offstreams, which is what I want.
When I do the ajax load, the website works, but the title tag gives the default url like localhost/offstreams/etc... and the title tag turns into
<title>
<title>Count to Four | Offstreams</title>
</title>
Does anyone know why?
It looks like you're doubling up on title tags there, the $('title').empty() bit will be leaving the previous ones there.
Try putting the title tags in your initial html:
<head>
// Title tag is contained in the php file
<title><?php include (BASEPATH . "includes/widgets/pageTitle.php"); ?></title>
</head>
And removing them from your php:
echo $band_name . " | " . "Offstreams";
I don't understand the reason for outputting the title in a loop since there is only one per page, unless I am missing something in your code. Seems like it needs to be outside.
if (isset($_GET['member']) && isset($_GET['edit']) && isset($_GET['band'])){
$band_id = $_GET['band'];
$sql = "SELECT `band_name` FROM `bands` WHERE `band_id` = '$band_id'";
$query = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($query)){
$band_name = $row['band_name'];
}
echo "<title>" . $band_name . " | " . "Offstreams</title>";
}
In regards to your JQuery script, keep this in mind from the .load() documentation:
jQuery uses the browser's .innerHTML property to parse the retrieved
document and insert it into the current document. During this process,
browsers often filter elements from the document such as <html>,
<title>, or <head> elements. As a result, the elements retrieved by
.load() may not be exactly the same as if the document were retrieved
directly by the browser.
In other words, what you're doing may not work properly all the time with all browsers. With that in mind, give this a try.
$(document).on('click', 'a', function(e) {
// Page url of destination
var pageurl = $(this).attr('href');
// prevent page from loading
e.preventDefault();
// Empty info inside the body class and reload new info
// THIS WORKS PERFECTLY
$('.body').empty().load(pageurl + " > .body > *");
// Give this a try
$(pageurl).load(pageurl, function() {
$('title').load('title', function() {
document.title = $(this).text();
});
});
// Push the URL state
if(pageurl !== window.location){
window.history.pushState({path:pageurl},'',pageurl);
}
//stop refreshing to the page given in
return false;
});
I want to use AJAX/Javascript with PHP to carry out this following function and not have it all done by PHP itself. I have created a function which deletes an item from the MySQL database. It gives a validation to the user if they want to remove it by selecting Yes or No.
However, how would i change this so that it does the same function but the validation appears as a popupbox, and when Yes or OK is pressed it deletes the item from the database and reloads the page to show it has been removed.
I have provided the PHP code which relates to this function, but i want to specifically change this to using AJAX/Javascript as well in accordance with PHP.
<?php
// Delete Item Question to Admin, and Delete Product if they choose
if (isset($_GET['deleteid'])) {
echo 'Do you really want to delete product with ID of ' . $_GET['deleteid'] . '? Yes | No';
exit();
}
if (isset($_GET['yesdelete'])) {
// remove item from system and delete its picture
// delete from database
$id_to_delete = $_GET['yesdelete'];
$sql = mysqli_query($link,"DELETE FROM products WHERE id='$id_to_delete' LIMIT 1") or die (mysql_error());
// unlink the image from server
// Remove The Pic -------------------------------------------
$pictodelete = ("../inventory_images/$id_to_delete.jpg");
if (file_exists($pictodelete)) {
unlink($pictodelete);
}
header("location: inventory_list.php");
exit();
}
?>
<?php
// This block grabs the whole list for viewing
$product_list = "";
$sql = mysqli_query($link,"SELECT * FROM products ORDER BY date_added DESC");
$productCount = mysqli_num_rows($sql); // count the output amount
if ($productCount > 0) {
while($row = mysqli_fetch_array($sql)){
$id = $row["id"];
$product_name = $row["product_name"];
$price = $row["price"];
$stock = $row["stock"];
$date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));
$product_list .= "Product ID: $id - <strong>$product_name</strong> - £$price - Stock: $stock - <em>Added $date_added</em> <a href='inventory_edit.php?pid=$id'>edit</a> • <a href='inventory_list.php?deleteid=$id'>delete</a><br />";
}
} else {
$product_list = "You have no products listed in your store yet";
}
?>
Your JS-File
$(document).ready(function() {
$('.delete').click(function() {
event.preventDefault();
var deleteId = $(this).parent().attr('id').val();
$.get('path/to/you/phpfile', {deleteId: deleteid}, function(data) {
var confirm = confirm(data);
if (confirm==true) {
$.get('path/to/you/phpfile', {yesdelete: 1});
}
});
});
});
In your PHP-File you have to remove header('Location: ...') and the block which grabs the list, wrap it in a function or etract it to another php file to call it with the a simliar ajax-command I used above. And you have to change th $product_list in the while-loop.
Product ID: <div id="$id">$id - <strong>$product_name</strong> - £$price - Stock: $stock - <em>Added $date_added</em> <a href='inventory_edit.php?pid=$id'>edit</a> • <div class="delete">Delete</div></div><br />
jQuery get the id-value of his parent-div. It´s actually not the best way, but something like this should work.
I am using a joomla module i would like to modify to auto load the default list of results.
currently, when the page loads no result is shown. If all search fields are empty and the user clicks the search button, the page will load all data. If information in placed in the search fields, the results will be broken down to match what was typed in.
I want the page to auto load all data when the page loads without the user clicking search.
How do i achieve this?
I believe the module uses ajax and i believe the info that affects this is below:
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: text/html');
define('_JEXEC', 1);
define('DS', DIRECTORY_SEPARATOR);
ini_set("display_errors", "On");
error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE & ~E_WARNING);
$my_path = dirname(__FILE__);
$my_path = explode(DS.'modules',$my_path);
$my_path = $my_path[0];
if (file_exists($my_path . '/defines.php')) {
include_once $my_path . '/defines.php';
}
if (!defined('_JDEFINES')) {
define('JPATH_BASE', $my_path);
require_once JPATH_BASE.'/includes/defines.php';
}
require_once JPATH_BASE.'/includes/framework.php';
$app = JFactory::getApplication('site');
$app->initialise();
///////////////////////////////////////////////////////////////////////////////////////////////
$name = $_GET['name'];
$value = mb_strtolower($_GET['value']);
$next = mb_strtolower($_GET['next']);
$db = JFactory::getDBO();
$query = "SELECT * FROM #__k2_extra_fields WHERE published = 1";
$db->setQuery($query);
$results = $db->loadObjectList();
$extra_val = '';
$extra_id = 0;
foreach($results as $result) {
if(trim(mb_strtolower($result->name)) == trim($value) . " " . trim($next) || trim(mb_strtolower($result->name)) == trim($next) . " " . trim($value)) {
$extra_val = $result->value;
$extra_id = $result->id;
break;
}
}
require_once(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_k2'.DS.'lib'.DS.'JSON.php');
$json = new Services_JSON;
$extra_val = $json->decode($extra_val);
if($extra_val != '') {
foreach($extra_val as $val) {
echo "<option>" . $val->name . "</option>";
}
echo "<option>".$extra_id."</option>";
}
?>
Please help!
to auto load search result we must need to store search query in session variable,
http://docs.joomla.org/How_to_use_user_state_variables
http://docs.joomla.org/API15:JApplication/getUserStateFromRequest
This are the links which will describe very well about how to manage request variable in session, so there is no variable in request it will get value from the session.
try to use something like this
<html>
<head>
<script>
function myFunction()
{
alert("Page is loaded");
}
</script>
</head>
<body onload="myFunction()">
<h1>Hello World!</h1>
</body>
</html>
then you can easily change myFunction to trigger your search on click event
<script>
function myFunction()
{
document.getElementById('YOUR-BUTTON-ID').onclick();
}
</script>