简体   繁体   English

用AJAX将模态表单数据发布到php

[英]POSTing modal form data with AJAX to php

I'm a beginner in the world of web programming and I'm in need of some guidance to help me solve a problem. 我是Web编程领域的初学者,需要一些指导来帮助我解决问题。 I apologize that my fundamentals are not very strong at this point. 我很抱歉,目前我的基本面还不是很强。

I have a main page called view.adminsettings.php which I placed a Navigation DIV and a content DIV. 我有一个名为view.adminsettings.php的主页,其中放置了导航DIV和内容DIV。 I have a link in the Navigation DIV that loads the content of a 2nd PHP page called view.pdus_1.php into the content DIV of view.adminsettings.php. 我在导航DIV中有一个链接,该链接将名为view.pdus_1.php的第二个PHP页面的内容加载到view.adminsettings.php的内容DIV中。 On this view.pdu_1.php I have a bootstrap modal popup containing a form in which to submit if the user wants to create another "PDU" in the existing list. 在此view.pdu_1.php上,我有一个引导模式弹出窗口,其中包含一个表单,如果用户要在现有列表中创建另一个“ PDU”,则该表单应提交。 I'd like the user to be able to submit this information via POST to a action.pdu_1.php page that will input the form data to the database. 我希望用户能够通过POST将此信息提交到action.pdu_1.php页面,该页面会将表单数据输入数据库。 I'd also like the view.pdu_1.php page to refresh in the content DIV page of the view.adminsettings.php page so that the user can immediately view their newly created item. 我还希望view.pdu_1.php页面在view.adminsettings.php页面的内容DIV页面中刷新,以便用户可以立即查看其新创建的项目。

My issues are many unfortunately. 不幸的是,我的问题很多。 I'd like help solving the following two issues: 我想帮助解决以下两个问题:

1) I am having trouble getting the data from the form to properly POST to the action.pdu_1.php page. 1)我无法将数据从表单正确地发布到action.pdu_1.php页面。 Right now it does both POST (without parameter) and GET. 现在,它同时执行POST(不带参数)和GET。 Which page should I post this code? 我应该在哪个页面上发布此代码? view.adminsettings.php or view.pdu_1.php? view.adminsettings.php或view.pdu_1.php?

2) I am also having trouble refreshing the view.pdu_1.php page within the content DIV. 2)我也无法刷新内容DIV中的view.pdu_1.php页面。 It does not reload the view.pdu_1.php page back into the DIV. 它不会将view.pdu_1.php页面重新加载到DIV中。

Current code to load view.pdu_1.php page into content div (WORKING): 当前代码,用于将view.pdu_1.php页面加载到内容div中(工作):

function loadPDUs(){
$(function() {
    $('#DisplayDiv').load('/pdus');
    return false;
});
};

HTML snippnet for DIVs in view.adminsettings.php: view.adminsettings.php中用于DIV的HTML片段网络:

<div class="container-fluid">

<div class="row">

    <div id="nav" class="col-md-2"> 

        <h4>Admin Settings</h4>
        <div style="height:20px"></div>
        <p><a href="#" onclick="return loadPDUs();"><i class="fa fa-plug"></i> PDUs </a></p>

    </div>


    <div id="DisplayDiv" class="col-md-10">
        <!-- PDU content here -->
    </div>
</div>

Sample boostrap modal form code: 样品boostrap模态形式代码:

<div class="modal fade" id="addpdu">
<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
            <h4 class="modal-title">Add PDU</h4>
        </div>
        <div class="modal-body" id="addpdudiv">
            <form class="form-horizontal">
                <input type="hidden" name="action" id="pduaddaction" value="add">
                <div class="form-group">
                    <label for="pduname" class="col-sm-2 control-label">Name</label>
                    <div>
                        <input type="text" class="form-control" id="pduname" placeholder="PDU Name" name="name">
                    </div>
                    <br>
                    <label for="pduports" class="col-sm-2 control-label">Ports</label>
                    <div>
                        <input type="text" class="form-control" id="pduports" placeholder="Number of ports" name="ports">
                    </div>
                    <br>
                    <p class="text-center">
                        <button id="submitpduadd" class="btn btn-primary">Save</button> &nbsp; <button type="reset" class="btn btn-default">Reset</button>
                    </p>
                </div>
            </form>
        </div>
    </div>
</div>

