PHP和JS的多页环境 [英] PHP and JS in multi-page environment

查看:140
本文介绍了PHP和JS的多页环境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我提前这是一个有点长道歉。我一直在试图找出这一点对于没有成功一段时间,所以我想后,我的大多数code所以让人叹为观止帮助我能有更好的了解自己在做什么。有人建议,我在我的最后一个职位 - <一个href="http://stackoverflow.com/questions/26597112/cannot-get-js-to-be-called-upon-form-post/26597229">Cannot得到的.js被要求表单POST - 我创建一个新的线程

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

我有一个项目,所有的code的发生在单页,HTML,PHP,JavaScript和一串SQL查询。我想摆脱这种情况,使用单独的页面,并把AJAX这个,所以我可以更新数据库,这是中央的页面,无需刷新。

I had a project where all the code was taking place on a single page, html, php, javascript, and a bunch of SQL queries. 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.

我有两个主要的页面 - 的test.php getuser.php ,以及两个小钻头, update.php 和< STRONG> update.js

I have two main pages - test.php and getuser.php, as well as two smaller bits, update.php and update.js.

test.php的是我第一次加载页面。它分成两个&LT; D​​IV&GT; S,顶格,它包含一个SQL查询到我的数据库,选择一个用户,下面的DIV它,一旦选择从下拉菜单中选择一个用户,启动脚本showUser(),并发送一个Ajax请求getuser.php加载向下跌破页面的其余部分。

test.php is the page I load first. 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.

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

    <?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和up​​date.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
    });
});
});

<?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);
?>

问题

现在,我开始通过加载test.php的,并从下拉菜单中,其填充底部的页面上半叶从getuser.php生成的表中选择一个名称。这是我的问题开始。 在getuser.php页面上,我有3个按钮 - 在启动下一步按钮和提交按钮。该启动下一步按钮送我回到起点(因为如果我要从头开始加载test.php的)和更新按钮的作品,但它加载update.php不加载update.js,重定向到update.php并成功地处理它,(这是整个事情我试图避免使用多页的AJAX环境...)如果我加载getuser.php?Q =约翰%20Doe 本身,这些按钮都完全按照我设计他们。

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. This is where my issues start. On the getuser.php page, I have 3 buttons - the start and next buttons, and the submit button. 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.

我把这个code。在我的update.js文件的开头,因为我无论是在test.php的和getuser.php称之为:

I put this code in the beginning of my update.js file, since I call it both in test.php and in getuser.php:

$(document).ready(function(){ 

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

});

只是为了确保我的js文件加载正确。

just to make sure my .js file is loading properly.

如果加载页面正常,(test.php的),还有就是在我的页面的头球顶红色的小边框 - 所以update.js被调用,但它没有被呼吁getuser.php的加载后随着周围有该网页上的div没有一点红色的边框。如果我加载getuser.php直接,无需通过test.php的,边界在那里,一切工作正常。

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. If I load getuser.php directly without going through test.php, the borders are there, and everything works fine.

我一定是跳过了学习的一些部分,当我开始进入这一点,因为我不知道是怎么回事错了,还是我的一些code,只有当我直接加载页面,而不是内部的工作原理另一页。

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.

推荐答案

最大的问题是您正在加载到DOM不处理你已经包含JavaScript文件的HTML内容。所以,你应该使用jQuery的 .load()正常加载页面的AJAX调用的后面。这将加载包含JavaScript文件。

The big problem is the HTML content you're loading into the DOM does not process the JavaScript files you've included. So, you should use jQuery's .load() to properly load the page behind your AJAX call. This will load the included JavaScript files.

这整个街区:

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();
}

变成了:

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

这篇关于PHP和JS的多页环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