简体   繁体   中英

How to use cookie set by JS in PHP

I am setting cookie using JS script on my page, but I need to use this value while generating HTML on server side PHP.
Let me expalain.
User requests page - > Of course PHP starts generating HTML -> User get response from server -> JS sets cookie.
Am I correct ? I understand this in this way.
But I need to use cookie set by JS while PHP generating response.
Of course it will work if reload the page,because new request is sent with cookies. But I need to use this cookies at a time I set it in JS.
Of course I can set in JS to reload page, but I don't think that is good solution.
What are possible solutions. I don't need to adhere to cookies. Maybe there are other possible ways to get data from JS to PHP.

If I understand your question right, there are at least 2 different ways:

  1. load an initial page which purpose is to redirect (via JavaScript or Refresh header) to the main page;
  2. load the entire main page in the first request, containing a placeholder block. Then set the cookie. Then fill the placeholder using AJAX technique (send another request using JS and replace HTML content of placeholer with a newly generated one).

For the 2nd approach you don't even need cookie, as JS can pass the value with a query string ( GET request parameter).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM