Home > Blockchain >  Trying to pass variable from JavaScript to PHP using Ajax but got error " Undefined array key&q
Trying to pass variable from JavaScript to PHP using Ajax but got error " Undefined array key&q

Time:03-21

I have had this error for multiple days now, I have tried searching this error up but whenever I search this error up it gives a different reason for the error and when I try to add what other sites say it doesn't work which is why I am asking here as I don't see what else I can do.

I am trying to pass a variable from JavaScript to PHP but it is not working and I have no idea why.

Here is my JavaScript code:

<head>
<script type="text/javascript" src="jquery.js"> </script>
</head>

<script>
var variable = "hello";
console.log(variable);
$.ajax
    ({
        url: "ajax.php",
        type: "POST",
        data:{pass : variable},
        success: function() { 
              alert("Success"); 
        } 
    });

</script>

Here is my PHP code:

$variable = $_POST['pass'];
echo($variable);

Everything seems to work perfectly. It writes the variable to the console, it comes up with the alert saying success. However I get an error message saying: 'Undefined array key "pass"'

What is causing this? Thank you?

CodePudding user response:

Your front end code looks OK, but I don't know your target PHP environement, but maybe your environnement doesn't accept formData.

By default, jQuery send ajax POST data as formData.

Try to send data as JSON

$.ajax({
    url: "ajax.php",
    type: "POST",
    data: JSON.stringify({pass : variable}),
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function(data){alert(data);},
});

And then you will probably have to adapt your php code:

$json = file_get_contents('php://input');
// Converts it into a PHP array
$data = json_decode($json, true);
$variable = $data['pass'];
echo($variable);

CodePudding user response:

Can you please use the developer tools in chrome browser that will help you to find if data is properly sent to php file. Also you can try $_REQUEST instead of post just to check what data is coming in REQUEST as it works for GET & POST both. If it still does not help you.

Also can you please use

data: {'pass':variable}

instead of

data: {pass:variable}

let me know if it works for you.

  • Related