I am attempting to create a cookie with information in javascript, which is then decoded by a php file, storing the data into a database. The problem with the cookie is that I can't call the php file from the javascript function using ajax, so I was wondering if there is an alternative method or if I'm doing it all wrong.
Ajax File
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script type="text/javascript"> function createCookie(value) { //Called on link click var expires; var date = new Date(); date.setTime(date.getTime() + 10000); expires = "; expires=" + date.toGMTString(); document.cookie = 'History' + "=" + escape(value) + expires + "; path=/"; $(document).ready(function() { $.ajax({ url: 'Query-Logger.php' }); }); } </script><?phprequire 'linkdisplay.php';echo '<a class="buy" target="_blank" href="' . $ebayla[ $ebayx ] . '" onclick="javascript:createCookie("' . $header . '");" style="text-decoration:none;">' . $header . '</a>';?>
I call PHP files with AJAX all the time. But there must be more to your PHP file than what you posted. For starters, you don't have 'session_start' at the top of the file. That is required so your code will access the correct session data.
Olaf Doschke
Dave is correct, aside of the missing session start the $_COOKIE['History'] is read and works for me, for example from an img tag:
I'm sorry but the $session_start code was omitted from my post, and is present on both files. In addition, I have pasted below the code for calling the function, which I believe may be the source of my problem.
if $header come from server side why do you need to send it back one more time to the server ?
the server build the page with its value, it should be able to get it one more time
you can also set cookie before sending anything to browser, just after $session_start() to overwrite a cookie with the same name
of course you can read cookie on page reload or change
Sorry again, I meant session_start();, I had a little brain fart there. As for the comment by leakim971, the data comes from a separate php file that I have updated to my original answer.