开发者

I am trying to display 2 totals calculated in a php function using a mouseover event with Ajax. How do I do this?

This is for a school project. This is what I have so Far. I am totally new to this and totally lost. Would appreciate some help.

Ajaxfunctions.js

function getXMLHttp()
{
  var xmlHttp

  try
  {
    //Firefox, Opera 8.0+, Safari
    xmlHttp = new XMLHttpRequest();
  }
  catch(e)
  {
    //Internet Explorer
    try
    {
      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e)
    {
        try
            {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
        catch(e)
            {
                alert("Your browser does not support AJAX!")
                return false;
            }
        }
    }
    return xmlHttp;
}


 function MakeRequest(product)
{
  var xmlHttp = getXMLHttp();

  xmlHttp.onreadystatechange = function()
  {
    if(xmlHttp.readyState == 4){
        if(xmlHttp.status == 200){
      HandleResponse(xmlHttp.responseText);
    }
    }   
  }

  xmlHttp.open("GET", "prodTotal.php?product=+_product", true);
  xmlHttp.send(null);
}

function HandleResponse(response)
{
  document.getElementById('totalqty').innerHTML = response;
  document.getElementByID('totaldol').innerHTML = response;
}

This is the PHP Class with the PRODTOTAL function and the mouseover events in the table.

<?php 

Class CarsClass {
        private $user = 'php06'; 
        private $pwd = 'php06';  
        private $dbConn;

function __construct($db='classicmodels') {
        //Create connection to MySQL database requested, if blank just connect up.

        $this->dbConn = new mysqli('localhost', $this->user, $this->pwd, $db);
        if (mysqli_connect_errno()) {
            echo 'Error: Could not connect to database.  Please try again later.';
            exit;
         }
        $query = "select count(*) as 'custcount' from customers";

        $result = $this->dbConn->query($query);
        $row = $result->fetch_assoc();
        $custCount = $row['custcount'];

        print "Connected to DB $db as user $this->user<br><br> Number of Rows $custCount<br><br>";
    }

function __destruct(){
        mysqli_close();
        Print "DB closed by user <br><br>";
    }

function header(){
    echo "Midterm Exam Script 2 Header<br><br>";
    }

function display(){
    $totqty = 0;
    $totamt = 0;
    //get row from WB_Resident Table
    $query = "select productCode,productName,productDescription,quantityInStock,buyPrice,MSRP from products";
    $result = $this->dbConn->query($query);
?>  

<table id="midterm2">

    <tr>
       <th colspan="13">Product Database Table</th>
    </tr>
    <tr> 
       <th width="2%">product Code</th>
       <th width="10%">product Name</th>
       <th width="10%">product Description</th>
       <th width="10%">quantity in stock</th>
       <th width="10%">buy Price</th>
       <th width="2%">MSRP</th>
       <th width="10%">Total Quantity</th>
    </tr>   
    <tr> 
    <th></th> 
    <th></th>
    <th></th>
    <th></th&开发者_如何学JAVAgt;
    <th></th>
    <th></th>
    <th width="10%">Total Dollars</th>

    </tr>

    <?php 
     while($row = $result->fetch_assoc()):
     $producta = $row["productCode"];
     //list($totqty, $totamt) = $this->ProdTotal($producta); 

    ?>
    <tr>
      <td>
         <?php echo $row["productCode"]; ?>
         &nbsp;
      </td>
      <td>
        <?php echo $row["productName"];?>
        &nbsp;
        </td>
      <td>
         <?php echo $row["productDescription"]; ?>
         &nbsp;
      </td>
      <td>
         <?php echo $row["quantityInStock"]; ?>
         &nbsp;
      </td>
      <td>
         <?php echo $row["buyPrice"]; ?>
         &nbsp;
      </td>
      <td>
         <?php echo $row["MSRP"]; ?>
         &nbsp;
      </td>
      <td>
      <div id ="totalqty" onmouseover="MakeRequest($producta)"></div>
      &nbsp; 
      <div id ="totaldol" onmouseover="MakeRequest($producta)"></div>  
      &nbsp;  
      </td>       
      </tr>

      <?php 
      endwhile;
      ?>
      </table>
    <?php   
  }

function footer(){
    echo "Midterm Exam Script 3 Footer<br><br>";
    }

function ProdTotal($product){

     $query = "select RTRIM(productCode) as productt, quantityOrdered, priceEach from orderdetails order by productt";

        $result = $this->dbConn->query($query);

        while($row = $result->fetch_assoc()){
        if ($row["productt"] == $product){
        $total = $row["quantityOrdered"] * $row["priceEach"];   
        $totqty = $totqty + $row["quantityOrdered"];
        $totamt = $totamt + $total;
        }
        }
        return array($totqty, $totamt);
        }


        }    
    ?>

This calls the class.

<html>
<head>
<title>Midterm2 Script 4</title>
<link rel="stylesheet" type="text/css" href="midterm2.css" />
<script src="ajax_functions.js" type="text/javascript"></script>
</head>

<body>

<?php 
require 'CarsClass4.php';

$obj1= new CarsClass('classicmodels');

$obj1->header();
$obj1->display();
$obj1->footer();

?>

</body>
</html>


Right, you have a few minor errors, and a missing file.

I am going to answer you here on your original question, try not to post duplicates - if your question does not get answered there is probably a reason. In this case because it was very long, answerers tend to like you to find where the problem is, rather than having to wade through code. The other major issue is that this is obviously a mid-term, and most people do not like answering homework questions as it defeats the object of you doing them slightly, unless you phrase the question in a suggestion style. Anyhow, it's your first question here and I do not to put you off at all, so end of rant.


Right, firstly in your Javascript file Ajaxfunctions.js, your MakeRequest(product) function has an error in it. This line:

xmlHttp.open("GET", "prodTotal.php?product=+_product", true);

Should be:

xmlHttp.open("GET", "prodTotal.php?product=" + product, true);

You need to pass the variable back to the PHP script, before you were passing " _product" as the product ID, rather than the variable given.

Then in your main CarsClass.php file, you have the same error in a different language, passing a string rather than the actual variable in the display() method. Find the lines with the onmouseover bindings.

<td>
    <div id ="totalqty" onmouseover="MakeRequest($producta)"></div>
    &nbsp; 
    <div id ="totaldol" onmouseover="MakeRequest($producta)"></div>  
    &nbsp;  
</td>

The $producta here gets sent as the text "$producta", you need the variable and you are not in PHP mode, so you can not just simply mention it, you need to echo it out from PHP as has been done in previous table cells.

<td>
    <div id ="totalqty" onmouseover="MakeRequest(<?php echo $producta; ?>)"></div>
    &nbsp; 
    <div id ="totaldol" onmouseover="MakeRequest(<?php echo $producta; ?>)"></div>  
</td>

The last thing you need is the actual AJAX request file prodTotal.php (if this is the name of the last file you put in your question, then a slightly different approach should be taken).

prodTotal.php

<html>
<head>
    <title>Midterm2 AJAX Response File</title>
</head>
<body>

<?php 
require 'CarsClass4.php';

$product = (isset($_GET['product']) ? trim($_GET['product']) : '');

if (!empty($product)) {
    $classicModels = new CarsClass('classicmodels');

    list ($totqty, $totamt) = $classicModels->ProdTotal($product);
?>
    <div id ="totalqty"><?php echo $totqty; ?></div>
    <div id ="totaldol"><?php echo $totamt; ?></div>
<?php
}
?>

</body>
</html>

The AJAX request has to go off and get the values, see how the PHP file looks at the requested value, calls the function to calculate it and outputs DIVs matching the IDs your code in the Javascript HandleResponse() routine is looking for, containing the values. That JS routine takes out the content .innerHTML and replaces it in to the elements.

Note that AJAX routines take time, so the hover over is not going to be instant. There may be more errors in your code elsewhere, but this is the hard part dealt with.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