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 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图