user1104615
user1104615

Reputation: 21

ajax and php undefined index

Here is my ajax code:

function send()
{
    var xmlhttp;
     if (window.XMLHttpRequest)
       {// code for IE7+, Firefox, Chrome, Opera, Safari
       xmlhttp=new XMLHttpRequest();
       }
     else
       {// code for IE6, IE5
       xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
       }

    xmlhttp.onreadystatechange=function()
       {
       if (xmlhttp.readyState==4 && xmlhttp.status==200)
         {
            alert(xmlhttp.responseText);
         }
       }

    xmlhttp.open("POST","test.php",true);
    xmlhttp.send('subject=' + document.getElementById("subject").value);
}

here is my php code:

<?php
$subject = $_POST['subject'];
echo $subject;
?>

It says error on line 2 in the php code, undefined index. I don't know what else to do..any help would be apriciated, thanks.

Upvotes: 0

Views: 2438

Answers (2)

Dan Prince
Dan Prince

Reputation: 29989

This means that there is no 'subject' value in the $_POST array. This means that when the request to the page was made, there was not a post variable called subject with a value. One simple way to check for this is to use:

if(isset($_POST['subject'])){
    $subject = $_POST['subject'];
}else{
    $subject = "default";
}

This was makes sure that subject has a value and will not cause any page errors. Make sure you are definitely sending a POST variable called subject (You can do this in Chrome Developer tools or Firebug in the Network requests panel).

Upvotes: 1

mustafa
mustafa

Reputation: 745

Check your form input named subject. You might have misspelled it.

Upvotes: 0

Related Questions