Search code examples
phpajaxbootstrap-typeahead

Typeahead input field and query passed to PHP with AJAX


I am using Twitter Bootstrap Typeahead for an autocomplete field.

End state goal: The user first enters details into field 1. When they enter details in field 2, ajax passes the query as it is written to a PHP file which queries a database based on what was also entered into field 1.

How do I pass both the query from field 2 and the contents of field 1 to the PHP file and access them.

Here is what I have so far:

HTML FILE:

<div class="field1">
    <input type="text" id="field1" data-provide="typeahead" name="field1">
</div>
<div class="field2">
    <input type="text" id="field2" data-provide="typeahead">
</div>

<script src="js/jquery-1.9.1.min.js"></script>
    <script src="js/bootstrap.js"></script>
    <script>
$(function() {
            $("#field2").typeahead({
                source: function(query, process) {
        var textVal=$("#field1").val();
                    $.ajax({
                        url: 'field2.php',
                        type: 'POST',
                        data: 'query=' + query,
                        dataType: 'JSON',
                        async: true,
                        success: function(data) {
                            process(data);
            console.log(textVal);
                        }
                    });
                }
            });
        });
    </script>

PHP FILE:

if (isset($_POST['query'])) {
$db_server = mysql_connect("localhost", "root", "root");
mysql_select_db("db_test");

$query = $_POST['query'];
$other = '**This needs to be field 1**';

$sql = mysql_query("SELECT * FROM table WHERE row1 LIKE '%{$query}%' AND row2 = '$other'");
$array = array();

while ($row = mysql_fetch_assoc($sql)) {
    $array[] = $row['row1'];
}

echo json_encode($array);}

At the moment, the query part works perfectly and the results are returned (the console also displays the value from 'Field1'. Just need to get that value into the php file at the same time!

Any help would be great


Solution

  • If I understood this correctly, you want to parse both the values of field 1 and 2 to the same AJAX call. This is how you do it.

    <script>
    $(function() {
      $("#field2").typeahead({
        source: function(query, process) {
          var textVal=$("#field1").val();
          $.ajax({
            url: 'field2.php',
            type: 'POST',
            data: 'query=' + query + '&field1=' + textVal,
            dataType: 'JSON',
            async: true,
            success: function(data) {
              process(data);
              console.log(textVal);
            }
          });
        }
      });
    });
    </script>
    

    Now you just make another $_POST['field1'] in your PHP file.