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.
4
Answers
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
And then you will probably have to adapt your php code:
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
instead of
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:
The PHP file:
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 thatres
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(correctionecho
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 ( likesuccess: 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