On my homepage I'm using the maximage fullscreen image plugin. When someone clicks on a
specific link (product page), I must find out what the current image in the slideshow is
and set it as the background-image in the product index page.
I'm making an ajax call the moment someone clicks the '/producten' link on the homepage and store it as a session variable.
The problem is, it's not making an ajax call, I can't see the POST request in my apache logfile, only the GET request for the '/producten' page. Is it going to fast? Can't I do a POST request just before I make the GET request? I can't pinpoint it. Here's my code:
homepage index:
jQuery(document).ready(function($)
{
$("a[href='/producten']").click(function() {
var best;
var maxz;
$('.mc-image').each(function() {
var z = parseInt($(this).css('z-index'), 10);
if (!best || maxz<z) {
best = this;
maxz = z;
}
});
var bg_image = $(best).css('background-image');
bg_image = bg_image.replace('url(','').replace(')','');
$.post('/producten', {bg_image:bg_image});
});
});
bg_image is set correctly, I tested it with a console.log(), and I get output.
/producten index:
<?php
session_start();
$_SESSION['bg_image'] = $_POST['bg_image'];
?>
In javascript:
/* $.post('/producten', {bg_image:bg_image}); */
this.href = this.href + '?bg_image=' + escape(bg_image)
In php:
if(isset($_GET['bg_image'])) {
$_SESSION['bg_image'] = $_GET['bg_image'];
header('Location: /producten');
exit;
}
Related
I have this issue i'm trying to solve.
I have this page lista.php
In which i load another page (which refreshes every x seconds) named pagination.php
I use this script:
function LoadContent()
{
$('#lista').load('pagination.php');
}
$(document).ready(function(){
LoadContent(); //load contentent when page loads
setInterval('LoadContent()',30000); //schedule refresh
});
Well, there is this URL:
lista.php?id=3
I need the pagination.php to grab the id, but it won't work..
the pagination.php is inside lista.php... how can i solve it?
I tried the GET method..
Any suggestion please?
Thanks.
To obtain id from your url like lista.php?id=3 you could use
var url = window.location.href;
var queryStr = url.substring(url.indexOf("?")+1);
var id = queryStr.split('=')[1];
So the whole code maybe like:
function LoadContent()
{
var url = window.location.href;
var queryStr = url.substring(url.indexOf("?")+1);
var id = queryStr.split('=')[1];
$('#lista').load('pagination.php?id=' + id);
}
$(document).ready(function(){
LoadContent(); //load contentent when page loads
setInterval('LoadContent()',30000); //schedule refresh
});
Add the parameter to the url, e.g.:
function LoadContent()
{
var id = ... <== assign id here
$('#lista').load('pagination.php?id=' + id);
}
$(document).ready(function(){
LoadContent(); //load contentent when page loads
setInterval('LoadContent()',30000); //schedule refresh
});
If you're using AJAX to load dynamically then that's a different URL, so append the current query string to the request with something like location.search.substring(url.indexOf("?")).
$('#lista').load('pagination.php' + location.search.substring(url.indexOf("?")));
i think you can use this:
$('#lista').load('pagination.php?id=<?php echo $_GET['id'] ?>');
Pages loaded via AJAX methods. index.php is the base page, profile.php is the page loaded
jQuery: ("post" nothing to do with HTML request)
$('<a/>', {href: '?userID='+post['userID']+'#profile'}).text(post['firstName']+' '+post['lastName'])
HTML:
Firstname Lastname
Raw URL (after click)
http://########/#####/index.php?userID=1#home
$_GET print_r on profile.php:
Array ()
By request; the ajax load javascript (index.php):
//AJAX page loading
$(document).ready(function(){
//Default page
if(!window.location.hash)
window.location.hash = '#home';
//Check page reference
checkURL();
//Update nav
$('#main-nav li').on("click", function (){
$('#main-nav li').removeClass('active');
$(this).addClass('active');
//Assign each link a new onclick event, using their own hash as a parameter
checkURL(this.hash);
});
//check for a change in the URL every 250 ms to detect if the history buttons have been used
setInterval("checkURL()",250);
});
//Store the current URL hash
var lasturl="";
function checkURL(hash){
if(!hash)
//if no parameter is provided, use the hash value from the current address
hash=window.location.hash;
if(hash != lasturl) {
//If hash changed, update current hash and load new one
lasturl=hash;
loadPage(hash);
}
}
function loadPage(url) {
//Adjust page name
url=url.replace('#','');
url=url+'.php';
//AJAX load page contents in to main content div
$('#content').load(url);
}
Solution:
Create global storage on root page (index.php).
Set vars in storage instead of using $_GET.
Access vars from child pages.
Example:
index.php (Javascript)
if (typeof(window.storage) === 'undefined') {
window.storagePV = {};
}
$('#nav-profile').click(function() {
window.storage.userID = <?php echo "$_SESSION[userID]"; ?>;
});
accessing userID to view the user's profile page
var userID = window.storage.userID
I am submitting some data to my database then reloading the same page as the user was just on, I was wondering if there is a way to remember the scroll position the user was just on?
I realized that I had missed the important part of submitting, so, I decided to tweak the code to store the cookie on click event instead of the original way of storing it while scrolling.
Here's a jquery way of doing it:
jsfiddle ( Just add /show at the end of the url if you want to view it outside the frames )
Very importantly, you'll need the jquery cookie plugin.
jQuery:
// When document is ready...
$(document).ready(function() {
// If cookie is set, scroll to the position saved in the cookie.
if ( $.cookie("scroll") !== null ) {
$(document).scrollTop( $.cookie("scroll") );
}
// When a button is clicked...
$('#submit').on("click", function() {
// Set a cookie that holds the scroll position.
$.cookie("scroll", $(document).scrollTop() );
});
});
Here's still the code from the original answer:
jsfiddle
jQuery:
// When document is ready...
$(document).ready(function() {
// If cookie is set, scroll to the position saved in the cookie.
if ( $.cookie("scroll") !== null ) {
$(document).scrollTop( $.cookie("scroll") );
}
// When scrolling happens....
$(window).on("scroll", function() {
// Set a cookie that holds the scroll position.
$.cookie("scroll", $(document).scrollTop() );
});
});
#Cody's answer reminded me of something important.
I only made it to check and scroll to the position vertically.
(1) Solution 1:
First, get the scroll position by JavaScript when clicking the submit button.
Second, include this scroll position value in the data submitted to PHP page.
Third, PHP code should write back this value into generated HTML as a JS variable:
<script>
var Scroll_Pos = <?php echo $Scroll_Pos; ?>;
</script>
Fourth, use JS to scroll to position specified by the JS variable 'Scroll_Pos'
(2) Solution 2:
Save the position in cookie, then use JS to scroll to the saved position when page reloaded.
Store the position in an hidden field.
<form id="myform">
<!--Bunch of inputs-->
</form>
than with jQuery store the scrollTop and scrollLeft
$("form#myform").submit(function(){
$(this).append("<input type='hidden' name='scrollTop' value='"+$(document).scrollTop()+"'>");
$(this).append("<input type='hidden' name='scrollLeft' value='"+$(document).scrollLeft()+"'>");
});
Than on next reload do a redirect or print them with PHP
$(document).ready(function(){
<?php
if(isset($_REQUEST["scrollTop"]) && isset($_REQUEST["scrollLeft"]))
echo "window.scrollTo(".$_REQUEST["scrollLeft"].",".$_REQUEST["scrollTop"].")";
?>
});
Well, if you use _targets in your code you can save that.
Or, you can do an ajax request to get the window.height.
document.body.offsetHeight;
Then drop them back, give the variable to javascript and move the page for them.
To Remember Scroll all pages Use this code
$(document).ready(function (e) {
let UrlsObj = localStorage.getItem('rememberScroll');
let ParseUrlsObj = JSON.parse(UrlsObj);
let windowUrl = window.location.href;
if (ParseUrlsObj == null) {
return false;
}
ParseUrlsObj.forEach(function (el) {
if (el.url === windowUrl) {
let getPos = el.scroll;
$(window).scrollTop(getPos);
}
});
});
function RememberScrollPage(scrollPos) {
let UrlsObj = localStorage.getItem('rememberScroll');
let urlsArr = JSON.parse(UrlsObj);
if (urlsArr == null) {
urlsArr = [];
}
if (urlsArr.length == 0) {
urlsArr = [];
}
let urlWindow = window.location.href;
let urlScroll = scrollPos;
let urlObj = {url: urlWindow, scroll: scrollPos};
let matchedUrl = false;
let matchedIndex = 0;
if (urlsArr.length != 0) {
urlsArr.forEach(function (el, index) {
if (el.url === urlWindow) {
matchedUrl = true;
matchedIndex = index;
}
});
if (matchedUrl === true) {
urlsArr[matchedIndex].scroll = urlScroll;
} else {
urlsArr.push(urlObj);
}
} else {
urlsArr.push(urlObj);
}
localStorage.setItem('rememberScroll', JSON.stringify(urlsArr));
}
$(window).scroll(function (event) {
let topScroll = $(window).scrollTop();
console.log('Scrolling', topScroll);
RememberScrollPage(topScroll);
});
I had major problems with cookie javascript libraries, most cookie libraries could not load fast enough before i needed to scroll in the onload event. so I went for the modern html5 browser way of handling this. it stores the last scroll position in the client web browser itself, and then on reload of the page reads the setting from the browser back to the last scroll position.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
if (localStorage.getItem("my_app_name_here-quote-scroll") != null) {
$(window).scrollTop(localStorage.getItem("my_app_name_here-quote-scroll"));
}
$(window).on("scroll", function() {
localStorage.setItem("my_app_name_here-quote-scroll", $(window).scrollTop());
});
});
</script>
I tackle this via using window.pageYOffset . I saved value using event listener or you can directly call window.pageYOffset. In my case I required listener so it is something like this:
window.addEventListener('scroll', function() {
document.getElementById('showScroll').innerHTML = window.pageYOffset + 'px';
})
And I save latest scroll position in localstorage. So when next time user comes I just check if any scroll value available via localstorage if yes then scroll via window.scrollTo(0,myScrollPos)
sessionStorage.setItem("VScroll", $(document).scrollTop());
var scroll_y = sessionStorage.getItem("VScroll");
setTimeout(function() {
$(document).scrollTop(scroll_y);
}, 300);
In my website authors (users) can mark posts as favorite.
It works this way:
if ($favinfo == NULL || $favinfo == "") {
$favicon = "ADD"; .
}
else {
$favicon = "REMOVE";
}
Its suposed to look dynamic, it works, when user click ADD, it adds the post to his favorites and reload the page with the REMOVE link.
The problem is its not really dynamic it reloads all the page.
How can i only reload that link (wich is inside a div)?
I know i have to use ajax, jquery, etc, but i tried some examples found here in S.O. but no success.
$('a').on('click', function(e){
// the default for a link is to post a page..
// So you can stop the propagation
e.stopPropagation();
});
Including this stop you page from reloading your entire page
If you want it to be dynamic, you will need to use AJAX. jQuery has ajax support which makes this really easy. If you are not familiar with ajax or javascript you should read up on it first.
PHP
if ($favinfo == NULL || $favinfo == "") {
$favicon = "<a class=\"fav-btn\" data-id=\"".$articleinfo['id']."\" data-action=\"add\" href=\"".$siteurl."/author/favorites.php"\">ADD</a>"; .
}
else {
$favicon = "<a class=\"fav-btn\" data-id=\"".$articleinfo['id']."\" data-action=\"remove\" href=\"".$siteurl."/author/favorites.php"\">REMOVE</a>";
}
JavaScript
$('a.fav-btn').on('click', function(e){
var $this = $(this), // equates to the clicked $('a.fav-btn')
url = $this.attr('href'), // get the url to submit via ajax
id = $this.attr('data-id'), // id of post
action = $this.attr('data-action'); // action to take on server
$.ajax({
url: url+'?'+action+'='+id
}).done(function(){ // once favorites.php?[action]= is done...
// because this is in .done(), the button will update once the server has finished
// if you want the link to change instantly and not wait for server, move this outside of the done function
if(action === 'add'){
$this.attr('data-action', 'remove').html('REMOVE'); // update the button/link
}else{
$this.attr('data-action', 'add').html('ADD');
}
})
return false; // prevent link from working so the page doesn't reload
}
If you are okay with using JQuery, you have some tools to accomplish this.
Have a structure / method of identifying your links.
You can have a click() listener on your add button that will call a JQuery $.post(url, callback) function.
In that callback function, you can have it update the corresponding DIV (that you defined in #1) with a 'remove' link. i.e if you identify the DIV by ID, you can retrieve it via $('#id') and then update that object.
The same idea can apply with the 'remove' link that you add.
So, generally...
<button id="add">Add</button>
<div id="links"> ...</div>
<script>
$('#add').click(function() {
$.post('your url',
function(data) {
var links = $('#links');
// update your links with 'remove' button, etc
}
);
});
</script>
I have several divs that a user can Minimize or Expand using the jquery toggle mothod. However, when the page is refreshed the Divs go back to their default state. Is their a way to have browser remember the last state of the div?
For example, if I expand a div with an ID of "my_div", then click on something else on the page, then come back to the original page, I want "my_div" to remain expanded.
I was thinking it would be possible to use session variables for this, perhaps when the user clicks on the expand/minimize button a AJAX request can be sent and toggle a session variable...IDK..any ideas?
There's no need for an ajax request, just store the information in a cookie or in the localstorage.
Here's a library which should help you out: http://www.jstorage.info/
Some sample code (untested):
// stores the toggled position
$('#my_div').click(function() {
$('#my_div').toggle();
$.jStorage.set('my_div', $('#my_div:visible').length);
});
// on page load restores all elements to old position
$(function() {
var elems = $.jStorage.index();
for (var i = 0, l = elems.length; i < l; i++) {
$.jStorage.get(i) ? $('#' + i).show() : hide();
}
});
If you don't need to support old browsers, you can use html5 web storage.
You can do things like this (example taken from w3schools):
The following example counts the number of times a user has visited a
page, in the current session:
<script type="text/javascript">
if (sessionStorage.pagecount) {
sessionStorage.pagecount=Number(sessionStorage.pagecount) +1;
}
else {
sessionStorage.pagecount=1;
}
document.write("Visits "+sessionStorage.pagecount+" time(s) this session.");
</script>
Others have already given valid answers related to cookies and the local storage API, but based on your comment on the question, here's how you would attach a click event handler to a link:
$("#someLinkId").click(function() {
$.post("somewhere.php", function() {
//Done!
});
});
The event handler function will run whenever the element it is attached to is clicked. Inside the event handler, you can run whatever code you like. In this example, a POST request is fired to somewhere.php.
I had something like this and I used cookies based on which user logged in
if you want only the main div don't use the
$('#'+div_id).next().css('display','none');
use
$('#'+div_id).css('display','none');
*Here is the code *
//this is the div
<div id = "<?php echo $user; ?>1" onclick="setCookie(this.id)" ><div>My Content this will hide/show</div></div>
function setCookie(div_id)
{
var value = '';
var x = document.getElementById(div_id);
var x = $('#'+div_id).next().css('display');
if(x == 'none')
{
value = 'block';
}
else
{
value = 'none';
}
console.log(div_id+"="+value+"; expires=15/02/2012 00:00:00;path=/")
//alert(x);
document.cookie = div_id+"="+value+"; expires=15/02/2012 00:00:00;path=/";
}
function getCookie(div_id)
{
console.log( div_id );
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==div_id)
{
return unescape(y);
}
}
}
function set_status()
{
var div_id = '';
for(var i = 1; i <= 9 ; i++)
{
div_id = '<?php echo $user; ?>'+i;
if(getCookie(div_id) == 'none')
{
$('#'+div_id).next().css('display','none');
}
else if(getCookie(div_id) == 'block')
{
$('#'+div_id).next().slideDown();
}
}
}
$(document).ready(function(){
get_status();
});
Look about the JavaScript Cookie Method, you can save the current states of the divs, and restore it if the User comes back on the Site.
There is a nice jQuery Plugin for handling Cookies (http://plugins.jquery.com/project/Cookie)
Hope it helps
Ended up using this. Great Tutorial.
http://www.shopdev.co.uk/blog/cookies-with-jquery-designing-collapsible-layouts/