dongyong6332 2016-10-26 09:54
浏览 64
已采纳

使用ajax从Javascript函数调用Php函数

Hello everyone I am new to php. I have been trying out this thing when a user enter a product name need to validate that the product is valid or not. For that purpose I have used onchange event when the text is entered.The onchange function will call the javascript function.From javascript function I am calling the php which is in the same file.So when I am entering the product name somehow the php function is not working.

Here is my code :

<?php
  include 'conf.php';//it contains the php database configuration
   session_start();

   $quantityRequired=0; 
   $productName_error="";
    if(is_ajax()){
      if(isset($_POST["productName"])){
        $productName=$_POST["productName"];
        $row=mysqli_query($conn,"SELECT * from OrderDetails where ProductName='".$productName."'");
        if($row)
        {
          $result=mysqli_fetch_assoc($row);
          $quantityRequired=$result["Quantity"];
        }   
        else
         {
          $productName_error="The product name is not valid or product does not exist";
          echo $productName_error;
         }  
      }
    } 
  function is_ajax() {
    $flag=(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'); 
    return $flag;
  }
?>
<html>
   <head>
       <title>Order Page </title>
       <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
   </head>
   <body>
      <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
         <label for="userName">Username</label><br>
         Product Name<input type="text" name="productName" id="productName" onchange="validateProduct()"><?php echo $productName_error?><br>
         Quantity Required<input type="text" name="quantityRequired" id="quantityRequired"><br>
         Availability<input type="text" name="availability">
         <p id="demo"></p>
      </form>
      <script>
        function validateProduct()
        {
            $.ajax({
             type: "POST"
         });

        }
      </script>
   </body>  
</html> 

so the code is when the user enters the product name.The function validate product is called.From validate product it will call the php which is in the same file. is_ajax() function is used to check whether it is the ajax request or not.

  • 写回答

3条回答 默认 最新

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 python对txt文件的处理
      • ¥25 需要一个能在H5中实现扫码的插件
      • ¥50 ArcGIS或MATLAB实现批量计算整个tif图像的EVI
      • ¥20 两个板子之间CAN通信ID号怎么设置
      • ¥15 两个板子CAN通信的话ID号怎么设置
      • ¥15 vue使用element-ui的el-upload上传图片至服务器,服务端使用的是node.js,图片上传成功,但界面显示不出来,是跨域问题?
      • ¥15 ANSYS APDL循环结果输出
      • ¥15 ArcGIS处理MODIS 09数据,计算EVI 像元值大小问题
      • ¥15 Python库一直装不好
      • ¥30 在linux上调用海康SDK没有进入函数内