PHP-jQuery-AJAX:如何在使用模态表单时发布值

时间:2022-11-23 19:58:03

I'm having an issue passing input and textarea values from a form in modal to AJAX so I can pass them to php.

我有一个从模态到AJAX的输入和textarea值的问题,所以我可以把它们传递给php。

The input field and textarea values are coming up blank when I submit the form in modal and jquery is not displaying any errors. It simply POST an empty (blank) string for each element.

当我以模态形式提交表单时,输入字段和textarea值会显示为空,而且jquery不会显示任何错误。它只是为每个元素发布一个空(空)字符串。

for example, it shows something like this.

例如,它显示了这样的东西。

subject=&content=

in the dialog box, I load a name and an ID and both POST successfully but the input values which are not loaded with the form, are not being sent. I understand that the name and ID do POST because they are loaded on DOM along with the form but I do not know how to pass values that are not loaded along with the form in modal.

在对话框中,我加载了一个名称和一个ID,并且都成功地发布了,但是没有加载表单的输入值没有被发送。我理解名称和ID会发布,因为它们与表单一起加载在DOM上,但我不知道如何传递没有随表单一起加载的值。

This is a sample of the form.

这是表格的样本。

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

This is a sample of the jquery/ajax call.

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

Any ideas on why and/or how to POST these values?

对于为什么和/或如何发布这些价值观有什么想法吗?

Thanks in advance,

提前谢谢,

Note: Excuse the formatting for the HTML portion. It's hard to properly format everything using a phone.

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

2 个解决方案

#1


2  

Note: If you are trying to define multiple modal using while loop,

注意:如果要使用while循环定义多个模态,

Your HTML

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

Your Script

你的脚本

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

Note: You just need to understand the JQuery selector (ID and Class). See the difference between #ID and .Class selectors in Jquery.

注意:您只需要理解JQuery选择器(ID和类)。请参见Jquery中的#ID和. class选择器之间的区别。

You are generating multiple Modal with same ID and try to get those field values using IDs (selector). But the IDs for each modal input fields must be unique to get the value. and for on click operation the button must have unique ID or you just need to define class as above code has.

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

See how I have defined class for click button and getting ID for each modal. Modal must be unique in the sense of their field.

看看我如何定义了单击按钮的类,并为每个模式获取ID。模态必须在它们的场意义上是唯一的。

#2


0  

Example done POST request with Ajax call on ModalBox

My View page code:

我的视图页面代码:

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

Modals on the same page:

同页的Modals:

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

Here is Script:

这是脚本:

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

Routes is:

路线是:

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

Put this line on page Head:

把这一行写在页首:

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

And in Controller Create and Get routes:

在控制器中创建和获取路由:

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

And these definitions:

和这些定义:

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

#1


2  

Note: If you are trying to define multiple modal using while loop,

注意:如果要使用while循环定义多个模态,

Your HTML

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

Your Script

你的脚本

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

Note: You just need to understand the JQuery selector (ID and Class). See the difference between #ID and .Class selectors in Jquery.

注意:您只需要理解JQuery选择器(ID和类)。请参见Jquery中的#ID和. class选择器之间的区别。

You are generating multiple Modal with same ID and try to get those field values using IDs (selector). But the IDs for each modal input fields must be unique to get the value. and for on click operation the button must have unique ID or you just need to define class as above code has.

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

See how I have defined class for click button and getting ID for each modal. Modal must be unique in the sense of their field.

看看我如何定义了单击按钮的类,并为每个模式获取ID。模态必须在它们的场意义上是唯一的。

#2


0  

Example done POST request with Ajax call on ModalBox

My View page code:

我的视图页面代码:

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

Modals on the same page:

同页的Modals:

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

Here is Script:

这是脚本:

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

Routes is:

路线是:

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

Put this line on page Head:

把这一行写在页首:

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

And in Controller Create and Get routes:

在控制器中创建和获取路由:

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

And these definitions:

和这些定义:

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