简体   繁体   English

使用ajax时无法使用的数据库功能

[英]Working database function doesn't work when using ajax

I have a function that pulls information from a mysql database. 我有一个从mysql数据库中提取信息的功能。 The function has been tested and works when calling it from a regular html form submit button. 从常规html表单提交按钮调用该函数时,该函数已经过测试并可以工作。 However, I have been trying to implement ajax, and I call the exact same function, but it isn't working, and I have no idea why. 但是,我一直在尝试实现Ajax,我调用了完全相同的函数,但是它不起作用,我也不知道为什么。

Here is the database function. 这是数据库功能。 I have removed unnecessary code to make it more readable. 我删除了不必要的代码以使其更具可读性。

function itemUPCsearch($upc)
    {
        $conn = localConnection();
        $query = "SELECT Items.UPC, availability, description, price, brand, perqty, item_type, unit_type, size, discount, serv_per_cal, calories, calories_from_fat, total_fat, saturated_fat, trans_fat, cholesterol, sodium, total_carbohydrate, dietary_fiber, sugars, protein, vitamins, ingredients, full_image_path FROM Items LEFT JOIN Nutrition ON Items.UPC = Nutrition.UPC LEFT JOIN item_pic P ON P.UPC = Items.UPC WHERE Items.UPC = ?";
        $stmt = mysqli_prepare($conn, $query);
        mysqli_stmt_bind_param($stmt, "s", $upc);
        mysqli_stmt_execute($stmt);
        mysqli_stmt_bind_result($stmt, $upc, $avail, $desc, $price, $brand, $perqty, $itype, $utype, $size, $discount, $servpercal, $cal, $calfromfat, $totfat, $satfat, $tranfat, $chol, $sod, $totcarb, $dietfib, $sugar, $prot, $vit, $ing, $image);



        while(mysqli_stmt_fetch($stmt))
        {

                // Execution never makes it inside this loop
                // Do stuff here (Code has been removed as it is not relevant
                // To this question)

        }
        mysqli_stmt_close($stmt);
        closeConnection($conn);

        return $searchItems;
    }

As far as I can tell, everything seems to be ok. 据我所知,一切似乎都还可以。 I have done a print_r on $conn and $stmt, and I get back what I would expect. 我在$ conn和$ stmt上完成了一个print_r,我得到了我期望的结果。 I compared these with the print_r of those objects on working functions and I get back the same results. 我将它们与工作功能上这些对象的print_r进行了比较,并得到了相同的结果。 I have printed the result of the execute function and it is returning true. 我已经打印了execute函数的结果,并且返回true。 The query never changed from when it worked with the regular form submit. 从使用常规表单提交开始,该查询就从未改变过。 The value $upc that was passed in is correct, and there is an entry for this in the database. 传入的值$ upc是正确的,并且数据库中对此有一个条目。 In fact, when I copy and paste the query with the upc value into mysql, I get back the correct result. 实际上,当我将带有upc值的查询复制并粘贴到mysql中时,会得到正确的结果。 For some reason though, the function never makes it inside the while loop, even though it makes it there when calling this same function using a form post while passing in the same upc. 但是由于某种原因,该函数永远不会将其置于while循环内,即使在传递相同的upc时使用表单发布调用此函数时,也不会使其进入while循环。

Here is my ajax script: 这是我的ajax脚本:

function loadCart(itemID,cart) {
  var httpRequest;
  makeRequest(itemID,cart);

  function makeRequest(itemID,cart) {
    if (window.XMLHttpRequest) { // Mozilla, Safari, ...
      httpRequest = new XMLHttpRequest();
    } else if (window.ActiveXObject) { // IE
      try {
        httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
      } 
      catch (e) {
        try {
          httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } 
        catch (e) {}
      }
    }

    if (!httpRequest) {
      alert('Giving up :( Cannot create an XMLHTTP instance');
      return false;
    }

    httpRequest.onreadystatechange = fillTheCart;
    httpRequest.open('GET', "../controller/addToCartAjaxScript.php?upc="+itemID+"&cart="+cart,true);
    httpRequest.send();
  }

  function fillTheCart() {
      try {
        if (httpRequest.readyState === 4) {
          if (httpRequest.status === 200) {
            document.getElementById("cartView").innerHTML=httpRequest.responseText;
          } 
          else {
            alert('There was a problem with the request.');
          }
        }
      }
      catch( e ) {
         alert('Caught Exception: ' + e.description);
      }
  }
}

And here is the script that the ajax calls: 这是ajax调用的脚本:

<?php

    //include_once '../databaseFunctions/session.php';
    include_once '../databaseFunctions/databaseConnection.php';
    include_once '../databaseFunctions/databaseFunctions.php';
    include_once '../controller/TableControllerHeader.php';
    include_once '../controller/ShoppingCartControllerHeader.php';
    include_once '../controller/UserControllerHeader.php';
    include_once '../controller/functions.php';

    $upc = intval($_GET['upc']);
    $cartName = $_GET['cart'];

    $cart = new Cart();
    $customer = new Customer();

    print $upc;

    if($upc != ""){
        $cart = addToCart($upc,$cartName);
    }
    else{
        if(isset($_SESSION['customer'])){
            $customer = unserialize($_SESSION['customer']);
            $cart = $customer->FindCart($cartName);
            if($cart = null){
                $cart = new Cart();
            }
        }
    }

    print $cart->PrintCart();

?>

I know that the ajax is working, because the print $cart->PrintCart(); 我知道ajax在工作,因为打印$ cart-> PrintCart(); at the end of the script called by ajax is printing what it is supposed to and it is placed in the element with the id "cartView", it just isn't including any data that was supposed to be pulled from the database function. 在由ajax调用的脚本结尾处,将打印其预期内容,并将其放置在ID为“ cartView”的元素中,它只是不包含任何应该从数据库函数中提取的数据。

The localConnection(); localConnection(); function that is called in the itemUPCsearch function is located in the databaseConnection.php script that was included at the beginning of the script that the ajax calls. 在itemUPCsearch函数中调用的函数位于ajax调用的脚本开头所包含的databaseConnection.php脚本中。 I am calling that script in my main script as well, but I don't think this is a problem. 我也在主脚本中调用了该脚本,但是我认为这不是问题。 I don't get any conflict errors, and if I take out the include statement, it gives an error that it can't find the localConnection() function. 我没有任何冲突错误,并且如果我删除了include语句,它会给出一个错误,即找不到localConnection()函数。

I don't understand what is wrong considering everything in the function appears correct. 考虑到函数中的所有内容都正确,我不明白这是什么问题。 Any help would be greatly appreciated! 任何帮助将不胜感激!

Edit 编辑

I have printed mysql_error() after each function call in the database function and got no error message after any of them. 我在数据库函数中的每个函数调用之后都打印了mysql_error(),但在任何一个函数之后都没有错误消息。

Ok, I finally figured out the problem. 好的,我终于解决了问题。 In the script that the ajax called, I was calling intval($_GET['upc']). 在ajax调用的脚本中,我正在调用intval($ _ GET ['upc'])。 The intval function was the problem. intval函数是问题所在。 Changing it to $upc = $_GET['upc'] fixed the problem. 将其更改为$ upc = $ _GET ['upc']可解决此问题。

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

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