I am trying to pass a text string to a PHP Variable using AJAX, but I keep getting this error when POST fires:
Warning: Undefined array key "mydata"
the alert fires and displays the value correctly, but then the PHP page displays the mentioned error. What’s wrong here?
AJAX:
$("#display_tasks").click(function() {
var name = $(this).text();
var namecut = name.substr(0,name.indexOf(' |'));
$.ajax({
type: 'POST',
url: 'opentask.php',
data: {mydata : namecut},
success:function(data) {
alert(data);
}
});
});
PHP:
$taskname = $_POST['mydata'];
echo $taskname;
3
Answers
You are using
$_POST['mydata']
always, not just when receiving AJAX request. And when you are just showing the page, the superglobal array $_POST haven’t got an element indexed by ‘mydata’. That’s why you get the error.A way to avoid this is to separate AJAX receiving request to another file. This is like is done by several PHP applications.
A simpler way you can use to test is to check $_POST, for example you can do this:
That way you only try to use
$_POST['mydata
]` when you are receiving a POST. Also, if element ‘mydata’ is not present, you will still get an undefined array key error.Replace
var name = $(this).text();
with
var name= $(this).attr('value');
or
document.getElementById('name').value
name is the text input name
I think this will work and test if it gets by console.log(name) first
Please remove
href="opentask.php"
from the following line (you just need the ajax to call opentask.php) :Secondly , please use
isset
to check the existence of $_POST[‘mydata’] before assigning it to $tasknameSo please use
and
opentask.php
Please visit the following sandbox to see the effect:
http://www.createchhk.com/SOanswers/subj/test1.php
[Additional point]
If you just want to test POST request to be displayed in the target page, please use a form submission. (because ajax will only return the result back to the calling page in the success block.)