Reputation: 3
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.
<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);
}
});
});
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
Reputation: 3997
Some mistakes that you have made are:
form
tagdata
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