以PHP JQUERY AJAX形式搜索和显示

时间:2017-05-18 12:39:56

标签: php jquery mysql ajax search

我试图在mysql数据库中搜索表单输入值,如果输入值存在于数据库中,那么我想以相同的形式显示匹配的输入行详细信息。请帮助我猜我在我的PHP代码中做错了什么。

由于

的index.php

  <div class="col-sm-6">
    <div class="form-group">
      <label for="campaignname">Link</label>
      <input type="text" class="form-control" id="link" name="link" placeholder="Link" required>
    </div>
  </div>

  <div class="col-sm-4">
    <div class="form-group">
      <label for="campaignname">First Name</label>
      <input type="text" class="form-control" id="suppfirstname" name="suppfirstname" placeholder="First Name" required>
     </div>
   </div>
   <div class="col-sm-4">
     <div class="form-group">
       <label for="campaignname">Last Name</label>
       <input type="text" class="form-control" id="supplastname" name="supplastname" placeholder="Last Name" required>
     </div>

调用Ajax的Jquery

<script>
 $(document).ready(function(){
      $('#link').change(function(){  
           var link = $(this).val();
           $.ajax({  
                url:"php_action/addnewlead/getlinkdata.php",  
                method:"POST",  
                data:{link:link},
                success:function(response){  
                            $("#suppfirstname").val(response.firstname);
                            $("#supplastname").val(response.lastname);
                }  
           });  
      });
 });
</script>

getlinkdata.php

<?php 

 $connect = mysqli_connect("localhost", "root", "", "test");  
 $output = '';
 if(isset($_POST["link"]))  
 {  
      if($_POST["link"] != '')
      {  
           $sql = "SELECT * FROM customertable WHERE link = '".$_POST["link"]."'";

      }  
      else
      {  
           $sql = "SELECT * FROM customertable WHERE link = 'jesusischrist'";
           // I dont want to load any data here so used wrong code

      }
      $result = mysqli_query($connect, $sql);  
      while($row = mysqli_fetch_array($result))  
      {  
           $output = $result;
      }  
      echo $output;
 }  

1 个答案:

答案 0 :(得分:0)

首先,正如有人提到你应该真正消毒你的意见,准备好的陈述也是一个很好的做法。我在这里稍微修改了你的原始代码,因为当你知道链接丢失时没有理由查询数据库。我认为你问题的一部分是你在最后回显你的输出,你不能回显数组元素(使用print_r或var_dump)。我将响应部分包装在JSON编码中,将其转换为Javascript可解析字符串,使您可以保持键/值结构的完整。

<?php 
try {
    if (isset($_POST['link'] && !empty($_POST['link']) {
        $mysqli = connect();

        // Sanitize your inputs. I'm guessing link is a string?
        $link = filter_var($_POST['link'], FILTER_SANITIZE_STRING);
        // create query string for prepared statement
        $sql = "SELECT firstname, lastname FROM customertable WHERE link = ? LIMIT 1";

        // prepare statement and bind variables
        $stmt = $mysqli->prepare($sql);
        $stmt->bind_param('s', $link);
        $stmt->execute();

        $result = $stmt->get_result();
        $row = $result->fetch_assoc();
        $stmt->close();

        sendResponse(200, $row);
    }
    sendResponse(400, ['status' => 'Link not supplied']);
} catch (\Exception $e) {
    sendResponse(500, ['status' => $e->getMessage()]);
}

/**
 * Sends JSON encoded response to client side with response http code.
 */
function sendResponse($code, $response)
{
    http_response_code($code);
    echo json_encode($response);
    exit();
}

/**
 * Handles connecting to mysql.
 *
 * @return object $connect instance of MySQLi class
 */
function connect()
{
    try {
        $connect = new \mysqli("localhost", "root", "", "test");
        return $connect;
    } catch (mysqli_sql_exception $e) {
        throw $e;
    }
}

更新你的javascript我可能会尝试这样的事情:

jQuery(document).ready(function($){
  $('#link').on('change', function(){  
    let link = $(this).val()
    ,   jqxhr = $.post(url:"php_action/addnewlead/getlinkdata.php", { link: link }); 

    jqxhr.done((response) => {
      $("#suppfirstname").val(response.firstname);
      $("#supplastname").val(response.lastname);
    });
    jqxhr.fail((error) => { throw new Error(`${error.status}: ${error.text}`)});
  });
});