0

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?

Not A Bot
  • 2,474
  • 2
  • 16
  • 33

3 Answers3

0

You should use setcookie in the PHP action instead of document.cookie (it works, the problem is this javascript must be executed before, so maybe, you could have problems with that).

You can receive your data in your submit action in PHP and use this line to set the cookie:

setcookie('name_of_your_cookie', 'value_of_your_cookie', time() + (86400 * 30)); // 86400 = seconds in 1 day

I recommend you write the name of your cookies with the snake case naming convention (name_of_your_cookie) and without spaces.

0

Changes in HTML Code:

  • Avoid using onclick() onClick in HTML is Bad Practice
  • Instead of using action inside form you can send data to the server using AJAX. You can use Fetch API or XHR or AXIOS or any other. Since your action part is executing and not the JavaScript, thus you are not able to set cookies via JavaScript.
  • Button does not have a value attribute. Even does not need the type attribute.
<form id="details" 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">go</button>
    
</form>

Changes in JavaScript:

  • Use EventListener instead of onclick()
  • Cookie's name should not have space in between words. Example Mobile No as cookie name should be avoided as it will work in JavaScript but PHP will give you NULL. So change Mobile No to Mobile_No and so on.
document.getElementById('go').addEventListener('click', submit);
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;
}

Your PHP is fine, still, to make output looks good you can use <br /> in-between var_dump.

<?php
   var_dump($_COOKIE['name']);
   echo   "<br />";
   var_dump($_COOKIE['ID No']);
   echo   "<br />";
   var_dump($_COOKIE['Mobile No']);
   echo   "<br />";
   var_dump($_COOKIE['Email']);
   echo   "<br />";
   var_dump($_COOKIE['Image']);
?>

Your PHP output looks like something like this:

string(3) "ABC"
string(1) "1"
string(10) "1234567890"
string(11) "abc@def.com"
string(11) "preview.jpg"


Update With Fetch API

HTML Code:

<form id="details" method="post" class="form">
    Full name: <input type="text" name="name_1" /><br><br>

    E-mail: <strong name="email_1">abc@def.com</strong><br><br>

    Mobile: <input type="tel" name="ph_number_1" /><br><br>
    
    <button id="go">go</button>

</form>

JavaScript Code:

document.getElementById('go').addEventListener('click', function(event){
    event.preventDefault()
    var name=document.getElementsByName("name_1")[0].value;
    
    var phone=document.getElementsByName("ph_number_1")[0].value;
    
    var email=document.getElementsByName("email_1")[0].innerHTML;
    
    
    document.cookie="Email =" + email;

    fetch('database_registration.php', {
          method : 'post',
          mode:    'cors',
          headers: {
            'Content-Type': 'application/json', // sent request
            'Accept':       'application/json' // expected data sent back
          },
          body: JSON.stringify({
             full_name: name, 
             mobile: phone
          })
  })
  .then((res) => res.json())
  .then((data) => console.log(data))
  .catch((error) => console.log(error))
});

PHP Code:

<?php
     $contentType = isset($_SERVER["CONTENT_TYPE"]) ?  trim($_SERVER["CONTENT_TYPE"]) : '';

     if ($contentType === "application/json") {
 
         $content = trim(file_get_contents("php://input"));

         $decoded = json_decode($content, true);

         $fullName = $decoded["full_name"];
         $mobile = $decoded["mobile"];
         $email = $_COOKIE["Email"];

         $responseToUser = array(
            "result" => "success"
         );
         print_r(json_encode($responseToUser));
    }
?>
Not A Bot
  • 2,474
  • 2
  • 16
  • 33
  • Can I send the `document.cookie` with the help of `Fetch` api? –  Jan 15 '21 at 08:26
  • @Noob You don't need to send any cookies to the server, the browser automatically sends cookies to the server. So by using ``$_COOKIE['cookie_name']`` to can access the cookie value. – Not A Bot Jan 15 '21 at 08:30
  • I've edited the question, using the `fetch` api. But the question is, can I add the `document.cookie` into the `body` of `fetch()`? –  Jan 15 '21 at 09:07
  • @Noob By adding ``document.cookie`` to the body what do you mean by it? You mean to send cookies or to set cookies? – Not A Bot Jan 15 '21 at 09:10
  • I mean what should I add in the `body` ? –  Jan 15 '21 at 09:17
  • @Noob In this current scenario, you don't need to send anything to the server. Fetch will help you when you are dealing with user data to be stored in DB or something of that type. Here is your scenario, you don't need. – Not A Bot Jan 15 '21 at 09:19
  • @Noob I will update my answer to solve your query. – Not A Bot Jan 15 '21 at 09:20
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/227375/discussion-between-noob-and-not-a-bot). –  Jan 15 '21 at 09:39
  • Doesn't work. Now it shows `POST http://127.0.0.1:5500/database_registration.php 405 (Method Not Allowed)` error –  Jan 15 '21 at 10:36
0

The solution might be much simpler - I had the problem as well: You have to set the path in the cookie. If you redirect from page x to y you will not find the cookie set on x unless you have set the path.

Example:

/shopystem/cart will not work on /shopsystem/checkout

/shopystem/ will work on /shopsystem/checkout

/shopystem/checkout will work on /shopystem/checkout

Refer to this: How to extract the hostname portion of a URL in JavaScript