Jquery with PHP problem - php

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.

Related

Using Previous Value In jquery .load data refresh

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});
}
});

Ajax visit link without actually visiting link

I've got a basic like button concept on my site that visits url.tld?action=love and adds +1 to the link's database column.
It's a hassle redirecting to another page all the time though. Is it possible to click the button, and send a request to the URL without actually redirecting to a new URL? Also maybe refresh the button afterwards only so that the count updates?
For a general idea of what my download button is this is in the header:
<?php require_once('phpcount.php'); ?>
<p class="hidden"><?php
$time = time();
for($i = 0; $i < 1; $i++)
{
PHPCount::AddHit("$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]", "127.0.0.1");
}
echo (time() - $time);
/*echo "PAGE1 NON: " . PHPCount::GetHits("page1") . "\nPAGE1 UNIQUE: " . PHPCount::GetHits("page1", true);
echo "\n\n" . PHPCount::GetHits("page2");
$ntot = PHPCount::GetTotalHits();
$utot = PHPcount::GetTotalHits(true);
echo "###$ntot!!!!$utot";*/?></p>
And this is an example of my "love" button.
Love <span class="count">'. PHPCount::GetHits("$package_get?action=love", true).'</span>
The reason I used this method is because people create pages, and I wanted the like button to work out of the box. When their page is first visited it adds their url to the database, and begins tallying unique hits.
This is basically adding a new link column called downloadlink?action=love, and tallying unique clicks.
use the following code. assgin id="btn_my_love" to that button and add this code to you page
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
//assign url to a variable
var my_url = <?php echo "https://alt.epicmc.us/download.php?link='.strip_tags($package_get).'?action=love"; ?>;
$(function(){
$("#btn_my_love").click(function(){
$.ajax({
url:my_url,
type:'GET',
success:function(data){
//comment the following result after testing
alert("Page visited");
},
error: function (request, status, error) {
alert(request.responseText);
}
});
//prevent button default action that is redirecting
return false;
});
});
</script>
Yes, it is possible. I am assuming you know what ajax is and how to use it, if not I am not going to give you the code because some simple reading on ajax as suggested by #Black0ut will show you how. But the basic steps are as follows:
Send ajax request to a PHP script that will update +1 vote to the database
In the PHP script, add +1 to the database and return some data to the ajax, maybe the new number of votes
Parse the return data in your JavaScript and update the button accordingly

PHP Session data lost on first reload with jquery load()

I'm loading content into a div with jquery's load() function and refresh that div every 15 seconds (it checks for a status).
For some reason after the first reload / refresh of the div, the session data is lost.
The exact code I'm using is very long, so a basic version of what I'm doing is this:
load.php
<?php
session_start();
$_SESSION['testvalue'] = "TESTVALUE";
?>
<div id="loaddiv"></div>
<script src="js/jquery.js"></script>
<script>
(function($)
{
$(document).ready(function()
{
$.ajaxSetup(
{
cache: false,
});
var $container = $("#loaddiv");
$container.load("load_test.php");
var refreshId = setInterval(function()
{
$container.load('load_test.php');
}, 10000);
});
})(jQuery);
</script>
load_test.php
<?php
session_start();
echo $_SESSION['testvalue'];
?>
Works fine when page loads initally and displays TESTVALUE, after the div refreshs there is no more output however.
Anyone experienced this before and knows what's going on ?
//EDIT
I'm one step further to solving this:
On the main page I'm selecting some things from my mysql db and putting this into the session, in the subpage (the one that jquery load() loads ) I am now just outputting the session values.
There's absolutely nothing on the subpage but this:
<?php
session_start();
echo $_SESSION['test_one'];
echo $_SESSION['test_two'];
?>
<?php echo session_id(); ?>
When jquery load() is triggered the second time, the values in
$_SESSION['test_one']; and $_SESSION['test_two']; change ... (It is running the mysql query again and putting something else into the session)
The values for the session get set on the mainpage, so why would refreshing the subpage run the mysql query on the main page again ?!

AJAX pagination solution for PHP

