0

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"
}
M. Eriksson
  • 13,450
  • 4
  • 29
  • 40
Abdallah
  • 198
  • 16

2 Answers2

0

As your output suggests, the $_POST elements are empty. To fix this you must assign variables to the individual elements of your form.

I also agree with Magnus Eriksson about triggering the js code only when you submit the form.

<script>
  var url = "<?php echo URLROOT; ?>"
  var name = $("input[name=name]").val();
  var body = $("input[name=body]").val();

  $.ajax({
    url: url + '/posts/add',
    type: 'POST',
    dataType: 'json',
    data: {'name' : name, 'body' : body},
    beforeSend: function() {
        //do something here like load a loading spinner etc. 
    },
   })
 </script>

Update

Here is one way to submit your form using JQuery's .click()

HTML:

<div class="your-form">
  <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>

<button id="submit-btn" class="btn btn-success">
</div>

JS:

$("#submit-btn").click(function() {
  var url = "<?php echo URLROOT; ?>"
  var name = $("input[name=name]").val();
  var body = $("input[name=body]").val();

  $.ajax({
   url: url + '/posts/add',
   type: 'POST',
   dataType: 'json',
   data: {'name' : name, 'body' : body},
   beforeSend: function() {
    //do something here like load a loading spinner etc. 
   },
  })
  .done(function() { 
    location.reload(); //add this if you want to reload the page after completion
  })
});
Mikelo
  • 271
  • 2
  • 16
  • thank you so much for your comment ..i have tried your js code and it still not working – Abdallah Mar 13 '19 at 09:24
  • @Abdallah That is because the code is immediately executed when the page is loaded. In this case, `name` and `body` are empty and thus you'll receive the same (empty) output. You should consider removing the `
    ` tags and replace your `` with a button and use jQuery's `.click()` to submit the form (so you don't have to reload your page). Or if you insist on using a `
    ` I would take a look at Ataullah's answer. I will update my answer to show you what I mean.
    – Mikelo Mar 13 '19 at 09:33
  • sorry for the late replay i have tried your method and its still not working ..i think their might be a problem in my controller – Abdallah Mar 14 '19 at 09:17
0

You have to pass form data with ajax.

$("#formID").submit(function(e) {

        e.preventDefault();
        var form = $(this);
        var URL= form.attr('action');

        $.ajax({
        type: "POST",
        url: URL,
        data: form.serialize(), 
        success: function(data)
        {
            console.log(data);
        }
        });
});