无法使用ajax加载表单

时间:2019-03-13 08:33:47

标签: php ajax

我使用php mvc模式创建了一个简单的博客网站,我正尝试使用ajax向数据库中添加帖子,但它给了我一个我无法解决的错误响应

我已将URLROOT定义为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>

我已经在发布控制器中创建了一个add方法

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);
    }
}

因此,一旦我加载添加页面,我会收到一条json错误消息,提示必须输入名称

我得到的输出

{
    "success":false,
    "message":"Name required Description required"
}

2 个答案:

答案 0 :(得分:0)

如您的输出所示,$ _POST元素为空。要解决此问题,必须将变量分配给表单的各个元素。

我也同意Magnus Eriksson关于仅在提交表单时触发js代码的想法。

<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>

更新

这是使用JQuery的.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
  })
});

答案 1 :(得分:0)

您必须使用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);
        }
        });
});