0

Hi I'm just wondering if it's possible to store the custom data attribute of an element with PHP into a variable and use that variable after refreshing the page?

I am trying to store this <a> tag's data attribute within a variable when it is pressed.

Here is an example of the element:

<a href="/book-testdrive" class="addtocart" data-value="NH06LKO" title="Book Test Drive">
  <span>&nbsp;Book Test Drive</span>
</a>

So I'm wondering if I can post the value of the data-value attribute when the <a> tag is clicked to a variable and store it on the server so it can be used after a page reload.

Is this possible with PHP?

Thanks, Nick

Uncle Kracker
  • 45
  • 1
  • 2
  • 8
  • Have a look at [How to pass JavaScript variables to PHP?](https://stackoverflow.com/questions/1917576/how-to-pass-javascript-variables-to-php) – Lumen Aug 15 '15 at 22:07

1 Answers1

1

PHP can't control what happens to your page after it renders it, therefore you have no way of accessing any values from PHP alone.

To continue beyond your question:

What you could do is use javascript (preferably jquery) and send the data via XHR request and set up php code which will receive it. Or you could store the data into a cookie, localStorage, sessionStorage or url, but this depends on your target browser support. All these methods will work in IE8+ for sure.

I can't advise you on which method is best, since I do not know what is your intent. Perhaps the easiest (probably not the best) option would be to set up a script to read the data via $_GET/$_POST and store the value in $_SESSION. Then on the front-end send the data with javascript XHR request or jQuery's $.ajax (wrapper for much easier XHR requests) to your php script.

Since I do not know what you're trying to do, I will not attempt to write any code for this. I suggest you to read or watch some php and javascript tutorials and documentation to learn about what I've just mentioned, if you don't know about it already.

Marko Gresak
  • 7,950
  • 5
  • 40
  • 46