PHP-jQuery-AJAX:如何在模态

时间:2017-04-19 17:22:07

标签: php jquery ajax

我有一个问题是将输入和textarea值从modal中的表单传递给AJAX,因此我可以将它们传递给php。

当我以模态提交表单时,输入字段和textarea值将显示为空白,而jquery未显示任何错误。它只是为每个元素POST一个空(空白)字符串。

例如,它显示了类似的内容。

subject=&content=

在对话框中,我加载了一个名称和一个ID,并且两个POST都成功,但未发送未加载表单的输入值。我知道名称和ID会执行POST,因为它们与表单一起加载到DOM上,但我不知道如何传递未在模式中加载的值。

这是表格的一个样本。

<?php while($row = mysqli_fetch_array($res)){
                //row data for each post
                $r_id = $row['r_id'];
                $name = $row['name'];
?>
<div id="m_f_box" class="modal fade msg-box-custom" tabindex="-1" data-width="400">
                <div class="modal-header-custom">
                                <h5 class="modal-title">Send to <span><?php echo $name ?></span></h5>
                </div>
                <form id="user_m_form" name="user_m_form" action="#" method="POST">
                <div class="modal-body">
                                <div class="row">
                                                <div class="col-md-12">
                                                                <div id="s_row" class="col_full">
                                                                <h5>Asunto</h5>
                                                <input id="m_subject" name="m_subject" class="required sm-form-control" type="text" maxlength="40"></input>
                                                                </div>
                                                                <div id="m_row" class="col_full">
                                                                <h5>Mensaje</h5>
                                                                                <textarea id="m_content" name="m_content" class="required sm-form-control" type="text"></textarea>
                                                                </div>
                                                </div>
                                </div>
                </div>
                                <div class="modal-footer">
                                                <button type="submit" id="send_m" name="user_m_form" class="button button-mini button-blue" value="<?php echo $r_id ?>">Send</button>
                                                <button type="button" id="can_m" name="can_m" data-dismiss="modal" class="button button-mini button-blue">Cancel</button>
                                </div>
                </form>
</div>
<?php } ?>

这是jquery / ajax调用的示例。

<script type="text/javascript">
$(document).on('click', '#send_m', function(e){
                e.preventDefault();
                var r_id = $('#send_m').val();
                var subject = $('#m_subject').val();
                var content = $('#m_content').val();
                //var form_data = $('#user_m_form').serialize(); test with serialized form data.
                //alert(subject); test what is being sent as an alert
                //console.log(subject); test what is being sent to view in console

                $.ajax({
                type:'POST',
                url:'test_file.php',
                data: {   r_id : recipient_id,
                          subject : subject,
                          content : content,
                      },
                cache: false,
                success:function(res){

                   //do some stuff
                                }
                });
                return false;
});
</script>

关于为什么和/或如何发布这些值的任何想法?

提前致谢,

注意:请原谅HTML部分的格式。使用手机正确格式化所有内容很困难。

2 个答案:

答案 0 :(得分:2)

注意:如果您尝试使用 while 循环定义多个模式,

您的HTML

<div id="m_f_box" class="modal fade msg-box-custom" tabindex="-1" data-width="400">
    <div class="modal-header-custom">
        <h5 class="modal-title">Send to <span><?php echo $name ?></span></h5>
    </div>
    <form id="user_m_form" name="user_m_form" action="#" method="POST">
    <div class="modal-body">
        <div class="row">
            <div class="col-md-12">
                <div id="s_row" class="col_full">
                <h5>Asunto</h5>
            <input id="m_subject_<?php echo $row['r_id']; ?>" name="m_subject" class="required sm-form-control" type="text" maxlength="40"></input>
                </div>
                <div id="m_row" class="col_full">
                <h5>Mensaje</h5>
                                <textarea id="m_content_<?php echo $row['r_id']; ?>" name="m_content" class="required sm-form-control" type="text"></textarea>
                </div>
            </div>
        </div>
    </div>
        <div class="modal-footer">
            <button type="submit" id="<?php echo $row['r_id']; ?>" name="user_m_form" class="button button-mini button-blue send" value="<?php echo $r_id ?>">Send</button>
            <button type="button" id="can_m" name="can_m" data-dismiss="modal" class="button button-mini button-blue">Cancel</button>
        </div>
    </form>
</div>
<?php } ?>

您的脚本

<script type="text/javascript">
$(document).on('click', '.send', function(e){
    var r_id = (this).attr('id');
    var subject = $('#m_subject'+id).val();
    var content = $('#m_content'+id).val();

    //......
    //.......
});
</script>

