简体   繁体   English

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

[英]jquery / ajax to run php query using user input as criteria, then display query result without page refresh

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. 我花了最后24个小时来寻找答案,尽管有类似的问题,但答案似乎比用例更复杂(因此我不理解),或者发现质量很低问题和答案。

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. 除了我的代码外,我的标题确实说明了所有内容,但要用完整的句子重申:我知道如何使用jquery使用用户输入和ph​​p更新mysql数据库字段。 Separately, I know how to retrieve php query results using ajax. 另外,我知道如何使用ajax检索php查询结果。 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. 我不知道如何同时完成这两项操作: 使用ajax将用户输入设置为php查询的参数,然后再提取该查询的结果。

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. 我以为一旦我将这些问题分开解决,这将变得很简单,但是我只是对.ajax()不够了解,这就是为什么我在这里。

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查询在单独的文件中

<?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. 如您所见,我尝试使用$ .post()设置查询参数,因为这是我所知道的唯一方法,但是它确实会返回任何结果。 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. 当我将一个值硬编码到我知道在mysql db表中的php查询中时,而不是尝试将用户输入发布到查询中时,它会正确返回并显示查询结果。

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. 我希望你们中一些聪明的人能够发现一些显而易见的东西,而像我这样的新手将不会看到...我肯定觉得一切都应该在.ajax()内进行,但我只是不知道该怎么办它,而且很难在任何地方找到答案。

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). 请让我知道如何改善我的问题,或者在哪里可以找到答案(尽管请记住,我是使用ajax的超级新手,所以我很可能看到了答案,只是不知道是什么我在看)。

remove the $.post then change ajax like this 删除$.post然后像这样更改ajax

$.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'] 在php页面中,您可以像$_POST['email']这样访问该变量

You don't need both $.post and $.ajax . 您不需要$.post$.ajax Use one of them 使用其中之一

$.post("5Query.php", {email:$('textarea').val()}, function(result){ $('#output').html(result); }); //added callback function that will handle response

or you can use $.ajax() 或者您可以使用$.ajax()

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

As you are return only string so you don't need to json_encode (if you want to return multiple records then you have to use it and you have to change your ajax success function accordingly. Change these line in php code 由于您仅返回字符串,因此不需要json_encode (如果要返回多个记录,则必须使用它,并且必须相应地更改ajax成功函数。请在php代码中更改这些行

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

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

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