通过Laravel中的ajax传递变量

时间:2017-11-26 06:38:43

标签: php jquery ajax

我在foreach中有一个按钮来提供用户项目,当我点击按钮打开弹出窗口创建工作报告时,我的代码就在这里:

@foreach(Auth::user()->projects as $project)
   <a href="#">
      <button type="submit" data-toggle="modal" data-target="#myModal{{$project->id}}" id="Addtr">
        today Report
    </button>
   </a>
<div class="modal fade" tabindex="-1" role="dialog"
    id="myModal{{$project->id}}">
      <input type="hidden" value="{{$project->id}}" id="project_id">
          <div class="form-group has-feedback has-feedback-left">
            <input type="text" class="form-control"  id="description">
               </div>
            <button type="submit" class="btn bg-teal btn-block btn-lg 
                    AddTodayReport"
                   data-dismiss="modal"
                      id="AddTodayReport">save
              </button>
    </div>
     {{csrf_field()}}

<script>

$(document).ready(function () {                                                                   
     $('#AddTodayReport').click(function (event) {
        var project_id = $('#project_id').val();
        var description = $('#description').val();
          console.log(project_id);
   });
  });
 </script>

我的问题在于,当我点击保存按钮(#AddTodayReport)将数据传递给ajax并在控制台中打印project_id时,我只需要给出第一个项目的ID和在其他项目中我不提供任何东西,我在输入之前打印{{project->id}}并且当前接收任何项目,我如何解决我的问题?

1 个答案:

答案 0 :(得分:0)

你必须将你的id改为class。因为ID必须是唯一的。它不能重复。

所以改变模态如下

reason

将id更改为class后,添加javascript如下:

<div class="modal fade" tabindex="-1" role="dialog"
    id="myModal{{$project->id}}">
      <input type="hidden"  value="{{$project->id}}"  class="project_id">
          <div class="form-group has-feedback has-feedback-left">
            <input type="text"   class="form-control description" >
               </div>
            <button type="submit"  class="btn bg-teal btn-block btn-lg 
                    AddTodayReport"
                   data-dismiss="modal"
                      class="AddTodayReport">save
              </button>
    </div>