将ID从foreach传递到模式

时间:2018-08-10 18:15:43

标签: javascript php jquery ajax

我正试图将我的$model['id']从foreach传递到包含形式,该形式对if语句和函数非常需要$model['id']的形式。

我尝试在按钮周围放置一个链接以使用通常的$_GET,但是这会强制页面刷新并因此关闭模式框,如果URL包含ID?

或者,我尝试使用通过AJAX post方法传递的data-id并以模态检索它。但是$_POST尚未定义,我错过了什么还是不能$_POST到同一页面?我对AJAX不太满意,因此不胜感激。

我的页面中有太多代码无法全部发布,因此这里是重要内容的摘录

<button data-id="<?php echo $model['id']; ?>" data-modal-type="type3" class="modal_button customer_button right">New Customer</button>

<div class="modal" id="type3">
    <div class="modal-content">
        <div class="modal-title"><h3>New Customer</h3></div>
        <div class="modal-padding">
            <?php
            $customer_model_id = (isset($_POST['id'])) ? $_POST['id'] : 'ID not found';
            echo $customer_model_id; // Always shows ID not found
            ?>
        </div>
    </div>
</div>

<script>
        $(".modal_button").click(function () {
        $(".modal").hide();
        var Type = $(this).data("modal-type");
        $("#" + Type).show();

        var id = $(this).data("id");
        alert($(this).data("id")); // Alert box shows the correct ID
        $.ajax({
            type: "POST",
            url: '<?php echo doc_root('index.php');//post to the same page we are currently on ?>',
            data: "id=" + id,
        });
    });
</script>

编辑: 我想我会越来越喜欢这个JavaScript。

<script> 
    $(".modal_button").click(function(){ 
    $(".modal").hide(); 
    var Type = $(this).data("modal-type"); 

    var id = $(this).data('id'); 
    $.ajax({ 
    type : 'POST', 
    url : 'customer_complete.php', 
    data : 'id='+ id, 
    cache: false, 
    success : function(data){ 
    $('.customer_complete').html(data); 
    } 
    }) 

    $("#"+Type).show(); 
    }); 
</script>

3 个答案:

答案 0 :(得分:0)

您的数据参数错误。

尝试一下:

    var idx = $(this).data("id");
    $.ajax({
        type: "POST",
        url: '<?php echo doc_root('index.php'); ?>',
        data: {id: idx}
    }).done(function( data ) {
       console.log( data );
    });

答案 1 :(得分:0)

据我了解,您已经在页面上获得了正确的ID值。看起来您是从php脚本( $ model ['id'] )获取的,并存储在按钮的 data-id 中。 另外,当您单击按钮时,看起来您已经可以获取此ID。进一步的操作取决于您将要做什么。

$(".modal_button").click(function () {
    var id = $(this).data("id"); //here you have an id
    $(some_selector).html(id); //to put it inside elements html
    $(another_selector).attr("placeholder", id); //to use it as placeholder (or any other attribute
});

这是用于同一页面上的js。

用于将其发布到服务器:

$.ajax({
    type: "POST",
    url: your_url,
    data: {
      id: id
    },
    success: function(result) {
        console.log(result);
        //some actions after POSTing
    }
});

在服务器上,通过$ _POST [“ id”]访问它。

为什么您做错了? 您的POST请求有效。您可以使用Chrome开发工具(“网络”标签)进行检查。它已发布到同一页面,并且可以。服务器的响应是一个带有id的内置html模式的html页面,正如您所希望的那样。但这是对AJAX调用的响应,它对您已加载的页面没有影响。另外,重新加载您始终具有“找不到ID”的页面,因为重新加载页面不会发出POST请求。

这是您所需要的一般逻辑: 您已经在页面上找到了ID。要将其传输到同一页面上的其他元素,构建为html标记等,请使用JS。 要将数据传输到服务器(例如,对于SQL),请使用AJAX。您最好创建一个单独的文件作为AJAX处理程序。该脚本将处理POSTed ID,执行所有必需的操作(如将新用户插入db),并将响应(简单的成功错误代码,字符串或JSON)发送回调用方。然后,在AJAX.success中,您可以处理响应,例如,如果操作失败,则通知用户。

希望这会有所帮助。

答案 2 :(得分:0)

