php – Using Ajax to submit a form, and run a SQL Select query based on user input from the form


I’m creating a web form on my WordPress powered website. The form is intended to allow the user to enter a ZIP Code (aka postal code). When the user submits the form, the page should query a MySQL table, SELECT the rows which match the search criteria and dispense those values into a table on the same page.

Unfortunately, I have been unsuccessful thus far.

Per the example I followed, three components are necessary to query a SQL table from within a WordPress site:

  1. A form, written in PHP, which resides in the .php file for your page template
  2. A function which actually executes the SQL query, added to your theme’s functions.php file
  3. A segment of Javascript code to tie the above two things together

Here is what I have so far.

First, the form code:

<form type="post" action="" role="form" id="DirectorySearchForm" class="DirectorySerch">
    <p style="font-size: 16pt;">Zip Code: <input style="font-size: 16pt;" type="text" name="inZip" width="200" height="32"></p>
    <input type="hidden" name="action" value="DirectorySearch">
    <input type="submit" name="submit" value="Search" style="font-size: 18pt;">
<div id="search_results"></div>

Second, the function in functions.php:

function DirectorySearch() {
    global $wpdb;
    echo "33333";   

    $inZip = $_POST['inZip'];

    $query = 'SELECT OrgName, Phone FROM directory_organizations WHERE Zip_Codes LIKE %s%';

    $results = $wpdb->get_results( $wpdb->prepare($query, $inZip) );
    echo $results;
add_action( 'wp_ajax_DirectorySearch', 'DirectorySearch' );    //If called from admin panel
add_action( 'wp_ajax_nopriv_DirectorySearch', 'DirectorySearch' );    //If called by non-user

Third, the javascript sequence to tie the above two together.

<script type="text/javascript">
  // get our references
  var $form = $('form.DirectorySerch'),
      $inZip = $('#inZip'),
      $results = $('#search_results');

// on submit, do the search 
  $form.submit(function(e) {

  // AJAX search call
  function do_search() {

    // grab the query value from the search field
    var search_text = $search_field.val();

    // do a POST ajax call
      type: "POST",
      url: "<?php echo admin_url('admin-ajax.php'); ?>",
      data: ({
        action: "DirectorySearch",
        search_text: search_text
      success: function (response){


I’m a beginner, so I borrowed heavily from examples of others trying to accomplish the same thing. However, my web form does not generate a query result.

Can anyone see what I might be doing wrong, or, alternatively, advise me on how to troubleshoot?

Frank 9 months 2022-05-16T20:57:53-05:00 0 Answers 0 views 0

Leave an answer