Cannot get cookie made in PHP in JavaScript file

I am trying to get the username a user enters in an input box in a php file as a cookie, then in a JS file read that cookie and get the username.
PHP
<?php
...
print('<form method="POST" name="loginForm" action="myDomain.com">' . "\n");
print(' <div class="loginContainer">' . "\n");
print(' <label for="userNameBox"><b>Account Login: </b></label>'. "\n");
print(' <input type="text" class="userName"id="userNameBox" placeholder="Enter Username" required="required">'. "\n");
print(' <input type="button" class="loginButton" id="loginButton" value="Login"/>' . "\n");
print(' </div>'. "\n");
print('</form>' . "\n")
print(' <div id="toolbar">' . "\n");
...
setcookie ( "LOGIN_USERNAME_COOKIE",
$_POST['userNameBox'] ,
$expires = 0,
$path = "/" ,
$domain = 'myDomain.com' ,
$secure = false,
$httponly = false
);
...
?>
JavaScript (just trying to print out the cookie)
confirm("Username entered: "+document.cookie.split('LOGIN_USERNAME_COOKIE=')[1]);
In the confirm Java alert I get this:
Username entered: __utma=261946002.205893547.1618416838.1618416838.1618416838.1; __utmc=261946002; __utmz=261946002.1618416838.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmt=1; __utmb=261946002.1.10.1618416838; _fbp=fb.1.1618416838418.1117675244
how can I fix this to get the cookie to contain the text the user enters and display it?
Answer
Solution:
Try this:
let username = document.cookie
.split('; ')
.find(row => row.startsWith('LOGIN_USERNAME_COOKIE='))
.split('=')[1];
confirm("Username entered: "+username);
Source: MDN
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: php undefined array key
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.