我决定为您编写一些代码,因为我发现该任务很有趣。该代码模拟了您在问题和评论中提出的情况,并且相对易于遵循。您可以按原样运行它,但不要忘记在connection.php中用您的数据库凭据替换我的数据库凭据。所有文件都在文件系统层次结构中的同一niveau上。因此,您可以创建一个文件夹,将所有文件放入其中,然后运行index.php页面。我使用prepared statements插入db,从而避免了任何sql injections的风险。我还评论了这一部分,以防万一您不熟悉它。

玩得开心。


index.php

这是主页。

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
        <meta charset="UTF-8" />
        <!-- The above 3 meta tags must come first in the head -->

        <title>Demo - Modal</title>

        <!-- CSS assets -->
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">

        <style type="text/css">
            body { padding: 20px; }
            .success { color: #32cd32; }
            .error { color: #ff0000; }
        </style>

        <!-- JS assets -->
        <script src="https://code.jquery.com/jquery-3.3.1.min.js" type="text/javascript"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>

        <script type="text/javascript">
            $(document).ready(function () {
                $('#type3').on('show.bs.modal', function (event) {
                    var modal = $(this);
                    var button = $(event.relatedTarget);
                    var modelId = button.data('model-id');

                    $.ajax({
                        method: 'post',
                        dataType: 'html',
                        url: 'new_customer.php',
                        data: {
                            'modelId': modelId,
                            'modalId': 'type3'
                        },
                        success: function (response, textStatus, jqXHR) {
                            modal
                                    .find('.modal-padding')
                                    .html(response);
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            modal
                                    .find('.modal-messages')
                                    .removeClass('success')
                                    .addClass('error')
                                    .html('An error occurred during your request. Please try again, or contact us.');
                        }
                    });
                });

                $('#type3').on('hide.bs.modal', function (event) {
                    var modal = $(this);

                    modal.find('.modal-padding').html('');

                    modal
                            .find('.modal-messages')
                            .removeClass('success error')
                            .html('');
                });
            });
        </script>
    </head>
    <body>

        <button type="button" data-model-id="13" data-modal-type="type3" data-toggle="modal" data-target="#type3" class="modal_button customer_button right">
            New Customer
        </button>

        <div class="modal" id="type3">
            <div class="modal-content">
                <div class="modal-title">
                    <h3>New Customer</h3>
                </div>
                <div class="modal-messages"></div>
                <div class="modal-padding"></div>
            </div>
        </div>

    </body>
</html>

new_customer.php

此页面包含用于向customers表中添加新客户的表单。

<?php
$modelId = $_POST['modelId'] ?? NULL;
$modalId = $_POST['modalId'] ?? NULL;
?>

<script type="text/javascript">
    $(document).ready(function () {
        $('#saveCustomerButton').on('click', function (event) {
            var form = $('#addCustomerForm');
            var button = $(this);
            var modalId = button.data('modal-id');
            var modal = $('#' + modalId);

            $.ajax({
                method: 'post',
                dataType: 'html',
                url: 'add_customer.php',
                data: form.serialize(),
                success: function (response, textStatus, jqXHR) {
                    modal
                            .find('.modal-messages')
                            .removeClass('error')
                            .addClass('success')
                            .html('Customer successfully added.');

                    $('#resetAddCustomerFormButton').click();
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    var message = errorThrown;

                    if (jqXHR.responseText !== null && jqXHR.responseText !== 'undefined' && jqXHR.responseText !== '') {
                        message = jqXHR.responseText;
                    }

                    modal
                            .find('.modal-messages')
                            .removeClass('success')
                            .addClass('error')
                            .html(message);
                }
            });
        });
    });
</script>

<style type="text/css">
    #addCustomerForm {
        padding: 20px;
    }
</style>

<form id="addCustomerForm" action="" method="post">
    <input type="hidden" id="modelId" name="modelId" value="<?php echo $modelId; ?>" />

    <div class="form-group">
        <label for="customerName">Name</label>
        <input type="text" id="customerName" name="customerName" placeholder="Customer name">
    </div>

    <button type="button" data-modal-id="<?php echo $modalId; ?>" id="saveCustomerButton" name="saveCustomerButton" value="saveCustomer">
        Save
    </button>

    <button type="reset" id="resetAddCustomerFormButton" name="resetAddCustomerFormButton">
        Reset
    </button>
</form>

add_customer.php

此页面包含用于处理将客户保存到数据库中的代码。

<?php

require 'connection.php';
require 'InvalidInputValue.php';

use App\InvalidInputValue;

try {
    $modelId = $_POST['modelId'] ?? NULL;
    $customerName = $_POST['customerName'] ?? NULL;

    // Validate the model id.
    if (empty($modelId)) {
        throw new InvalidInputValue('Please provide the model id.');
    } /* Other validations here using elseif statements */

    // Validate the customer name.
    if (empty($customerName)) {
        throw new InvalidInputValue('Please provide the customer name.');
    } /* Other validations here using elseif statements */

    /*
     * Save the customer into db. On failure exceptions are thrown if and
     * only if you are setting the connection options correspondingly.
     * See "connection.php" for details.
     */
    $sql = 'INSERT INTO customers (
                model_id,
                name
            ) VALUES (
                ?, ?
            )';

    /*
     * Prepare the SQL statement for execution - ONLY ONCE.
     *
     * @link http://php.net/manual/en/mysqli.prepare.php
     */
    $statement = mysqli_prepare($connection, $sql);

    /*
     * Bind variables for the parameter markers (?) in the
     * SQL statement that was passed to prepare(). The first
     * argument of bind_param() is a string that contains one
     * or more characters which specify the types for the
     * corresponding bind variables.
     *
     * @link http://php.net/manual/en/mysqli-stmt.bind-param.php
     */
    mysqli_stmt_bind_param($statement, 'is', $modelId, $customerName);

    /*
     * Execute the prepared SQL statement.
     * When executed any parameter markers which exist will
     * automatically be replaced with the appropriate data.
     *
     * @link http://php.net/manual/en/mysqli-stmt.execute.php
     */
    mysqli_stmt_execute($statement);

    /*
     * Close the prepared statement. It also deallocates the statement handle.
     * If the statement has pending or unread results, it cancels them
     * so that the next query can be executed.
     *
     * @link http://php.net/manual/en/mysqli-stmt.close.php
     */
    mysqli_stmt_close($statement);

    /*
     * Close the previously opened database connection.
     * Not really needed because the PHP engine closes
     * the connection anyway when the PHP script is finished.
     *
     * @link http://php.net/manual/en/mysqli.close.php
     */
    mysqli_close($connection);
} catch (InvalidInputValue $exc) {
    /*
     * Throw an error to be catched by the "error" callback of the ajax request.
     * This can be achieved by sending a specific or a custom response header to the client.
     *
     *  - Specific header: A header containing any already assigned status code.
     *  - Custom header: A header containing any NOT already assigned status code. This type of
     *    headers have the reason phrase "Unassigned" in the official HTTP Status Code Registry.
     *
     * @link https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml HTTP Status Code Registry.
     */
    header('HTTP/1.1 500 Internal Server Error', TRUE, 500);
    echo $exc->getMessage();
    exit();
} catch (Exception $exc) {
    // For all other system failures display a user-friendly message.
    header('HTTP/1.1 500 Internal Server Error', TRUE, 500);
    echo 'An error occurred during your request. Please try again, or contact us.';
    exit();
}