Sample AJAX 样本AJAX

$(function(){
$("button#submitpduadd").click(function(){
    $.ajax({
        type: "POST",
        url: "/actions/action.pdu_1.php",
        data: $('form.form-horizontal').serialize(),
        success: function(){
            console.log("submit successful");
            $("#addpdudiv").modal('hide');
            $('#DisplayDiv').load('/pdus');
        },
        error: function(){
            alert("failure");
        }
    });
});
});

Sample Action.pdu_1.php Code: 示例Action.pdu_1.php代码:

<?php
session_start();

$action = filter_input(INPUT_POST, "action");

if($action === "add") {

$name = filter_input(INPUT_POST, "name");
$ports = filter_input(INPUT_POST, "ports");

$pdu = new pdu();

$pdu->create($name, $ports, $location);

}
?>

I can offer some suggestions. 我可以提供一些建议。 First for the PDU loading: 首先进行PDU加载:

<div class="container-fluid">
    <div class="row">
        <div id="nav" class="col-md-2"> 
            <h4>Admin Settings</h4>
            <div style="height:20px"></div>
            <p><a href="/pdus" id="loadPDU"><i class="fa fa-plug"></i> PDUs</a></p>
        </div>
        <div id="DisplayDiv" class="col-md-10">
           <!-- PDU content here -->
        </div>
    </div>
</div>
<script>
$(function(){
    $("#loadPDU").click(function(e){
        e.preventDefault();
        $('#DisplayDiv').load($(this).attr("href"));
    });
});
</script>

Just a little more portable and if a browser that does not support or use JS/JQuery, it will fail back, sort of. 只是更具可移植性,如果浏览器不支持或不使用JS / JQuery,它将回退。 You can also then make other links or buttons that can leverage the same code. 然后,您还可以创建其他可以利用相同代码的链接或按钮。

Your AJAX code is fine overall. 您的AJAX代码总体来说还不错。 A few small changes can make it more solid and let you know if it's working or dying someplace. 进行一些小的更改可以使其更牢固,并让它知道它在起作用还是在某个地方死亡。

$(function(){
    $("button#submitpduadd").click(function(){
        $.ajax({
            type: "POST",
            url: "/actions/action.pdu_1.php",
            data: $('form.form-horizontal').serialize(),
            type: 'JSON',
            success: function(retData){
                if(retData.error.length){
                    console.log(retData.error);
                } else {
                    console.log(retData);
                }
                $("#addpdudiv").modal('hide');
                $('#DisplayDiv').load('/pdus');
            },
            error: function(){
                alert("HTTP failure. Try Again.");
            }
        });
    });
});

The nature of PHP errors will almost always return a 200 status, so AJAX will very rarely get a 400 or 500 status response when making an HTTP Request. PHP错误的性质几乎总是返回200状态,因此在发出HTTP请求时AJAX很少会收到400或500状态响应。 You can force it to do so, yet this is time consuming and you can't details back when it fails. 您可以强制执行此操作,但这很耗时,并且无法在失败时返回详细信息。 This means that success() is going to be hit even if PHP encounters an error. 这意味着即使PHP遇到错误,也会击中success() Our PHP needs to be able to tell our JS/JQuery that an error was encountered. 我们的PHP必须能够告诉我们的JS / JQuery遇到错误。

<?php
session_start();

$action = filter_input(INPUT_POST, "action");
if($action === "add") {
    $name = filter_input(INPUT_POST, "name");
    $ports = filter_input(INPUT_POST, "ports");
    $location = (isset($_POST['location'])?filter_input(INPUT_POST, "location"):"");
    $params = array("name" => $name, "ports" => $ports, "loc" => $location);
    try {
        $pdu = new pdu();
        $pdu->create($name, $ports, $location);
    } catch (Exception $e) {
        $error = array('error' => 'Caught exception: ' .  $e->getMessage());
    }
    echo (isset($error))?json_encode($error):json_encode($params));
}
?>

So now the PHP will return something even if their is a failure. 因此,即使它们失败了,PHP现在也会返回一些信息。 We can examine that data, success or failure, and figure out whats happening. 我们可以检查数据,成功或失败,并找出正在发生的事情。 Even if PHP has a error earlier, the resulting HTML should be view-able using FireBug or other debug tools. 即使PHP较早出现错误,使用FireBug或其他调试工具也应可以查看生成的HTML。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM