简体   繁体   English

多页面环境中的PHP和JS

[英]PHP and JS in multi-page environment

I apologize in advance for this being a bit long. 谨此致歉,敬请原谅。 I've been trying to figure this out for a while without success, so I wanted to post most of my code so the amazing people helping me could have better idea of what I was doing. 我一直试图弄清楚这一点没有成功,所以我想发布我的大多数代码,以便帮助我的出色人员可以更好地了解我的工作。 It was suggested to me in my last post - Cannot get .js to be called upon form POST - that I create a new thread 我在上一篇文章中建议我- 无法以POST形式调用.js ,我创建了一个新线程

I had a project where all the code was taking place on a single page, html, php, javascript, and a bunch of SQL queries. 我有一个项目,其中所有代码都在一个页面,html,php,javascript和一堆SQL查询中进行。 I am trying to move away from this, use separate pages, and incorporate AJAX into this so I can update the database, which is central to the page, without refreshing. 我试图摆脱这一点,使用单独的页面,并将AJAX合并到其中,以便我可以更新数据库(该页面的中心)而无需刷新。

I have two main pages - test.php and getuser.php , as well as two smaller bits, update.php and update.js . 我有两个主要的页面- test.php的getuser.php,以及两个小钻头,update.phpupdate.js。

test.php is the page I load first. test.php是我首先加载的页面。 It's split up into two <div> s, the top div, which contains a SQL query to my database to select a user, and the bottom div which, upon selection of a user from the dropdown menu, launches the script showUser(), and sends an AJAX request to getuser.php to load the rest of the page down below. 它分为两个<div> ,最上面的div包含对我的数据库的SQL查询以选择用户,最下面的div则在从下拉菜单中选择用户后启动脚本showUser(),并向getuser.php发送AJAX请求,以将页面的其余部分加载到下面。

test.php test.php的

<?php session_start(); ?>
<!doctype html>

<html>

  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <link rel="stylesheet" href="/bootstrapstyle.css">
    <link rel="stylesheet" href="/toastr.css">
    <script type="text/javascript" src="/toastr.js"></script>
    <script type="text/javascript" src="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
    <style type="text/css">
      body {
        padding-top: 50px;
        padding-bottom: 20px;
      }
    </style>
  <script type="text/javascript" src="/update.js"></script>

  <script>
    function showUser(str) {
      if (str !==".PM") {
        if (str=="") {
          document.getElementById("txtHint").innerHTML="";
          return;
        } 
        if (window.XMLHttpRequest) {
          // code for IE7+, Firefox, Chrome, Opera, Safari
          xmlhttp=new XMLHttpRequest();
        } else { // code for IE6, IE5
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function() {
          if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
          }
        }
      }
      xmlhttp.open("GET","getuser.php?q="+str,true);
      xmlhttp.send();
    }
</script>
</head>
<body>

<div class="navbar navbar-inverse navbar-fixed-top">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            <span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="home.php">HOME</a>
        </div>
        <div class="navbar-collapse collapse">
          <form>
          <ul class="nav navbar-nav">

            <li>
              <a>
                <?php
                include('./db.php');
                $PM = mysqli_query($con, "SELECT DISTINCT PMName FROM report WHERE PMname <> '' ORDER BY PMName ASC");
                ?>
                <span class="custom-dropdown custom-dropdown--red">
                <select class="navbar-inverse" placeholder="PM Name" name="PMName" onchange="showUser(this.value)">
                <?php
                while ($row = mysqli_fetch_row($PM)) {
                $selected = array_key_exists('PMName', $_POST) && $_POST['PMName'] == $row[0] ? ' selected' : '';
                printf(" <option value='%s' %s>%s</option>\n", $row[0], $selected, $row[0]);
                }
                ?>
                </select>
                </span>
              </a>
            </li>
          </ul>
          </form>
        </div>
      </div>
    </div>

<div id="txtHint"><b>Select a name from the dropdown menu above...</b></div>

</body>
</html>

