My html code:
<form id="details" action="database_registration.php" class="form">
Full name: <strong name="name_1">ABC</strong><br><br>
ID No:<strong name="org_number_1">1</strong><br><br>
Mobile No:<strong name="ph_number_1">1234567890</strong><br><br>
E-mail: <strong name="email_1">abc@def.com</strong><br><br>
ID Card: <img src="preview.jpg" alt="preview" name="image" style="width: 100px; height: 100px;"><br><br>
<button id="go" onclick="submit()" type="button" value="submit">go</button>
</form>
My javascript:
function submit(){
var nme=document.getElementsByName("name_1")[0].innerHTML;
var id=document.getElementsByName("org_number_1")[0].innerHTML;
var phone=document.getElementsByName("ph_number_1")[0].innerHTML;
var email=document.getElementsByName("email_1")[0].innerHTML;
var img=document.getElementsByName("image")[0].src;
document.cookie="name =" + nme;
document.cookie="ID No =" + id;
document.cookie="Mobile No =" + phone;
document.cookie="Email =" + email;
document.cookie="Image =" + img;
}
My php code:
<?php
var_dump($_COOKIE['name']);
var_dump($_COOKIE['ID No']);
var_dump($_COOKIE['Mobile No']);
var_dump($_COOKIE['Email']);
var_dump($_COOKIE['Image']);
?>
I keep getting the error:
Undefined array key
for each of the $_COOKIE
values. Why? I have searched for this error on the internet, and in most cases, it happens mostly because of the fault of the programmer in giving incorrect names. But in my case, all the keys
are correct. Please help me in fixing this error.
EDIT: Taking @Not A Bot's suggestion, I've modified my javascript by using the fetch()
api:
document.getElementById('go').addEventListener('click', submit);
function submit(){
var nme=document.getElementsByName("name_1")[0].value;
var id=document.getElementsByName("org_number_1")[0].value;
var phone=document.getElementsByName("ph_number_1")[0].value;
var email=document.getElementsByName("email_1")[0].value;
var img=document.getElementsByName("image")[0].value;
document.cookie="name =" + nme;
document.cookie="ID_No =" + id;
document.cookie="Mobile_No =" + phone;
document.cookie="Email =" + email;
document.cookie="Image =" + img;
const dForm = document.getElementById('details');
dForm.addEventListener('submit', function(e) {
e.preventDefault();
fetch("database_registration.php",{
method: 'post',
mode: 'cors',
body: // what should I add here?
}).then(function (response){
return response.text();
}).then(function (text){
console.log(text);
}).catch(function (error){
console.error(error);
})
});
}
Can I add the document.cookie
in the body
of the fetch API
?