connection.php

<?php

/*
 * This page contains the code for creating a mysqli connection instance.
 */

// Db configs.
define('HOST', 'localhost');
define('PORT', 3306);
define('DATABASE', 'tests');
define('USERNAME', 'root');
define('PASSWORD', 'root');

/*
 * Enable internal report functions. This enables the exception handling,
 * e.g. mysqli will not throw PHP warnings anymore, but mysqli exceptions
 * (mysqli_sql_exception).
 *
 * MYSQLI_REPORT_ERROR: Report errors from mysqli function calls.
 * MYSQLI_REPORT_STRICT: Throw a mysqli_sql_exception for errors instead of warnings.
 *
 * @link http://php.net/manual/en/class.mysqli-driver.php
 * @link http://php.net/manual/en/mysqli-driver.report-mode.php
 * @link http://php.net/manual/en/mysqli.constants.php
 */
$mysqliDriver = new mysqli_driver();
$mysqliDriver->report_mode = (MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

/*
 * Create a new db connection.
 *
 * @see http://php.net/manual/en/mysqli.construct.php
 */
$connection = mysqli_connect(HOST, USERNAME, PASSWORD, DATABASE, PORT);

InvalidInputValue.php

这是一个自定义异常类。当发布的用户输入值无效时,抛出此类型的异常。

<?php

namespace App;

use Exception;

/**
 * Custom exception. Thrown when posted user input values are invalid.
 */
class InvalidInputValue extends Exception {

}

“客户”表的定义

我没有创建models表,所以没有FK。

CREATE TABLE `customers` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `model_id` int(11) DEFAULT NULL,
  `name` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;