admin管理员组

文章数量:1201805

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;">
</form>
<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;
    die();
}
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">
(function($){               
  // get our references
  var $form = $('form.DirectorySerch'),
      $inZip = $('#inZip'),
      $results = $('#search_results');

// on submit, do the search 
  $form.submit(function(e) {
    e.preventDefault();
    do_search();
  });

  // 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
    $.ajax({
      type: "POST",
      url: "<?php echo admin_url('admin-ajax.php'); ?>",
      data: ({
        action: "DirectorySearch",
        search_text: search_text
      }),
      success: function (response){
        console.log(response);
        $results.html(response);
      }     
    });
  }

})(jQuery);
</script>

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?

本文标签: phpUsing Ajax to submit a formand run a SQL Select query based on user input from the form