douxiao0400
douxiao0400
2015-11-17 04:29
浏览 64

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
    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']

    点赞 评论
  • dsstjqsr631426
    dsstjqsr631426 2015-11-17 04:45

    You don't need both $.post and $.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()

            // 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

    if($row){
      echo $name;
      } else {
        echo $error;
      }
    
    点赞 评论

相关推荐