doutan2111
2019-05-21 21:38
浏览 64
已采纳

为什么javascript会将这些变量作为对象在php中提供?

I am trying to pass some variables to a PHP file in order to run an SQL query. However JavaScript is passing these variables as objects. Why is this happening? How can I change that?

  <?php include 'dbconfig.php';?>
<?php header('Content-Type: text/html; charset=utf-8');?>

<!DOCTYPE HTML PUCLIC "-//W3C//DTDHTML 4.0 Transitional//EN">
<HTML>
<HEAD>
    <TITLE>LIBRARY DATABASE</TITLE>
    <link rel="stylesheet" type="text/css" href="mytable.css">
    <link rel="stylesheet" type="text/css" href="styles.css">
    <link rel="stylesheet" type="text/css" href="jquerycss.css">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript"></script>
    <script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js" type="text/javascript"></script>
    <script type="text/javascript">

        $(function () { 

            var new_dialog = function (type, row) {
            var dlg = $("#dialog-form").clone();
            var memberID = dlg.find(("#memberID")),
            MFirst = dlg.find(("#MFirst")),
            MLast = dlg.find(("#Mlast")),
            Street = dlg.find(("#Street")),
            number = dlg.find(("#number")),
            postalCode = dlg.find(("#postalCode")),
            Mbirthdate = dlg.find(("#Mbirthdate"));
                type = type || 'Create';
                var config = {
                    autoOpen: true,
                    height: 500,
                    width: 600,
                    modal: true,
                    buttons: {
                        "Create an account": save_data,
                        "Cancel": function () {
                            dlg.dialog("close");
                        }
                    },
                    close: function () {
                        dlg.remove();
                    }
                };
                if (type === 'Edit') {
                    config.title = "Edit User";
                    get_data();
                    delete (config.buttons['Create an account']);
                    config.buttons['Edit account'] = function () {
                        window.open("edituple.php?memberID="+ memberID +"&MFirst=" + MFirst +"&MLast=" + MLast +"&Street=" + Street
                        +"&number=" + number + "&postalCode=" + postalCode +"&Mbirthdate=" + Mbirthdate);
                        dlg.dialog("close");
                    }; 
                }
                dlg.dialog(config); 
                function get_data() {
                    var _memberID = $(row.children().get(1)).text(),
                     _MFirst = $(row.children().get(2)).text(),
                     _MLast = $(row.children().get(3)).text(),
                    _Street = $(row.children().get(4)).text(),
                    _number = $(row.children().get(5)).text(),
                    _postalCode = $(row.children().get(6)).text(),
                    _Mbirthdate = $(row.children().get(7)).text();
                    memberID.val(_memberID);
                    MFirst.val(_MFirst);
                    MLast.val(_MLast); 
                    Street.val(_Street);
                    number.val(_number); 
                    postalCode.val(_postalCode);
                    Mbirthdate.val(_Mbirthdate); 
                } 
                function save_data() {
                    $("#users tbody").append("<tr>" + "<td>" + (fname.find("option:selected").text() + ' ').concat(lname.find("option:selected").text()) + "</td>" + "<td>" + email.val() + "</td>" + "<td>" + password.val() + "</td>" + "<td><a href='' class='edit'>Edit</a></td>" + "<td><span class='delete'><a href=''>Delete</a></span></td>" + "</tr>");
                    dlg.dialog("close");
                }
            }; 
            $(document).on('click', 'span.delete', function () {
                $(this).closest('tr').find('td').fadeOut(1000, 
        function () {
            // alert($(this).text());
            $(this).parents('tr:first').remove();
        }); 
                return false;
            });
            $(document).on('click', 'td a.edit', function () {
                new_dialog('Edit', $(this).parents('tr'));
                return false;
            }); 
            $("#create-user").button().click(new_dialog); 
        });
    </script>
