Programmyx
Programmyx

Reputation: 3

Undefined Index $_POST Error in Ajax, PHP

Getting Undefined Index postBody Error in Ajax I don't know how to fix this.
I have already checked many posts but that didn't help.


HTML CODE in index.php:

<form method="post">
  <textarea name="postBody" type="text" id="postBody" placeholder="What's on your mind?"></textarea>
  <input type="submit" name="postButton" id="postButton" value="POST" class="cg nq w-50">
</form>

Here is Ajax Code in my index.php at the end after jquery cdn.

$("#postButton").click(function(e) {
    e.preventDefault();
    var body = $("#postBody").val();
    var dataString = 'postBody='+body;
    $.ajax({
        type:'POST',
        data:dataString,
        url:'submitPost.php',
        success:function(data) {
            alert(data);
        }
    });
});


And this is submitPost.php Code.

include("config.php");
global $con;
$body = $_POST['postBody'];
$date_added = date("F j, Y, g:i a");

$query = mysqli_query($con,"INSERT INTO posts VALUES('','$body','$date_added')");

if($query == 1){
   echo "Post Submitted";
else{
   echo "Error";
} 

This code actually Return Post Submitted in alert and Insert the $date_added and but not $body. Error: undefined Index postBody in postSubmit.php on 3.

Upvotes: 0

Views: 161

Answers (1)

Sinto
Sinto

Reputation: 3997

Some mistakes that you have made are:

  • mis-spelled form tag
  • wrong passing of data through ajax

$("#postButton").click(function(e) {
  e.preventDefault();
  var body = $("#postBody").val();
  $.ajax({
    type: 'POST',
    data: {'postBody': body},
    url: 'submitPost.php',
    success: function(data) {
      alert(data);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
  <textarea name="postBody" type="text" id="postBody" placeholder="What's on your mind?"></textarea>
  <input type="submit" name="postButton" id="postButton" value="POST" class="cg nq w-50">
</form>

Upvotes: 1

Related Questions