当前位置: 动力学知识库 > 问答 > 编程问答 >

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

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. Right now it does both POST (without parameter) and GET. Which page should I post this code? view.adminsettings.php or view.pdu_1.php?

2) I am also having trouble refreshing the view.pdu_1.php page within the content DIV. It does not reload the view.pdu_1.php page back into the DIV.

Current code to load view.pdu_1.php page into content div (WORKING):

function loadPDUs(){

$(function() {

$('#DisplayDiv').load('/pdus');

return false;

});

};

HTML snippnet for DIVs in view.adminsettings.php:

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

<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

$(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:

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

<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. You can also then make other links or buttons that can leverage the same code.

Your AJAX code is fine overall. 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. 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. Our PHP needs to be able to tell our JS/JQuery that an error was encountered.

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

分享给朋友:
您可能感兴趣的文章:
随机阅读: