Home > Software design >  How do I fix Undefined array key "token" in C:\xampp\htdocs\TPO\registered.php on line
How do I fix Undefined array key "token" in C:\xampp\htdocs\TPO\registered.php on line

Time:10-31

I would like to send data from javascript to php but this "Undefined array key "token" in C:\xampp\htdocs\TPO\registered.php on line 2" is trigger in my php file.

JavaScript function

function doSomething(Acronym) { 
 $.post('registered.php', {token: "Hello"});
 console.log($(Acronym).data('id'))
} 

registered.php

<?php
$variable = $_POST['token'];
echo($variable);
?>

CodePudding user response:

You can use jQuery Ajax for posting data to the PHP files by javascript.

This can be your js file:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" ></script>
<script>
    var vars = {
        'token': 'Hello',
    };
    var userStr = JSON.stringify(vars);
    $.ajax({
        url: 'registered.php',
        type: 'post',
        data: { vars: userStr },
        success: function (response) {
            console.log(response);
        }
    });
</script>

And this is your PHP file:

<?PHP
    $vars = $_POST['vars'];
    $variable = json_decode($vars, true);
    echo($variable);
?>
  • Related