注意:您只需要了解JQuery选择器(ID和Class)。查看Jquery中#ID.Class选择器之间的区别。

您正在生成具有相同ID的多个Modal,并尝试使用ID(选择器)获取这些字段值。但是每个模态输入字段的ID必须是唯一的才能获取值。对于单击操作,该按钮必须具有唯一ID,或者您只需要按照上面的代码定义类。

了解我如何为点击按钮定义类并获取每个模态的ID。模态在其领域意义上必须是唯一的。

答案 1 :(得分:0)

使用ModalBox上的Ajax调用完成POST请求的示例

我的浏览页面代码:

<div class="panel panel-default">
    <div class="panel-body">
        <p class="text-danger">There are total <span class="text-bold">{{ sizeof($data) }}</span> Departments.</p>
        <table class="table" id="department-data">
            <tr>
                <th>#</th>
                <th>Name</th>
                <th>Edit</th>
                <th>Delete</th>
                <th>Manage</th>
            </tr>
            <?php $order = 0; ?>
            @foreach($data as $key)
            <tr>
                <td>{{ ++$order }}</td>
                <td id="department_name">{{ $key->title }}</td>
                <td>
                    <a href="#">
                        <button class="btn  btn-default edit-department" data-toggle="modal" data-target="#updateDepartmentModel" id="{{ $key->id }}"><i class="fa fa-pencil"></i></button>
                    </a>
                </td>
                <td>
                    <button id="{{ $key->id }}" class="btn btn-danger delete-btn" data-toggle="modal" data-target="#delete-department"><i class="fa fa-trash"></i></button>
                </td>
                <td>
                    <a href='program/{{ $key->id }}' id="delete-id">
                        <button class="btn btn-primary"><i class="fa fa-cog"></i></button>
                    </a>
                </td>
            </tr>
            @endforeach
        </table>
    </div>
</div>

同一页面上的模式:

<!-- Add New Department Modal -->
<div class="modal fade" id="newDepartmentModel" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add New Department</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form action="{{ url('department/create') }}" method="POST">
                {{ csrf_field() }}
            <div class="modal-body">
                    <div class="form-group">
                        <label for="title">Department Name:</label>
                        <input type="text" class="form-control" id="title" name="title">
                    </div>
            </div>
            <div class="modal-footer">
                <button type="submit" class="btn btn-primary">Add</button>
                <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
            </div>
            </form>
        </div>
    </div>
</div>
<!-- ./Model -->

<!-- Update Department Modal -->
<div class="modal fade" id="updateDepartmentModel" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Update a Department</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form>
                <div class="modal-body">
                    <div class="form-group">
                        <label for="old-title">Department Name:</label>
                        <input type="text" class="form-control" id="old-title" name="title">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" id="edit-dept" class="btn btn-primary edit-dept">Edit</button>
                    <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
                </div>
            </form>
        </div>
    </div>
</div>
<!-- ./Model -->

这是脚本:

<script type="text/javascript">

    var token = '{{ Session::token() }}';
    var url = '{{ route('department/edit') }}';
    var dept_id = '';

    // Setup Ajax
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    // Update the department
    $(document).on('click', '.edit-department',  function () {
        var department_id = $(this).attr('id');
        console.log(department_id);
        dept_id = department_id;
        $.get('department/'+department_id, function (data) {
            $('#old-title').val(data.title);
            console.log(data);
        });

    });


    // Handle Post Request (Edit Department)
    $(document).ready(function () {
        $('#edit-dept').click(function () {
            $.ajax({
                method: 'POST',
                url: url,
                data: { id: dept_id, title: $('#old-title').val(), _token: token},
                dataType: 'JSON'
            }).done(function (data) {
                //console.log(data);
            });
        });
    });


</script>

路线是:

Route::post('department/edit', function (\Illuminate\Http\Request $request){

$id = $request->input('id');
$title = $request->input('title');
DB::table('departments')->where('id', $id)->update(array('title' => $title));
return redirect('department')->with('alert_info', 'Department was successful Update!');})->name('department/edit');

将此行放在页面上:

<!-- csrf for meta -->
<meta name="csrf-token" content="{{ csrf_token() }}" />

在Controller创建和获取路径中:

Route::post('department/create', 'DepartmentController@store');
Route::get('department/{id}', 'DepartmentController@showById');

这些定义:

public function store(StoreDepartmentPostRequest $request)
{
    $department = new Department;
    $department->title = $request->input('title');
    $department->timestamps = time();
    $department->save();

    return redirect('department')->with('alert_success', 'Department was successful added!');

}



public function showById($id){
        $data = Department::findOrFail($id);

        return response()->json($data);
    }