So I've got a data table that is updated with two different sets of buttons. The jquery is thus;
$('body').on('click', "button", function () {
var $but_name = $(this).attr("name");
var $but_id = $(this).attr("id");
if($but_name==="sky_week") {
$("#adv_stats").load("index.php #adv_stats", {this_week:$but_id});
} else if($but_name==="ASC") {
$("#adv_stats").load("index.php #adv_stats", {up_down_type:"ASC",sort_type:$but_id});
} else if($but_name==="DESC") {
$("#adv_stats").load("index.php #adv_stats", {up_down_type:"DESC",sort_type:$but_id});
}
});
It literally just grabs the id of the button clicked and passes what was clicked to the load to refresh the data table.
(On an unrelated note, I'm new to jquery but I've got my load pointing at itself. So index.php is the page the code is on and I've just got it pointing at a div lower down to update that. It works - and shouldn't get stuck on an infinite loop because it's only triggered on clicks - but I feel like it's wrong and bad coding. Can someone confirm or deny this?)
The issue I have is that when you click the ASC or DESC buttons, it doesn't pull the week through because that's on a different button. I think it's because of the PHP at the top of the page that pulls it;
$this_week = $_POST['this_week'] ?? '202118';
$up_down = $_POST['up_down_type'] ?? 'ASC';
$sort = $_POST['sort_type'] ?? 'nt_login';
$breakdown = get_adv_breakdown($this_week, $sort, $up_down);
And it's because of the '?? '202118' bit, which is defaulting to 202118 as the week instead of the currently selected week.
How do I get it to update the ASC values and keep the currently selected week? I feel like I need to somehow store the week somewhere else, but this is hitting the limit of my jquery knowledge.
Here's a visual of the final page, showing the two different sets of buttons;
https://i.stack.imgur.com/UU8Kd.png
I've added the html that generates the buttons;
<td align="center">Advisor<button name="ASC" id="nt_login"><i class="arrow up"></i></button><button name="DESC" id="nt_login"><i class="arrow down"></button></td>
etc
etc
And a little loop that adds the last 12 weeks;
<div id="week-buttons">
<p align="center"><?php foreach($no_weeks as $week) { ?>
<button name="sky_week" class="sky-primary-button w-button" id='<?php echo h($week['Week']); ?>' onclick="this.blur();">
<?php echo h($week['Week']); ?>
</button>
<?php } ?></p>
</div>
It looks like you are reloading your page whenever you do a sort. In order to preserve the value of $this_week you will need to pass that as a $_POST value to your page when you fire .load()
It should be as simple as doing something like this:
$('body').on('click', "button", function () {
var $but_name = $(this).attr("name");
var $but_id = $(this).attr("id");
if($but_name==="sky_week") {
$("#adv_stats").load("index.php #adv_stats", {this_week:$but_id}); // this seems to be an error?
} else if($but_name==="ASC") {
$("#adv_stats").load("index.php #adv_stats", {up_down_type:"ASC",sort_type:$but_id, this_week: $this_week});
} else if($but_name==="DESC") {
$("#adv_stats").load("index.php #adv_stats", {up_down_type:"DESC",sort_type:$but_id, this_week: $this_week});
}
});
Related
so i have a php loop, i am using jquery slide toggle to hide/show a table with sql results. currently the table is loaded using php only, but as there is a lot going on its causing some loading problems i need to fire the ajax with the slide toggle btn, so it only requests the current items details when the button is pressed. i can get it to call the php file from the jquery but im having difficulty passing the value for each item across, so it can perform the request on the database. here is what the php foreach loop content looks like;
<span class="searchitem">
// some visible content here
<span value="item name" class="btn">button</span>
<span class="slide_area">
// hidden slide content ajax needs to populate with php result
</span>
</span>
this html is repeated i use jquery slidetoggle to hide the slide_area, what i need to do is populate the slide_area with results from php, the php file needs the name to return the results the name is passed via get with the url, so i only need append the url with the actual name from btn's value, im sure this cant be that difficult but here i am.
here's the jquery:
<script type="text/javascript">
//<![CDATA[
$(document).ready(function ()
{
$('.searchitem').each(function () {
$(this).find('.slide_area').hide();
$(this).find('.btn').click(function ()
{
var ajax_load = "<img src='images/spinner.gif' style='width:50px;' alt='loading...' />";
var loadUrl = "ajax/item.php?name=";
var loadName = $(".btn");
var Name = URLEncode(loadName);
var loadString = loadUrl + Name;
$(this).parent().find('.slide_area').slideToggle(1500).html(ajax_load).load(loadString);
});
});
});
//]]>
</script>
i need to get the value from btn and append the loadURL, im open to sending the data a different way like through post if needed, updated the jquery still not working what am i doing wrong here?
Thanks.
The easiest way would to use the Phery library http://phery-php-ajax.net/
the key here is the data-phery-remote="toggle" that will call the PHP function automatically on click, and can be reused everywhere
<span class="searchitem">
// some visible content here
<span value="item name" data-phery-remote="toggle" class="btn">button</span>
<span class="slide_area">
// hidden slide content ajax needs to populate with php result
</span>
</span>
The logic is reversed, the load will happen with only one AJAX call, instead of two.
Phery::instance()->set(array(
'toggle' => function($data){
$r = new PheryResponse;
/* do your code, fill $html_content */
$r->this()->siblings('.slide_area')->html($html_content)->toggle();
return $r;
}
))->process();
QUESTION: What is the proper way to use .get() in conjunction with .one() (or .live()) so that an external php file is appended only once?
MOST RECENT EDIT:
solution
<script>
$(document).ready(function(){
$('.tree li a').one("click", function() {
var currentAnchor = $('.tree li a').attr('href');
if(!currentAnchor){
var query = "page=1";
}
else
{
var splits = currentAnchor.substring(1).split('&');
//Get the section
var page = splits[0];
delete splits[0];
var query = "page=" + page;
alert ("page=" + page);
}
//Send the petition
$("#loading").show();
$.get("callbacks.php",query, function(data){
$("#content").append(data);
$("#loading").hide();
});
return false;
});
});
</script>
More Specifically:
I'm using Javascript and PHP to load some external PHP pages as sections in my main template.
I'm using a switch and append() so the included files keep appending. I need every file to be able to be appended ONLY ONCE. Here is the scenario as I'd like it to happen
1) downloads link is clicked
2) downloads.php appears
3) errors link is clicked
4) errors.php appears below downloads.php
5) downloads link is clicked again
6) page just scrolls up to top of downloads.php
I need the same functionality as the example on the documentation page of .one() where every div can be clicked only once.
I also looked at Using .one() with .live() jQuery and I especially liked the approach used in the accepted answer.
Iried using boolean flag as suggested below but all it did was limit my consecutive clicks on the same link to one. So if I click one link 1 multiple times it'll show page 1.php only once but if I click on link 1, then link 2, then link 1 again it will display page 1.php, then append page 2.php and append another page 1.php.
I'm starting to think that the setInterval is wrong and I may use .one() for the whole checkAnchor() function and bind it to the <a> tags. I tried this but it's not working either :(((
core.js - using .one()
var currentAnchor = null;
//$(document).ready(checkAnchor);
//Function which chek if there are anchor changes, if there are, sends the ajax petition checkAnchor
$("a").one("click", function (){
//Check if it has changes
if(currentAnchor != document.location.hash){
currentAnchor = document.location.hash;
//if there is not anchor, the loads the default section
if(!currentAnchor){
query = "page=1";
}
else
{
//Creates the string callback. This converts the url URL/#main&id=2 in URL/?section=main&id=2
var splits = currentAnchor.substring(1).split('&');
//Get the section
var page = splits[0];
delete splits[0];
var query = "page=" + page;
}
alert ("hello");
//Send the petition
$("#loading").show();
$.get("callbacks.php",query, function(data){
$("#content").append(data);
$("#loading").hide();
});
}
});
The other thing I liked as an approach is adding the names of the pages to an array and then checking that array to make sure the page wasn't displayed yet. I managed to fill up an array with the page names using .push() but I hit a dead end when looking up for a value in it. If you have an idea how that's supposed to look like that'd be very helpful as well.
core.js
///On load page
var contentLoaded;
$().ready(function(){
contentLoaded = false;
setInterval("checkAnchor()", 300);
alert (contentLoaded);
});
var currentAnchor = null;
//Function which chek if there are anchor changes, if there are, sends the ajax petition
function checkAnchor(){
//Check if it has changes
if(currentAnchor != document.location.hash){
currentAnchor = document.location.hash;
//if there is not anchor, the loads the default section
if(!currentAnchor){
query = "page=1";
}
else
{
//Creates the string callback. This converts the url URL/#main&id=2 in URL/?section=main&id=2
var splits = currentAnchor.substring(1).split('&');
//Get the section
var page = splits[0];
delete splits[0];
var query = "page=" + page;
}
alert ("hello");
//Send the petition
$("#loading").show();
alert (contentLoaded);
if (!contentLoaded){
$.get("callbacks.php",query, function(data){
$("#content").append(data);
$("#loading").hide();
});
alert (contentLoaded);
}
contentLoaded = true;
}
}
here is my
callbacks.php
<?php
//Captures the petition and load the suitable section
switch($_GET['page']){
case "4100errors" :
include 'template/4100errors.php';
break;
case "4100downloads" :
include 'template/4100downloads.php';
break;
}
?>
And my main file
4100.php
<?php
include 'template/header.php';
include 'template/4100menu.php';
include 'template/log.php';
include 'template/links.php';
include 'template/4100breadcrumbs.php';
?>
<div class="left-widget">
<div style="display:none; position:absolute; top:-9999; z-index:-100;">
</div>
<div id="side-nav-bar" class="Mwidget">
<h3>Contents</h3>
<ul class="tree">
<li><a href="#4100downloads" class="links" >Downloads</a> </li>
<li>Error Troubleshooting</li>
</ul>
</div>
</div>
<div id="content" style="margin-top:100px; margin-left:300px;">
<?
switch ($_GET['page'])
{
case "4100downloads": include 'template/4100downloads.php'; break;
case "4100errors": include 'template/4100errors.php'; break;
}
?>
</div>
</body>
</html>
4100dowloads.php
Downloads test page
4100error.php
Errors test page
Also you can look at the test page here http://period3designs.com/phptest/1/4100.php
"What is the proper way to use .get() in conjunction with .one() (or .live()) so that an external php file is appended only once?"
.one() and live() really have little to do with $.get. They're only for event handling.
If you intend to run the code every 50ms as you are, but want to replace the current content, then use .html() instead of .append().
$("#content").html(data);
This will overwrite the old content.
I assume you're aware of this, but just to be sure, your code is running at an interval because of this...
$().ready(function(){
setInterval("checkAnchor()", 50); // better--> setInterval(checkAnchor, 50);
});
If you only want it once on document load, then do this...
$(document).ready(checkAnchor);
Just use a boolean flag to determine if you loaded the data yet or not. Set it to false on page load, and just after the call to $.get set it to true. Then, wrap your $.get with an if (!contentLoaded) { $.get ... }.
That way you will execute the $.get only once.
BTW: $.one is used to bind an event to an element, that will execute only once and then unbind it self from it.
For starters, here is my php:
$id2 = mysql_real_escape_string($id2);
$getdata8 = mysql_query("SELECT * FROM musicbook WHERE identify='$identify' ORDER BY id DESC LIMIT 20");
$numrowsgetdata = mysql_num_rows($getdata8);
if ((mysql_num_rows($getdata8))<1)
{
echo "<i>Be the first to say something?</i><p/>";
}
while ($row8 = mysql_fetch_assoc($getdata8))
{
$id8 = $row8['id'];
$name8 = $row8['name'];
$message8 = $row8['message'];
$message10 = nl2br($message8);
$date8 = $row8['date'];
if ($name8==$username)
{
echo "
<div class='messagediv' style='background:#1A1A1A;'><div style='padding:5px;'>$message10<br/>
<div style='margin-top:4px; font-size:.8em; float:left;'><div style='float:left;'><a href='http://www.pearlsquirrel.com/$name8' style='color:white;'>$name8</a><font style='color:#D6D6D6'> on $date8</font></div>
<input type='hidden' id='wpm2' value='$id8'><input type='button' id='deletelistenchat' class='deletelistenchat' style='display:none;' onclick='LinkOnClick2($id8); loadlistenchat();' value='(delete?)' /></div></div></div>
";
}
else
{
echo "
<div class='messagediv'><div style='padding:5px;'>$message10<br/>
<div style='margin-top:4px; font-size:.8em; float:left;'><div style='float:left;'><a href='http://www.pearlsquirrel.com/$name8' style='color:white;'>$name8</a><font style='color:#D6D6D6'> on $date8</font></div>
</div></div></div>";
}
}
if($numrowsgetdata >= 20)
{
echo "<div id='loadingcomments'><img src='loading.gif' style='height:30px; width:30px;'></div>";
}
?>
Here is my jquery:
$('.messagediv').live('mouseover mouseout', function(event) {
if (event.type == 'mouseover') {
document.getElementById('deletelistenchat').style.display='block';
} else {
document.getElementById('deletelistenchat').style.display='none';
}
});
Now what I want to happen is that for each .messagediv div when you hover over it, it shows the delete button, #deletelistenchat. However, it only works for the last row of each mysql query and I want the hover effect to work on each one as a user hover over it. For example, if I hover over the first post by a user, the hover effect activates on the last post retrieved by the mysql query. I have been trying to figure this out for some time now, and am lost as anything. Help would be appreciated.
ID's are unique. You are using the same ID over and over, because of this, the DOM is only finding the last element with that ID -- that's the intended effect, it's a result of how you wrote your php.
<input type='button' id='deletelistenchat'
Remove the ID from this button. You already have the class here.
let's change your hover event.
$(function(){
$('.messagediv').on('mouseover', function() {
$(this).find('.deletelistenchat').css('display', 'block');
}).on('mouseout', function(){
$(this).find('.deletelistenchat').css('display', 'none');
});
});
*Edit*
DOM Behavior wasn't functioning as expected because I didn't clearly look at your markup, that's my fault. Made it jQuery 1.7 worthy, and separated your mouseover and mouseout statements to be able to clearly see them.
The working Fiddle -> http://jsfiddle.net/6MpX9/
I am trying to do pagination using javascript but all in vain, please help..
<script language="Javascript">
function nextclicked()
{
document.getElementById("clickednext").value = document.getElementById("clickednext").value + 1;
document.forms["newsmanager"].submit();
}
</script>
<form name = "newsmanager" method="post" action="NewsManager.php">
<input type = "hidden" id="clickednext" name="clickednext" >
if(isset($_POST['clickednext']) && $_POST['clickednext']>=1)
{
$_POST['clickednext'] = $_POST['clickednext'] +9;
$NewsQuery = "SELECT NewsDetails FROM News LIMIT " .$_POST['clickednext']. ",10";
}
else
{
$NewsQuery = "SELECT NewsDetails FROM News LIMIT 0,10";
}
$result = mysqli_query($dbc,$NewsQuery);
}
UPDATE :
<div class=d2 align=left>
<a href="#" onclick=" nextclicked(); submit();" >
Next
</a>
UPDATE ENDS......
The first time when i click the Next hyperlink label, then it works, that is, 10 is assigned $_POST['clickednext'] and the next 10 values appear from the database, but the second time i click the label , then it doesn't?
Your code is completely wrong.
You should scrap it and start all over again.
I will show you how to do so.
I have a rule when it comes to Ajax, and it goes like this.
If you cannot do the functionality without Ajax, there's no way you should attempt to do it with Ajax.
If you know anything about javascript, you'll know that XmlHttpRequest makes working with Ajax hellish. Hence why we have javascript frameworks such as JQuery and Mootools. You might also like a php ajax framework called PHPLiveX. I only use JQuery, so here's how to do the solution in JQuery.
Step 1: Strip your ajax and create the solution in php
This pagination tutorial in php will help.
Step 2a: Create the ajax with PHPLiveX
PHPLiveX is really cool and underated, as it allows you to use php functions without reloading the whole page, in a more convienient way, than if you'd used javascript.
PHPLiveX will help you the best.
It's pretty straightforward. You call a php function to do something, return some values, and choose the target: of where you want the values to go.
I personally would use PHPLiveX for this job, as it's better suited. JQuery is more for postdata.
Step 2b: Create the ajax in JQuery
I'm going to assume that you know how to select elements by id with JQuery and append or replaceWith them. If not you can look the function up.
Below is the code required to submit a POST or GET with JQuery. Adapt this to your code. You'll have to modify the code below to add appending and stuff.
$(".tornfieldcard").click(function() {
var dataString = $("#addfieldForm").serialize();
//lets get the form data and use that
var newValue = $("#newValue").val();
var itemid4 = $(this).attr("itemid4");
var dataString = "itemid=" + itemid + "&newValue=" + newValue;
//or get the attr/valu from elements
$("#loading5").show();
$("#loading5").fadeIn(400).html('<img src="icons/loading.gif">');
$.ajax({
type: "POST",
url: "ajaxcontrols.php",
data: dataString,
cache: false,
success: function(html){
$("#loading5").remove();
$(".fieldcardNEW").fadeOut('slow');
$('.fieldcardNEW').remove();
$("#conveyorbelt_"+itemid4+"").append("<div class=\"fieldcard\"><b>"+attribute+"</b> <br><div itemid=\""+itemid4+"\" attribute=\""+attribute+"\">"+value+"</div></div>");
}
});
Here's a little algorithm I wrote using php to create pagination:
$x=$numStories;
$y=$x%5;
$z=($x-$y)/5;
if($y!=0){
$numPages=$z+1;
}
else{
$numPages=$z;
}
Where 5 is the number of stories per page, and $numStories is the total amount of stories (or in your case, news articles) you wish to use.
Then, just display the amount of pages ($numPages) in any way you'd like, and your good to go.
[EDIT]
I created an archive.php page, that took a page number as a GET parameter (archive.php?page=3). From there, I selected the first five entries in my database after $pageNum (in this case 3) * 10 (or however many posts per page you are wanting to display.
The best thing to do is make as much of your code dynamic and flexible, so that it is self sustaining.
[EDIT 2]
<script>
function nextclicked()
{
document.forms["newsmanager"].submit();
}
</script>
<?php
$currentPage = $_POST['page'];
$numStories = //get the total amount of entries
$x=$numStories;
$y=$x%10;
$z=($x-$y)/10;
if($y!=0){
$numPages=$z+1;
}
else{
$numPages=$z;
}
if(isset($currentPage) && $currentPage>=1)
{
$currentPage = $currentPage +9;
$NewsQuery = "SELECT NewsDetails FROM News LIMIT " .$currentPage. ",10";
}
else
{
$NewsQuery = "SELECT NewsDetails FROM News LIMIT 0,10";
}
$result = mysqli_query($dbc,$NewsQuery);
}
?>
<form>
<input type='hidden' name='page' text='' value='<?php echo "$currentPage"' />
</form>
Next-->
PHP is server-side language. you have to put your php code to
<?php
=====
<script language="Javascript">
function nextclicked()
{
document.getElementById("next").value = document.getElementById("next").value + 1;
document.forms["newsmanager"].submit();
}
</script>
<form name = "newsmanager" method="post" action="NewsManager.php">
<input type = "hidden" id="clickednext" name="clickednext" >
<?php
if(isset($_POST['clickednext']) && $_POST['clickednext']>=1)
{
$_POST['clickednext'] = $_POST['clickednext'] +9;
$NewsQuery = "SELECT NewsDetails FROM News LIMIT " .intval($_POST['clickednext']). ",10";
}
else
{
$NewsQuery = "SELECT NewsDetails FROM News LIMIT 0,10";
}
$result = mysqli_query($dbc,$NewsQuery);
}
?>
additionally, user can't click to hidden form field. you need, for example button and have onclick event ready
<button name="next" value="1" onclick="nextclicked();">Next</button>
Let me post the code first.
function alertCallback<?=$position_info['id']?>()
{
var id = <?=$position_info['id']?>;
var itemname= '<?=$na?>';
<?PHP if($position_info['name'] == $wposition){ ?>
var reward = '<?= $itmname ?>';
$('#selected_item').html(''+itemname+reward);
<?PHP item_add($_SESSION['userid'],$itmid,1); } else { ?>
var noreward = 'You Found Nothing!';
$('#selected_item').html(''+itemname+noreward);
<?PHP } ?>
}
The above is working to an extent. The page is a image map where if you click on the right spot then you get an item. It is currently working where if you click on the right spot you get the item. Or get told you found nothing.
The problem I have is that the page reloads to set new positions
<script type="text/javascript">
//one seconds=1000 micro seconds
setInterval(function() {
$('#load').load('itemclick_ajax.php');
},60000);
</script>
but another item is won as long as the page is displayed. Any ideas on how to stop this occuring. If i keep the browser showing the page then im running up to thousands of items won.
Are you trying to stop the page reload?
Try adding "return false;" at the end of your Javascript function.