Trying to practice ajax and PHP a little, I can’t figure out why whenever I send something, it returns empty or undefined index.
PHP:
<?php
if (!empty($_POST['message'])) {
echo 'works';
} else {
echo 'empty';
}
?>
returns empty.
JS:
$('form').submit(function(){
var meth = $(this).attr('action');
var msg = $('.msg');
$.post(meth, function(data) {
$('.messages').append(data);
}) ;
return false;
});
HTML:
<form class="send" action="process.php" method="post">
<textarea type="text" name="message" class="msg" value="blah"></textarea>
<input type="submit" name="submit" class="submit">
</form>
If I just do ‘echo 'test'; in the process.php file, it works; undefined index if otherwise.
What am I doing wrong?
I see you’ve edited the syntax errors, so you can ignore this section:
Well of the top of my head I see two syntax errors, one in php:
and one in JS:
Also let me be the first to point out that you should indent your code properly. It’s hard to see the depth of your scope otherwise, and just makes your code plain unreadable.
emptyis the wrong function to be using to check if an index on an array is set. That’s what’s generating your “undefined index” warnings. Useissetorarray_key_existsinstead:The
emptyfunction just checks if the variable contains a value that evaluates to empty, such as an empty string, an empty array, a NULL etc. It doesn’t check if a variable is set.Additionally, you don’t set the value of a textarea by populating the value attribute. That won’t work. You set the value by placing it between the open and close tags like this:
Then you fetch the text (in jQuery) by requesting the value