</HEAD>
<BODY>
<div class="navbar">
                <a href="mydatabase.php">Home</a>
                <a href="member_table.php">Member</a>
                <a href="book_table.php">Book</a>
                <a href="borrows_table.php">Borrows</a>
              </div>
              <br><br>
              <div class="navbar2">
                    <a href="insert.php">Insert</a>
                    <a href="update.php">Update</a>
                    <a href="delete.php">Delete</a>
                  </div>

    <TABLE class="minimalistBlack">
        <thead>
        <tr>
        <th> memberID </th>
        <th> First Name </th>
        <th> Last Name </th>
        <th> Street </th>
        <th> Number </th>
        <th> Postal Code </th>
        <th> Birthdate </th>
        <th> Update </th>
        </tr>
        </thead>
        <?php 
            $conn= mysqli_connect("localhost","root","","library");
            mysqli_set_charset($conn, "utf8");

            if ($conn -> connect_error){
                die("Conenction failed:". $conn->connect_error);
            }
            $sql="SELECT memberID,MFirst,MLast,Street,number,postalCode,Mbirthdate FROM member";
            $result = $conn->query($sql);
            if ($result->num_rows>0){

                while($row= $result->fetch_assoc()){
                    echo "<tr>";
                    echo "<td>".$row['memberID']."</td>";
                    echo "<td>".$row['MFirst']."</td>";
                    echo "<td>".$row['MLast']."</td>";    
                    echo "<td>".$row['Street']."</td>"; 
                    echo "<td>".$row['number']."</td>"; 
                    echo "<td>".$row['postalCode']."</td>"; 
                    echo "<td>".$row['Mbirthdate']."</td>"; 
                    echo "<td><a class =\"edit\" href=\"\">Edit </a>
                     | <a href=\"deletefmtable.php?memberID=$row[memberID]\" onClick=\"return confirm('Are you sure you want to delete?')\">Delete</a></td>";  
                }
                echo "</TABLE>";
            }
            else { echo "0 result"; }
            $conn->close();
         ?>
    </TABLE>
    <div id="dialog-form" title="Create new user" style="display:none">

        <p class="validateTips">

            All form fields are required.</p>       

            <form>

        <fieldset>

            <label for="memberID">

                Member ID </label>

                <input type="text" name="email" id="email" value="" class="text ui-widget-content ui-corner-all" />

            <label for="MFirst">

                First Name</label>

                <input type="text" name="email" id="email" value="" class="text ui-widget-content ui-corner-all" />


            <label for="MLast">

                Last Name </label>

            <input type="text" name="email" id="email" value="" class="text ui-widget-content ui-corner-all" />

            <label for="Street">

                Street </label>

            <input type="text" name="password" id="password" value="" class="text ui-widget-content ui-corner-all" />

            <label for="number">

             number </label>

            <input type="text" name="password" id="password" value="" class="text ui-widget-content ui-corner-all" />

            <label for="postalCode">

            Postal Code </label>

            <input type="text" name="password" id="password" value="" class="text ui-widget-content ui-corner-all" />

            <label for="Mbirthdate">

            Birthdate </label>

            <input type="text" name="password" id="password" value="" class="text ui-widget-content ui-corner-all" />

        </fieldset>

        </form>

    </div>
</BODY>
</HTML>

