Reputation: 159
I'm trying to sketch out the easiest way to pass integers into an array when a button/href is clicked. I need to access the array globally on the page.
Do I have to do this with Ajax or is it possible to do it all in one file through a session array?
Thanks for pointing me in the right direction.
-Jonathan
Upvotes: 0
Views: 205
Reputation: 6369
I suggest using client side tehcnology such as localStorage or cookies instead.
The main reason is that, if you are trying to track clicks on buttons and links with PHP, you would need to send a new HTTP request every time so you can track it on your PHP with $_POST
or $_GET
. While this can be obvious for a link, this will really hurt the user experience when it comes to buttons (that are not a form submit buttons).
Assuming you want to avoid refershing the page on every button click, you will need to implement Ajax. Which leads us to the folllowing question - if you are already using javascript and Ajax, why not simply track everything in Javascript from the first place and only communicate with the server when needed?
Client Side Tracking with localStorage
:
By using localStorage
or Cookies
, you can simply bind events to clicks and save it to an array.
In Javascript/jQuery you can use the following examaple:
$(document).ready(function() {
var urls = JSON.parse(localStorage["visited"]) || [];//get the visited urls from local storage or initialize the array
if (urls.indexOf(document.URL) == -1) {//if current url does not exist in the array
urls.push(document.URL);//add it to the array
localStorage["visited"] = JSON.stringify(urls);//save a stringifyed version of the array to local storage
}
});
By having the array data in Javascript you can more easily manipulate the DOM and CSS without dependency on the server. (i.e changing a link's text, href or css if it was already clicked).
Hope this helps!
Upvotes: 1
Reputation: 11
Either way you're going to need a PHP file to handle the POST event (let's call that buttonHandler.php).
buttonHandler.php will have $_POST['buttonID/name'] which contains the button value. If that post variable has a value, then the button was clicked.
Now whether you do a normal POST which requires a page reload, or use AJAX is a personal choice. If you use ajax, I seriously recomend you look into jquery. It makes ajax amazingly simple.
EDIT: If you're only editing this from one page, you could put the handler in the same file. It doesn't necessarily have to be a seperate file.
Upvotes: 0