getuser.php getuser.php

    <?php session_start(); ?>
    <!doctype html>
    <html>     
      <head>        
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <link rel="stylesheet" href="/bootstrapstyle.css">    
        <link rel="stylesheet" href="/toastr.css">    
        <script type="text/javascript" src="/toastr.js"></script>             
        <script type="text/javascript" src="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>     
        <style type="text/css">      body {         padding-top: 50px;         padding-bottom: 20px;       }     
        </style>  
        <script type="text/javascript" src="/update.js"></script>     
      </head>     
      <body>

    <?php
    $q = $_GET['q'];
    include('./db.php');
    $LimitStart = 0 ;
    $LimitItems = 10 ;
    //THIS IS THE SQL COMMAND THAT ACTUALLY GRABS THE CORRECT PM
    $sqlPM= "SELECT * FROM report WHERE PMName = '".$q."' and REGNSB <> 0.000 ORDER BY TrackNumber ASC Limit $LimitStart,$LimitItems";
    $result     = mysqli_query($con, $sqlPM);
    // THIS IS FOR THE PAGE COUNT TOTAL OF THAT SPECIFIC PM
    $sqlCommand = "SELECT COUNT(*) FROM report where PMName = '".$q."' AND REGNSB <> 0.000";
    $query = mysqli_query($con, $sqlCommand) or die(mysqli_error());
    $pages      = mysqli_fetch_row($query);
    $totalPages = round($pages[0] / 10);
    mysqli_free_result($query);

    if (isset($_POST['previous'])) {                  
        $postedLimit = (isset($_POST['previous']) ? (int) $_POST['previous'] : 0);
        $prevLimit = 1;
        $_SESSION['page'] = ((int) $nextLimit / 10)+1;
        $result = mysqli_query($con, "SELECT * FROM report WHERE PMName = '$PMSelection' AND REGNSB <> 0.000 ORDER BY TrackNumber ASC Limit $LimitStart,$LimitItems");
    }

    if (isset($_POST['next'])) {
            $postedLimit = (isset($_POST['next']) ? (int) $_POST['next'] : 0);
            $nextLimit = $postedLimit + 10;
              $_SESSION['page'] = ((int) $nextLimit / 10)+1;

            $result = mysqli_query($con, "SELECT * FROM report WHERE PMName = '$PMSelection' AND REGNSB <> 0.000 ORDER BY TrackNumber ASC, RegNSB DESC Limit $nextLimit,$LimitItems");
        }

    if (isset($_SESSION['page'])) {
    } else {
    $_SESSION['page'] = 1 ;
    }        
    ?>

    <!-- MAIN JUMBOTRON THAT LISTS THE TITLE OF THE PAGE AS WELL AS THE PAGE 1 OF X THING... -->
    <div class="jumbotron">
    <div class="container">
      <h1 class="pull-left">DW1 Invoice-Backlog Report</h1>
      <h2 class="pull-right"><?= $q ?></h2>
    </div>
    <div class="container">
        <div class="test">
            <div class="inner">
                <form method="POST" action="">
                Page&nbsp;<?= $_SESSION['page'] ?>&nbsp;of&nbsp;<?= $totalPages ?>&nbsp;&nbsp;:&nbsp;&nbsp; 
                <input class="button" type="submit" name="previous" value="START" onclick="this.value=<?php echo $prevLimit; ?>">  
                <input class="button" type="submit" name="next" value="NEXT" onclick="this.value=<?php echo $nextLimit; ?>"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                </form>
            </div>
        </div>
    </div>      
    <div class="container pull-right">                         
    </div>
    </div>

    <div class="container">
    <div class="row">
      <div class="col-xs-6 col-sm-3 col-lg-12">       
        <form id="updateChanges" method="POST" action="update.php">
          <div class="container pull-right">
            <h2 class="pull-left">
              <input class="button" name="update"<?= $LineID ?>" type="submit" id="update" value="UPDATE">            
            </h2>
          </div>

    <div id="tableRefresh">
    <table id="box-table-a">  
<tr>
<th>
 ..all my headers..........
</th>
</tr>
<?php
while ($row = mysqli_fetch_array($result)) {

    $LineID             = $row['LineID'];
    $trackNumber        = $row['TrackNumber'];
    $PMName             = $row['PMName'];
    $RegNSB             = number_format($row['RegNSB'], 0);
    $TrackCount         = $row['TrackCount'];
    $TrackNSB           = number_format($row['TrackNSB'], 0);
    $TotalBacklog       = number_format($row['TotalBacklog'], 0);
    $AverageBacklog     = number_format($row['AverageBacklogTrackMargin'] * 100, 2);
    $RGPPercent         = number_format($row['RGPPercent'] * 100, 2);
    $PMComments         = $row['PMComments'];
    $PMMRecommendations = $row['PMMRecommendations'];
    $Outcome            = $row['Outcome'];
    $NewGPPercent       = $row['NewGPPercent'];
    $AdditionalGP       = $row['AdditionalGP'];
    $PMM                = $row['PMM'];
    $NEDA               = $row['NEDA'];
    $InvoiceNumber      = $row['InvoiceNumber'];
    $InvCustEB          = $row['InvCustEB'];

      ?>

<tr>
<td>
....all my rows...
</td>
</tr>
<?php
}
?>

update.js and update.php files: update.js和update.php文件:

$(function() {

    // Get the form.
    var form = $('#updateChanges');

    // Set up an event listener for the contact form.
    form.submit(function(event) {

    // Stop the browser from submitting the form.
    event.preventDefault();

    // Serialize the form data.
    var formData = form.serialize();

    // Submit the form using AJAX.
    $.ajax({
        type: 'POST',
        url: form.attr('action'),
        data: formData
    });
});
});

and

<?php

include('./db.php');

$data       = array();    //array to pass back the sum of PM Comments, PM Recs, Outcomes... etc....