The purpose of the code , is to display a table and have edit and delete on the side. Delete button works perfectly , however for edit I need to pass the variables mentioned above to a php file

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douzhuo3233 2019-05-22 17:33
    已采纳

    Ok, I like a challenge. Starting from the top:

    1. You want to avoid mixing your PHP and HTML as much as possible. Likewise for JavaScript. Ideally they're in separate files altogether, but we'll just separate them here. Do your work at the top, and limit yourself to display only code down below.

    2. Always escape data for display in HTML. Use htmlspecialchars() for this.

    3. This isn't 1999, you should be using a modern document type declaration. Modern HTML also means lowercase elements and no need for type attributes on the <script> elements.

    4. Indent and space your code consistently. It will help you debug problems and find efficiencies.

    5. Declare variables with var either before using them or when first used

    6. You shouldn't be cloning this dialog. Just populate it with new values when clicked.

    7. Here we start getting into your real issues. First, you're relying on global variables way too much. As one example, you set all these variables' values in a get_data() function. But that happens when the dialog is being set up, not when the button is pushed. This stuff needs to happen at the time the form is submitted. (But see #12.)

    8. We can get rid of that get_data() function altogether and move its functionality to where it belongs, the click handler for the edit link.

    9. Using data- attributes is a great way to pass data from PHP to your client-side script. You can set these attributes on the button and avoid clumsy DOM traversal, instead just use $.data().

    10. Anytime something is getting changed or created, use the POST action, not GET. As the name implies, GET is only for fetching resources and should not take actions that change data.

    11. Why remove completely with the dialog with the close property? I assume you want to reuse it or you wouldn't have the results from the edit pop up in a new window.

    12. There's no need to get JS involved in your form submission at all, if you aren't using Ajax; just let the form submit normally.

    13. Be consistent with your code. Why does the delete button have an event handler in the HTML, when all the others are separate?

    14. You weren't closing your <tr> elements, and you closed your <table> element twice.

    15. All your form elements were named and ID'd incorrectly.

    This should do the trick:

    <?php
        include 'dbconfig.php';
        $conn= mysqli_connect("localhost","root","","library");
        mysqli_set_charset($conn, "utf8");
    
        if ($conn -> connect_error) {
            die("Conenction failed:". $conn->connect_error);
        }
        $sql="SELECT memberID, MFirst, MLast, Street, number, postalCode, Mbirthdate FROM member";
        $result = $conn->query($sql);
        $data = [];
        while ($row= $result->fetch_assoc()) {
            $data[] = array_map("htmlspecialchars", $row);
        }
        $conn->close();
    
        // test data
        $data = [
            ["memberID"=>1, "MFirst"=>"John", "MLast"=>"Smith", "Street"=>"Main St", "number"=>"123", "postalCode"=>"K1A 1A1", "Mbirthdate"=>"1990-06-27"]
        ];
        header('Content-Type: text/html;charset=utf-8');
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <title>LIBRARY DATABASE</title>
        <meta http-equiv="content-type" content="text/html;charset=UTF-8">
        <link rel="stylesheet" type="text/css" href="mytable.css">
        <link rel="stylesheet" type="text/css" href="styles.css">
        <link rel="stylesheet" type="text/css" href="jquerycss.css">
        <script src="http://code.jquery.com/jquery-1.8.3.js"></script>
        <script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
    
        <script>
            $(function () { 
                var new_dialog = function (type) {
                    var dlg = $("#dialog-form");
                    type = type || 'Create';
                    var config = {
                        autoOpen: true,
                        height: 500,
                        width: 600,
                        modal: true,
                        buttons: {
                            "Create an account": function () {
                                $("#users tbody").append("<tr>" + "<td>" + (fname.find("option:selected").text() + ' ').concat(lname.find("option:selected").text()) + "</td>" + "<td>" + email.val() + "</td>" + "<td>" + password.val() + "</td>" + "<td><a href='' class='edit'>Edit</a></td>" + "<td><span class='delete'><a href=''>Delete</a></span></td>" + "</tr>");
                                dlg.dialog("close");
                            },
                            "Cancel": function () {
                                dlg.dialog("close");
                                return true;
                            }
                        }
                    };
                    if (type === 'Edit') {
                        config.title = "Edit User";
                        delete (config.buttons['Create an account']);
                        config.buttons['Edit account'] = function () {
                            // just let the form submit itself normally
                            $("#dialog-form form").submit();
                            dlg.dialog("close");
                        };
                    }
                    dlg.dialog(config); 
                }; 
                $(document).on('click', 'span.delete', function () {
                    $(this).closest('tr').find('td').fadeOut(1000, function () {
                        $(this).parents('tr:first').remove();
                    }); 
                    return false;
                });
                $("a.edit").click(function () {
                    // populate the values; we're getting all the info from
                    // the data- attributes on the link itself
                    // note JS makes them all lowercase
                    $("#dialog-form input#memberID").val($(this).data("memberid"));
                    $("#dialog-form input#MFirst").val($(this).data("mfirst"));
                    $("#dialog-form input#MLast").val($(this).data("mlast"));
                    $("#dialog-form input#Street").val($(this).data("street"));
                    $("#dialog-form input#number").val($(this).data("number"));
                    $("#dialog-form input#postalCode").val($(this).data("postalcode"));
                    $("#dialog-form input#Mbirthdate").val($(this).data("mbirthdate"));
                    new_dialog('Edit');
                    return false;
                }); 
                $("a.delete").click(function() {
                    return confirm('Are you sure you want to delete?');
                });
                $("#create-user").button().click(function() {
                    // just clear the values
                    $("#dialog-form input").val("");
                    new_dialog();
                }); 
            });
        </script>
    </head>
    <body>
        <div class="navbar">
            <a href="mydatabase.php">Home</a>
            <a href="member_table.php">Member</a>
            <a href="book_table.php">Book</a>
            <a href="borrows_table.php">Borrows</a>
        </div>
        <br/><br/>
        <div class="navbar2">
            <a href="insert.php">Insert</a>
            <a href="update.php">Update</a>
            <a href="delete.php">Delete</a>
        </div>
    
        <table class="minimalistBlack">
            <thead>
                <tr>
                    <th> memberID </th>
                    <th> First Name </th>
                    <th> Last Name </th>
                    <th> Street </th>
                    <th> Number </th>
                    <th> Postal Code </th>
                    <th> Birthdate </th>
                    <th> Update </th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($data as $row):?>
                <tr>
                    <td><?=$row['memberID']?></td>
                    <td><?=$row['MFirst']?></td>
                    <td><?=$row['MLast']?></td>
                    <td><?=$row['Street']?></td>
                    <td><?=$row['number']?></td>
                    <td><?=$row['postalCode']?></td>
                    <td><?=$row['Mbirthdate']?></td>
                    <td>
                        <a
                            class ="edit"
                            href="#"
                            <?php foreach ($row as $k=>$v):?>
                            data-<?=$k?>="<?=$v?>"
                            <?php endforeach?>
                        >Edit</a> |
                        <a class="delete" href="deletefmtable.php?memberID=<?=$row['memberID']?>">Delete</a>
                    </td>
                </tr>
            <?php endforeach;?>
            </tbody>
        </table>
    
        <div id="dialog-form" title="Create new user" style="display:none">
            <p class="validateTips">
                All form fields are required.</p>
                <form method="post" action="edituple.php" target="_blank">
                    <fieldset>
                        <label for="memberID">Member ID </label>
                        <input type="text" name="memberID" id="memberID" value="" class="text ui-widget-content ui-corner-all" readonly="readonly" />
    
                        <label for="MFirst">First Name</label>
                        <input type="text" name="MFirst" id="MFirst" value="" class="text ui-widget-content ui-corner-all" />
    
                        <label for="MLast">Last Name </label>
                        <input type="text" name="MLast" id="MLast" value="" class="text ui-widget-content ui-corner-all" />
    
                        <label for="Street">Street </label>
                        <input type="text" name="Street" id="Street" value="" class="text ui-widget-content ui-corner-all" />
    
                        <label for="number">number </label>
                        <input type="text" name="number" id="number" value="" class="text ui-widget-content ui-corner-all" />
    
                        <label for="postalCode">Postal Code </label>
                        <input type="text" name="postalCode" id="postalCode" value="" class="text ui-widget-content ui-corner-all" />
    
                        <label for="Mbirthdate">Birthdate </label>
                        <input type="text" name="Mbirthdate" id="Mbirthdate" value="" class="text ui-widget-content ui-corner-all" />
                    </fieldset>
            </form>
        </div>
    
    </body>
    </html>
    

    All you'll need to do is allow for edituple.php to look at $_POST instead of $_GET. And don't forget to use prepared statements for database updates! I'd strongly recommend use of PDO or a higher-level database API. mysqli is very verbose, it was really designed to build database APIs, not be used directly.

    评论
    解决 无用
    打赏 举报
  • 查看更多回答(1条)

相关推荐 更多相似问题