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:
- A form, written in PHP, which resides in the .php file for your page template
- A function which actually executes the SQL query, added to your theme's functions.php file
- 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
版权声明:本文标题:php - Using Ajax to submit a form, and run a SQL Select query based on user input from the form 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738584711a2101362.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论