简体   繁体   中英

Trying to pass variable from JavaScript to PHP using Ajax but got error " Undefined array key"

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?

Edit: People have told me to use isset, I have added that it removed the error however it still does not echo the PHP variable, meaning it is still not been passed to PHP, I am still trying to find how to fix this.

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);

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.

If you get this error in your ajax.php file which you Post the data to it, I say it's normal because when you open that file (ajax.php) it's like that there is no $_POST['pass'] because you just opened that file without running JS to send data. If you want to receive data that you send you can do this:

Your JS code I call this file index:

var variable = "hello";
$.ajax
({
    url: "ajax.php",
    type: "POST",
    data:{pass : variable},
    success: function(res) { 
          alert(res); 
    } 
});

The PHP file:

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

Then if You open up that index file, after running the JS code it'll send that post data to your PHP file and your PHP file will echo that, then the value will store in that res variable which when every thing went fine, you can see the alert of that res in the page (index file).

Notice that as I said you can't open up the PHP file lonely because it doesn't receive a post data on its own, it is normal for undefined to return.

Re: @puckloe your code is working, php echo wouldn't be printed with ajax( correction echo is working but wouldn't show on page if you don't print it with JS too ), you have to catch the response in ajax success function ( like success: function(response) ) and print or alert the response --> success: function(response) { alert("hi look this is echo from php"+response) }

you ajax code should look like

$.ajax
    ({
        url: "ajax.php",
        type: "POST",
        data:{pass : variable},
        success: function(response) { 
              alert("hi look this is echo from php" + response); 
        } 
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM