简体   繁体   中英

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

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.

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

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.

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

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

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

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:

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

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.

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. So, you should use jQuery's .load() to properly load the page behind your AJAX call. This will load the included JavaScript files.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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