AJAX和PHP存在问题

时间:2017-06-05 22:03:58

标签: php jquery ajax mysqli

我很擅长编码,如果这是一个愚蠢的问题,那就很抱歉。我想知道我是做错了什么,或者是否有更好的方法可以解决我的问题。我使用AJAX向php处理程序提交信息,然后基本上用更新的信息替换我页面上的数据,这样页面就不必每次刷新。

这是我的AJAX代码。

<script>
     $(document).ready(function(){
         $("#start<?php echo $rowCount; ?>").click(function(){
                        $("#displayJobs").load("assemblyStartHandlerCopy.php", {
                            jobID: <?php echo $jobID; ?>,
                            roomID: <?php echo $roomID; ?>,
                            finishColor: '<?php echo $finishColor; ?>',
                            startTime: '<?php echo $assemblyS; ?>'
                        });
                        $("#displayJobsNotStarted").load("assemblyNotStartedCount.php");
                    });
                });
</script>

我的PHP代码是

<?php include "../../../includes/db.php"; ?>
<?php
    $startBtnColor = "";
    $completeBtnColor = "";
    $onQlistStatus = "On Q-List";
?>

<!--IF START BUTTON UPDATE DATA-->
<?php
date_default_timezone_set("America/Denver");
if(isset($_POST['jobID'])) {
    $jobID = $_POST['jobID'];
    $roomID = $_POST['roomID'];
    $finishColor = $_POST['finishColor'];
    $startTime = $_POST['startTime'];
    $start = date("Y-m-d H:i:s");

    if($startTime == NULL || $startTime == 0) {
        $startTime = $start;
    }
    elseif($startTime != NULL || $startTime == 0) {
        $startTime = 0;
    };

$querySetStart = "UPDATE rooms SET assemblyS = '$startTime' WHERE jobID = $jobID AND finishColor = '$finishColor'";
$resultSetStart = mysqli_query($connect, $querySetStart);

if(!$resultSetStart) {
    echo "Start Button Failed " . mysqli_error($connect);
};
?>

<!--GET AND DISPLAY JOBS-->
    <table>
            <tr>
                <th class="rowStart">Start</th>
                <th class="rowJobName">Job Name</th>
                <th class="rowWoodType">Wood Type</th>
                <th class="rowFinishColor">Finish Color</th>
                <th class="rowComplete">Complete</th>
            </tr>
<?php 
    $query = "SELECT 
        jobs.jobID,
        jobs.jobName, 
        rooms.roomID, 
        rooms.roomName, 
        rooms.assemblyS,
        rooms.assemblyF,
        rooms.assemblyNeeded,
        rooms.woodType,
        rooms.finishType,
        rooms.finishColor
        FROM jobs 
        LEFT JOIN rooms 
        ON jobs.jobID = rooms.jobID 
        WHERE rooms.assemblyNeeded = 1 AND jobs.status = '$onQlistStatus' AND rooms.assemblyF IS NULL
        OR rooms.assemblyNeeded = 1 AND jobs.status = '$onQlistStatus' AND rooms.assemblyF = 0
        GROUP BY jobs.jobName, rooms.finishColor 
        ORDER BY deliveryDate, jobName, finishColor LIMIT 100";

    $result = mysqli_query($connect, $query);

    $x = 1;
    $rowCount = 1;

    if ($result) {
    while($row = mysqli_fetch_assoc($result)) {
        $jobID = $row['jobID'];
        $jobName = $row['jobName'];
        $woodType = $row['woodType'];
        $finishColor = $row['finishColor'];
        $roomID = $row['roomID'];
        $assemblyS = $row['assemblyS'];
        $assemblyF = $row['assemblyF'];
//SET BUTTON BACKGROUND COLOR
        if ($assemblyS != NULL) {
            $startBtnColor = "green";   
        };
        if ($assemblyS == NULL || $assemblyS == 0) {
            $startBtnColor = "white";
        };
//ALTERNATE ROW COLOR
        $x++;
        if ($x%2 == 0) {
            $class1 = "backgroundColor1";
        }
        else {
            $class1 = "backgroundColor2";
        };
//DISPLAY ROW INFORMATION
        $start = "<td class='rowStart'><button id='start$rowCount' style='background-color: $startBtnColor'>Start</button></td>";
        ?>
            <script>
                $(document).ready(function(){
                    $("#start<?php echo $rowCount; ?>").click(function(){
                        $("#displayJobs").load("assemblyStartHandlerCopy.php", {
                            jobID: <?php echo $jobID; ?>,
                            roomID: <?php echo $roomID; ?>,
                            finishColor: '<?php echo $finishColor; ?>',
                            startTime: '<?php echo $assemblyS; ?>'
                        });
                        $("#displayJobsNotStarted").load("assemblyNotStartedCount.php");
                    });
                });
            </script>
        <?php
        $jobName = "<td class='$class1 rowJobName'>$jobName</td>";
        $woodType = "<td class='$class1 rowWoodType'>$woodType</td>";
        $finishColorRow = "<td class='$class1 rowFinishColor'>$finishColor</td>"; 

        $complete = "<td class='rowComplete'><button id='complete$rowCount' style='background-color: $completeBtnColor'>Complete</button></td>";
            ?>
            <script>
                $(document).ready(function() {
                    $("#complete<?php echo $rowCount; ?>").click(function() {
                        $("#displayJobs").load("assemblyCompleteHandlerCopy.php", {
                            jobID: <?php echo $jobID; ?>,
                            roomID: <?php echo $roomID; ?>,
                            finishColor: '<?php echo $finishColor; ?>',
                            completeTime: '<?php echo $assemblyS; ?>'
                        }, function(responseTxt, statusTxt, xhr) {
                            if(statusTxt == "success") {
                            //DO NOTHING    
                            };
                            if(statusTxt == "error") {
                                alert("Error: " + xhr.status + ": " + xhr.statusText);
                            };
                        });

                    $("#displayJobsNotStarted").load("assemblyNotStartedCount.php");
                    $("#recentlyCompleted").load("assemblyRecentlyCompletedHandler.php", {
                        complete: 1
                    }, function(responseTxt, statusTxt, xhr) {
                            if(statusTxt == "success") {
                            //DO NOTHING    
                            };
                            if(statusTxt == "error") {
                                alert("Error: " + xhr.status + ": " + xhr.statusText);
                            };
                        });
                    });
                });
            </script>
            <?php
        echo "<tr>" . $start . $jobName . $woodType . $finishColorRow . $complete . "</tr>";
        $rowCount++;
    };
    };  
?>
            </table>
<?php
}
?>

