I have created a simple blog website using php mvc pattern and i am trying to add a post to the database using ajax but its giving me an error respond that i cant resolve
I have Defined the URLROOT as define('URLROOT', 'http://localhost/shareposts');
view/add.php
<h2>Add Post</h2>
<p>Create a post with this form</p>
<form action="<?php echo URLROOT; ?>/posts/add" method="post">
<div class="form-group">
<label for="title">Title: <sup>*</sup></label>
<input type="text" name="name" class="form-control form-control-lg">
</div>
<div class="form-group">
<label for="body">Body: <sup>*</sup></label>
<textarea name="body" class="form-control form-control-lg "> </textarea>
</div>
<input type="submit" class="btn btn-success" value="Submit">
</form>
</div>
<script>
var url = "<?php echo URLROOT; ?>"
$.ajax({
url: url + '/posts/add',
type: 'POST',
dataType: 'json',
data: form,
beforeSend: function() {
//do something here like load a loading spinner etc.
},
})
</script>
I have created an add method in the post controller
controller/post.php
<?php
class Posts extends Controller
{
public function add()
{
$response = array();
$message = '';
if(empty($_POST['name'])) {
$message .= "Name required <br />";
}
if(empty($_POST['body'])) {
$message .= "Description required <br />";
}
if($message) {
$response['success'] = false;
$response['message'] = $message;
} else {
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$body = filter_var($_POST['body'], FILTER_SANITIZE_STRING);
$data = [
'name' => $name,
'body' => $body,
'user_id' =>$_SESSION['user_id'],
];
if($this->postModel->addPost($data)) {
$response['success'] = true;
$response['message'] = "Success";
} else {
$response['success'] = false;
$response['message'] = "Something went wrong. Try again later.";
}
}
echo json_encode($response);
}
}
so once i load the add page i get a json error message which says name is required
Output i get
{
"success":false,
"message":"Name required Description required"
}