douxiao0400 2015-11-17 04:29
浏览 74
已采纳

jquery / ajax使用用户输入作为条件运行php查询,然后显示没有页面刷新的查询结果

I've spent the last 24 hours trying to find an answer, and while there are similar questions, the answers seem to be either more complicated than my use-case (so I don't understand it), or I find low-quality questions/answers.

My title really says it all, except for my code, but to reiterate in full sentences: I know how to update mysql database fields with user input and php using jquery. Separately, I know how to retrieve php query results using ajax. What I can't figure out is how to do both these things at the same time: Use ajax to set user input as a parameter of a php query, then also pull the results of that query.

I thought it was going to be simple once I figured these things out separately, but I just don't understand .ajax() well enough at all, and that's why I'm here.

Here is my code:

User Input Page

<!DOCTYPE html>
<html lang="en">
 <head>
 <meta charset="utf-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <title>Pull from query</title>

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

 <style>

 #topRow {
     margin-top:40px;
     text-align:center;
 }
 </style>
 </head>
 <body>

 <div class="container contentContainer" id="topContainer">
 <div class="row">

     <div class="col-md-6 col-md-offset-3" id="topRow">
     <textarea class="form-control"></textarea>
     </div>

     <div class="row">
         <div class="col-md-6 col-md-offset-3" id="output" style="border:1px solid #000000;height:40px;margin-top:40px;text-align:center;">
         </div>
     </div>

 </div>
 </div>


  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

    <script>

    //  "keyup" RUNS FUNCTION EVERY TIME USER USES KEYBOARD
    $("textarea").keyup(function() {

        $('#output').html("loading...");

        var email = $('textarea').val();

        $.post("5Query.php", {email:$('textarea').val()} );

        // ACCESS QUERY RESULTS (HOPEFULLY!)
        $.ajax({                                      
            url: '5Query.php',
            dataType: 'json',
            success: function(data)
                {
                    var result = data
                    $('#output').html(result);
                }
    });

        })

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

PHP Query in separate file

<?php

  // SET DATABASE LINK AS A VARIABLE THAT CAN BE USED WHEN RUNNING QUERIES
  $link = mysqli_connect(...connection stuff...);

  if (mysqli_connect_error()) {
    die("Could not connect");
  }

  // SELECT all fields FROM databasename
  $query = "SELECT * FROM users WHERE email='".mysqli_real_escape_string($link, $_POST['email'])."'";

  // CREATE ARRAY CONTAINING ALL VALUES FOR ROW MATCHING QUERY CRITERIA
  $row = mysqli_fetch_array(mysqli_query($link, $query));
  $name = $row['name'];
  $error = 'I could not find that user name';

  //echo json_encode($row);

  if($row){
  echo json_encode($name);
  } else {
    echo json_encode($error);
  }


?>

As you can see, I tried using $.post() to set the query parameter, since that is the only way I know how, but it does return any results. When I hard-code a value into the php query that I know is in the mysql db table, rather than trying to post user input to the query, it correctly returns and displays the query result.

I'm hoping that some of you smart people can spot something obvious that a novice like me wouldn't see... I definitely feel like everything should take place within .ajax(), but I just don't know how to do it, and it's weirdly difficult to find the answer anywhere.

Please let me know how to improve my question, or where I might find an answer (although keep in mind that I'm a super-novice with ajax, so it's entirely possible that I may have seen an answer and just did not know what I was looking at).

  • 写回答

2条回答 默认 最新

  • dps43633 2015-11-17 04:33
    关注

    remove the $.post then change ajax like this

    $.ajax({
        url: '5Query.php',
        type: 'post',
        dataType: 'json',
        data: {
            email: $('textarea').val()
        },
        success: function(data) {
            var result = data
            $('#output').html(result);
        }
    });
    

    In php page you can access that variable like this $_POST['email']

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?