我知道它非常混乱。基本上所有信息都被拉入表中并通过while循环回显行。然后,如果我选择一个与&#34;作业相关的按钮&#34;或&#34;行&#34;它标志着一个开始时间,第二个标志着颜色,第三个给了我一个新的计数。 有没有更好的方法来做到这一点,或者确保我的代码不会被激发,除非它成功。

对我来说奇怪的是我的代码在PHP处理程序中重复。如果我刷新页面,每次都会正常显示,没有任何问题。

2 个答案:

答案 0 :(得分:1)

正如所建议的,我将创建一个可以与AJAX一起使用的独立PHP脚本。这可能看起来像:

<强> PHP

 <root>
     <bp>
            <id>999</id>
            <comp>123</role>
            <role>FL01</role>
             <role>FL00</role>
        </bp>
    <bp>
            <id>999</id>
            <comp>456</role>
            <role>FL01</role>
             <role>FL02</role>
        </bp>
    <bp>
            <id>888</id>
            <comp>123</role>
            <role>FL01</role>
             <role>FL00</role>
        </bp>
    <bp>
            <id>888</id>
            <comp>456</role>
            <role>FL01</role>
             <role>FL02</role>
        </bp>
    </root>

如果您<?php include "../../../includes/db.php"; $startBtnColor = ""; $completeBtnColor = ""; $onQlistStatus = "On Q-List"; date_default_timezone_set("America/Denver"); if(isset($_POST['jobID'])) { $jobID = $_POST['jobID']; $roomID = $_POST['roomID']; $finishColor = $_POST['finishColor']; $startTime = $_POST['startTime']; $start = date("Y-m-d H:i:s"); if($startTime == NULL || $startTime == 0) { $startTime = $start; } elseif($startTime != NULL || $startTime == 0) { $startTime = 0; } if($stmt = $connection->prepare("UPDATE rooms SET assemblyS = '?' WHERE jobID = ? AND finishColor = '?'")){ $stmt->bind_param("sis", $startTime, $jobID, $finishColor); if($stmt->execute()){ $stmt->close(); echo "Update Start Button Failed " . mysqli_error($connect); $connection->close(); die(); } } $connection->close(); die(); } $query = $connection->prepare("SELECT jobs.jobID, jobs.jobName, rooms.roomID, rooms.roomName, rooms.assemblyS, rooms.assemblyF, rooms.assemblyNeeded, rooms.woodType, rooms.finishType, rooms.finishColor FROM jobs LEFT JOIN rooms ON jobs.jobID = rooms.jobID WHERE rooms.assemblyNeeded = 1 AND jobs.status = '?' AND rooms.assemblyF IS NULL OR rooms.assemblyNeeded = 1 AND jobs.status = '?' AND rooms.assemblyF = 0 GROUP BY jobs.jobName, rooms.finishColor ORDER BY deliveryDate, jobName, finishColor LIMIT 100"); if($query){ $query->bind_param("ss",$onQlistStatus,$onQlistStatus); $query->execute(); $query->bind_result($result); $x = 1; $rowCount = 1; $results = array(); if ($result) { while($row = mysqli_fetch_assoc($result)) { $results[] = array( 'jobID' => $row['jobID'], 'jobName' => $row['jobName'], 'woodType' => $row['woodType'], 'finishColor' => $row['finishColor'], 'roomID' => $row['roomID'], 'assemblyS' => $row['assemblyS'], 'assemblyF' => $row['assemblyF'], //SET BUTTON BACKGROUND COLOR 'assemblyS' => ($startBtnColor != NULL) ? "green" : "white", //ALTERNATE ROW COLOR 'class1' => (!$x++%2) ? "backgroundColor1" : "backgroundColor2" ); $rowCount++; } } $query->close(); } $connection->close(); header('Content-Type: application/json'); echo json_encode($results); ?> ,它将更新数据库。如果您对此运行POST,您将获得JSON数据。

这允许您将所有JavaScript保存在HTML中。这使得解决问题变得更加容易。它还允许您随时调用数据。只需使用GET来提取数据。

MySQLi提供prepare我强烈建议使用。这将有助于再次保护SQL注入尝试。您当前的代码很容易受到这些攻击。

您的数据将以对象数组的形式返回。类似于:

$.getJSON()

我建议使用[{ 'jobID': 1, 'jobName': "job1", 'woodType': "hardwood", 'finishColor': "cherry", 'roomID': "room1", 'assemblyS': "2017-06-30 09:00:00", 'assemblyF': "2017-06-30 16:00:00", 'startBtnColor': "green", 'class1': "backgroundColor1" }, { 'jobID': 2, 'jobName': "job1", 'woodType': "hardwood", 'finishColor': "cherry", 'roomID': "room2", 'assemblyS': "2017-07-01 09:00:00", 'assemblyF': "2017-07-01 16:00:00", 'startBtnColor': "green", 'class1': "backgroundColor2" }, { 'jobID': 3, 'jobName': "job1", 'woodType': "hardwood", 'finishColor': "cherry", 'roomID': "room3", 'assemblyS': "2017-07-02 09:00:00", 'assemblyF': "2017-07-02 16:00:00", 'startBtnColor': "green", 'class1': "backgroundColor1" }]; 来迭代数据。你可以像这样建立你的桌子:

https://jsfiddle.net/Twisty/wkt9jnrq/

<强> HTML

$.each()

<强>的JavaScript

<table id="startJobs">
  <thead>
    <tr>
      <th class="rowStart">Start</th>
      <th class="rowJobName">Job Name</th>
      <th class="rowWoodType">Wood Type</th>
      <th class="rowFinishColor">Finish Color</th>
      <th class="rowComplete">Complete</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

您可以在 $.each(myData, function(k, o) { var btn = $("<button>", { id: "start-" + o.jobID }) .css("background-color", o.startBtnColor) .html("Start") .click(function(e) { $.post("assemblyStartHandlerCopy.php", { jobID: o.jobID, roomID: o.roomID, finishColor: o.finishColor, startTime: o.assemblyS }, function(result) { if (result.length) { alert(result); } }); }); var row = $("<tr>").appendTo("#startJobs tbody"); row.append($("<td>", { class: "rowStart " + o.class1 }).append(btn), $("<td>", { class: "rowJobName " + o.class1 }).html(o.jobName), $("<td>", { class: "rowWoodType " + o.class1 }).html(o.woodType), $("<td>", { class: "rowFinishColor " + o.class1 }).html(o.finishColor), $("<td>", { class: "rowComplete " + o.class1 }).html(o.assemblyF)); }); 的{​​{1}}回调中提取$.each()

答案 1 :(得分:0)

在这段代码中你可以改进很多东西。

首先,你不应该直接从PHP编写值到JavaScript,你应该将它们存储在变量中,并为JavaScript设置单独的文件,而是使用这些变量。

其次,您应该在将值写入数据库之前转义值,以避免使用addslashes方法进行SQL注入。

您现在正在做的是将所有代码写在一个文件中,这使得代码难以理解。组织您的代码并使用方法/函数将其划分为可管理的块,并在需要时使用单独的文件。