3

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?

6
  • In your first code sample, is the [ after the else supposed to be a {? May 6, 2012 at 0:52
  • you need to either pass a named field yourself or use jquery'ies built-in form serialize function.
    – hakre
    May 6, 2012 at 0:53
  • what's that ? } else [ echo 'empty'; }
    – Sliq
    May 6, 2012 at 0:54
  • @hakre i'm reading about .serialize() and it makes sense, can you post an example maybe?
    – devs
    May 6, 2012 at 1:05
  • @devs: You'll fimd a thousand of those examples on this site already.
    – hakre
    May 6, 2012 at 10:06

4 Answers 4

4

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:

<?php


  if (!empty($_POST['message'])) {
    echo 'works';
  } else [ // <- This should be a {
     echo 'empty';
  }

?>

and one in JS:

$('form').submit(function(){

      var meth = $(this).attr('action');

      var msg = $('.msg');
      $.post(meth, function(data) {

        $('.messages').append(data);

      }) // <- Should be a ; here

      return false; 
    });

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.

empty is 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. Use isset or array_key_exists instead:

if (!isset($_POST['message'])) {
// or
if (!array_key_exists('message', $_POST)) {

The empty function 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:

<textarea class="msg">My message</textarea>

Then you fetch the text (in jQuery) by requesting the value

var my_message = $('textarea.msg').val()
3
  • the echo works. But when I assign $message = $_POST['message']; to send back the message, it doesn't work. returns undefined index. also the code indents properly in my code editor, its when I copy/paste is when it gets hectic :/
    – devs
    May 6, 2012 at 1:02
  • If the PHP's returned text is "undefined index" then that just means that the post request didn't send the message. The code in your question certainly confirms that, if that's the code you're using
    – Hubro
    May 6, 2012 at 1:05
  • Val worked with your HTML? It shouldn't have. I guess you've changed it :-)
    – Hubro
    May 6, 2012 at 1:19
3

The best way to test this, is to echo back the sent data:

<?php
  if (isset($_POST['message'])) {
    echo $_POST['message'];
  }
?>

If you get the action property with prop() it will usually get you the absolute link, which is better IMO.

$('form').on('submit', function(e){
    e.preventDefault();
    var meth = $(this).prop('action'),
        Mymsg = $('.msg').text(); //assuming the element contains text
    $.post(meth, {message: Mymsg}, function(data) {
        $('.messages').append(data);
    });
});

To send the entire form use serialize, was going to add that, but see Jonathan's answer instead.

2
  • 'prop() it will usually get you the absolute link' hm, can you explain? jquery api is down for me.
    – devs
    May 6, 2012 at 1:12
  • Sure, try this fiddle to see the difference!
    – adeneo
    May 6, 2012 at 1:20
2

Since you aren't using default behavior, you have to pass along the names and values of form fields yourself for PHP to receive any of them:

// ...
$.post(meth, $(this).serialize(), function(data) {
// ...

You may also consider using array_key_exists to avoid undefined errors:

if (array_key_exists('message', $_POST)) {
    # ...
}
0

Try putting the value of the text area between the <textarea></textarea> tags, like so:

<textarea type="text" name="message" class="msg">blah</textarea>

Textarea functions differently than a typical <input /> field.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.