weixin_33716941 2019-03-13 08:33 采纳率: 0%
浏览 12

无法使用ajax加载表单

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"
}
  • 写回答

2条回答 默认 最新

  • weixin_33691817 2019-03-13 08:58
    关注

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

报告相同问题?

悬赏问题

  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名