for ($n = 0, $t = count($_POST['PMComments']); $n < $t; $n++) {
    $UpdateValue             = $_POST['Update'][$n];
    $PMCommentsValue         = $_POST['PMComments'][$n];
    $PMMRecommendationsValue = $_POST['PMMRecommendations'][$n];
    $OutcomeValue            = $_POST['Outcome'][$n];
    $NewGPPercentValue       = $_POST['NewGPPercent'][$n];
    $AdditionalGPValue       = $_POST['AdditionalGP'][$n];
    $LineID                  = $_POST['LineID'][$n];

    $sqlUPDATE = "UPDATE report SET PMComments = '$PMCommentsValue' , PMMRecommendations = '$PMMRecommendationsValue' , Outcome = '$OutcomeValue' , NewGPPercent = '$NewGPPercentValue', AdditionalGP = '$AdditionalGPValue'  WHERE LineID = $LineID ;";
?>
<div id="alerts">
<?php    
    echo $sqlUPDATE . "<br>";  //this echos back the entire SQL entry that will be made
?>
</div>
<?php    
    $doUPDATE = mysqli_query($con, $sqlUPDATE);
    if (!$doUPDATE) {
        die('Could not update data: ' . mysqli_error($con));
    }

    if ($OutcomeValue <> 'null') {                  

      $sqlMOVE  = "INSERT INTO results SELECT * FROM report WHERE LineID = $LineID ;" ;
      $sqlDELETE = "DELETE FROM report where LineID = $LineID ;" ;
      $doMOVE = mysqli_query($con, $sqlMOVE);
      if (!$doMOVE) 
        {
          die('Could not MOVE data: ' . mysqli_error($con));
        }
      $doDELETE = mysqli_query($con, $sqlDELETE);
      if (!$doDELETE) 
        {
          die('Could not DELETE data: ' . mysqli_error($con));
        } 
    }
}  

mysqli_close($con);
?>

The Issue 问题

Right now, I start by loading test.php and selecting a name from the dropdown menu, which populates the bottom half of the page with the table generated from getuser.php. 现在,我首先加载test.php并从下拉菜单中选择一个名称,该菜单将用getuser.php生成的表填充页面的下半部分。 This is where my issues start. 这是我的问题开始的地方。 On the getuser.php page, I have 3 buttons - the start and next buttons, and the submit button. 在getuser.php页面上,我有3个按钮- startnext按钮,以及submit按钮。 The start and next buttons send me back to the start (as if I were to load test.php from scratch), and the update button WORKS, but it loads update.php without loading update.js, redirecting to update.php and processing it successfully, (which is the whole thing I'm trying to avoid by utilizing a multi-page AJAX environment...) If I load up getuser.php?q=John%20Doe by itself, these buttons all work exactly as I designed them. start和“ next按钮将我带回到开始位置(就像我要从头开始加载test.php一样),而update按钮是“工作”,但它在不加载update.js的情况下加载了update.php,并重定向到update.php并进行了处理它成功完成了(这是我试图通过使用多页AJAX环境避免的全部事情...) 如果我自己加载getuser.php?q = John%20Doe ,那么这些按钮的工作方式与我完全一样设计他们。

What I've tried 我尝试过的

I put this code in the beginning of my update.js file, since I call it both in test.php and in getuser.php: 我将此代码放在update.js文件的开头,因为我在test.php和getuser.php中都将其称为:

$(document).ready(function(){ 

    $("div").css("border", "3px solid red");
  console.log("update.js loaded successfully");

});

just to make sure my .js file is loading properly. 只是为了确保我的.js文件正确加载。

If load the page normally, (test.php), there is a small red border around the top header of my page - so update.js is being called, but it's not being called on the getuser.php that loads after that as there are no little red borders around the divs on that page. 如果正常加载页面(test.php),则页面顶部的标题周围会出现一个红色小边框-因此会调用update.js,但不会在随后加载的getuser.php上调用它。该页面上的div周围没有红色边框。 If I load getuser.php directly without going through test.php, the borders are there, and everything works fine. 如果我直接加载getuser.php而不通过test.php,那么边界就在那里,并且一切正常。

I must have skipped over some section of learning when I started getting into this, because I have no idea what is going wrong, or some of my code only works when I load the page directly and not "inside" of another page. 开始学习该课程时,我肯定已经跳过了一部分学习,因为我不知道出了什么问题,或者我的某些代码仅在我直接加载该页面而不是在另一个页面“内部”时才有效。

The big problem is the HTML content you're loading into the DOM does not process the JavaScript files you've included. 最大的问题是,您加载到DOM中的HTML内容无法处理包含的JavaScript文件。 So, you should use jQuery's .load() to properly load the page behind your AJAX call. 因此,您应该使用jQuery的.load()来正确加载AJAX调用后面的页面。 This will load the included JavaScript files. 这将加载包含的JavaScript文件。

This entire block: 这整个块:

function showUser(str) {
  if (str !==".PM") {
    if (str=="") {
      document.getElementById("txtHint").innerHTML="";
      return;
    } 
    if (window.XMLHttpRequest) {
      // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
    } else { // code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4 && xmlhttp.status==200) {
        document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
      }
    }
  }
  xmlhttp.open("GET","getuser.php?q="+str,true);
  xmlhttp.send();
}

becomes: 变为:

function showUser(str) {
  if (str !==".PM") {
    if (str=="") {
      document.getElementById("txtHint").innerHTML="";
      return;
    } 
  }
  $("#txtHint").load( "getuser.php?q="+str );
}

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

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