This might be a dumb question, but I'm new to transferring data from the client side to the server side. I'm using the code here to create a cookie. Then I was going to use $_COOKIE
in a separate PHP file to read the data from the cookie. Is it possible to run my PHP code without loading a new tab/window?

- 117
- 1
- 16
-
1Post the code "here", not a link. – Felippe Duarte Jul 09 '18 at 16:10
-
1You would need to use ajax which is using JavaScript to make the request to the php page in the background instead of loading another page directly. – Jonathan Jul 09 '18 at 16:13
-
Yes, it is possible. But it's probably not the best way to do it - a cookie is intended to be read repeatedly on every future page/session for its lifetime. If you want to simply transfer data between the front and backends, you'd probably be more interested in using AJAX: www.w3schools.com/xml/ajax_intro. – Ewan Jul 09 '18 at 17:01
-
I suggest a read on https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX ... w3schools is such trash ;) – IncredibleHat Jul 09 '18 at 17:03
2 Answers
You can have the server return a 204 No Content
response, or make the request with fetch
or XMLHttpRequest
, or by loading an image, or by loading a new page in an iframe, or by making any other HTTP request that doesn't trigger a whole new page load.
… but there seems little point in storing data in a cookie (which is used when you want to include data in every subsequent request) and then sending it to PHP without caring about what the response it. Possibly you would be better of forgetting about the cookie and just using fetch
or XMLHttpRequest
to make a POST request with the data in the request body instead of in a cookie.

- 914,110
- 126
- 1,211
- 1,335
You can send a POST/GET request to the target page using AJAX.
$.ajax({
url: "test.php",
....
Read more about Jquery's Ajax Here.
You don't really need to use jQuery, you can use the standard vanilla way.
As for server-side, you can fetch data sent via AJAX with $_POST['foo']
, $_GET["bar"]
...
Where 'foo' and 'bar' are the field names passed thought AJAX.

- 729
- 8
- 18
-
1This is either a comment of a link only answer. Neither are very well respected when placed in an answer – RiggsFolly Jul 09 '18 at 17:00