Right now I use a pagination system that requires url like
http://mypage.com/index.php?page=1
http://mypage.com/index.php?page=2
http://mypage.com/index.php?page=3
http://mypage.com/index.php?page=4
etc...
So it uses $_GET method to find out what page the user is on.
I decided to switch most of my website to ajax and came over a problem. When I use Ajax to load new content on a page the url stays the same all the time e.g. http://mypage.com/index.php . Therefore pagination system I use is useless.
I was not able to find efficient AJAX pagination systems, (e.g some where lagy, most required user to scrol to the tiop each time he / she clicked on a next page, because they stayed at the bottom of the page when they clicked next page. etc...)
So I decided to ask you lot if anyone has an efficient pagination solution that works with ajax.
Example of what needs to be paginated:
$sql = mysql_query("SELECT * FROM myMembers WHERE username='$username' LIMIT 1") or die (mysql_error("There was an error in connection"));
//Gather profile information
while($row = mysql_fetch_assoc($sql)){
$username = $row["username"];
$id = $row["id"];
$data_display .= '<b>'.Name.'</b> has an id of <span style="color: f0f0f0;">'.$id.'</span>';
}
<!doctype>
<html>
<?php echo "$data_display"; ?> //and I need to paginate this entries
</html>
jQuery that loads new content from different pages into #content div
<script type="text/javascript">
function viewHome(){
$('#woodheader').load("inc/home_top.php", function () {
$(this).hide().fadeIn(700)
});
$('#content').html('<span class="loader">Loading.. <img class="loaderimg" src="images/ajax_loader.gif"/></span>').load("inc/home.php", function () {
$(this).hide().fadeIn(700)
});
}
function viewAbout(){
$('#woodheader').load("inc/about_top.php", function () {
$(this).hide().fadeIn(700)
});
$('#content').html('<span class="loader">Loading.. <img class="loaderimg" src="images/ajax_loader.gif"/></span>').load("inc/about.php", function () {
$(this).hide().fadeIn(700)
});
}
function viewProducts(){
$('#woodheader').load("inc/products_top.php", function () {
$(this).hide().fadeIn(700)
});
$('#content').html('<span class="loader">Loading.. <img class="loaderimg" src="images/ajax_loader.gif"/></span>').load("inc/products.php", function () {
$(this).hide().fadeIn(700)
});
}
</script>
Pagination is not as hard as you can think, you can use jQuery's load() function to load content into an element with the page's content.
So for example you have:
<div id="page-content"></div>
Page 1
Page 1
Page 3
<script>
$.ready(function(){
var currPage = <?=$pageNumber; ?>; // The page number loaded on page refresh
$('#link1,#link2,#link3').onclick(function(){
// Get the first number inside the id
var pageNum = parseInt($(this).attr('id'));
// Don't load the same page
if(currPage == pageNum) return;
// Show loading animation or whatever
// Load the page using ajax
$('#page-content').load('pages.php?page='+pageNum, function(){
// End loading animation
currPage = pageNum;
});
return false; // Important for not scrolling up
});
});
</script>
Regarding the url, you have three options to choose from when a user clicks a page link:
Just load the page with no changing of the url
Use the HTML5 history.pushState(see MDN resource) if supported and with option 3 as fallback for unsupported browsers
Use #page1, #page1 etc. as the href value of the links so that the user knows on what page they are on and parse the value of the url in php:
$uri = explode('#page', $_SERVER['REQUEST_URI']);
$pageNumber = intval($uri[1]);
I would create a index.php that doesn't load any $data_display initially.
Internally in javascript I would keep a variable named $page that would initially equals 1.
After load it would make a ajax call to names.php?page=$page and pass the results to a handler that presents it to the user.
Then on the links to "back" and "next" I would put a javascript function that first sets $page to the previous or next number, then calls names.php?page=$page and pass the results to the same handler.

How do I use externalInterface to allow Flash to call javascript to update a value on the screen?

I have a Flash movie that is embeded in a PHP page. The PHP page displays a value to the user (the number of images they have uploaded). When the user uploads a new image I want the value on the PHP page to reflect the change without refreshing the page.
This value is retrieved from database using MySQL. So heres what Ive done so far -
On the PHP page where I want to show the value I have a div
<div id="content_info"><script type="text/javascript" src="getInfo.php?group= <?php echo($groupid); ?> "></script></div>
This calls an external PHP file that queries the database and outputs the result like this
Header("content-type: application/x-javascript");
//do the query with PHP and get $number and then output
echo "document.write(\" (".$number.")\")";
When the page loads for the first time the correct number shows in the div and so all works fine. The next step is to call something to update the contents of this div when the value changes. So I will set up externalInterface in flash to call a javascript function to do this.
This is where Im stuck, I want to be able to do something like this -
function ReplaceContentInContainer(id) {
var container = document.getElementById(id);
container.innerHTML = getInfo.php?type=new&group= <?php echo($groupid) ?>;
}
and call this by
ReplaceContentInContainer(content_info)
I realise this isnt going to work but can anyone show me how to get this result?
many thanks
group= <?php echo($groupid); ?> will be executed only when PHP creates the page. You should store that value inside a variable in the javascript. See if this works.
<div id="scriptDiv">
<script type="text/javascript">
<!-- store the group id -->
var groupID = <?php echo($groupid); ?>;
function getGroupID()
{
return groupID;
}
function updateValue(value)
{
document.getElementById("content_info").innerHTML = value;
}
</script>
<div id="content_info">
<!-- for initial value -->
<script type="text/javascript"
src="getInfo.php?group= <?php echo($groupid); ?> ">
</script>
</div>
</div>
Now you can use flash's URLLoader:
var ldr:URLLoader = new URLLoader();
var gid:String = ExternalInterface.call("getGroupID");
var req:URLRequest = new URLRequest("getInfo.php");
req.data = {type:"new", group:gid};
ldr.addEventListener(Event.COMPLETE, onLoad);
ldr.addEventListener(IOErrorEvent.IO_ERROR, onError);
ldr.load(req);
private function onLoad(e:Event):void
{
var data:String = URLLoader(e.target).data;
ExternalInterface.call("updateValue", data);
}
private function onError(e:IOErrorEvent):void
{
trace("ioError");
}

Categories