I'm trying to do a basic search feature for my website database. I want to search the text content inside a custom database table using Wordpress and WPDB.
For some reason the search is not returning anything from the database but I'm also not getting any error messages. Here is my code:
thePage.php:
<form class="searchCV_form" role="form" action="">
<div>
<input type="text" id="search_text" name="search_text" class="cv__text">
<span class="input-group-btn">
<button type="submit" class="btn btn-default btn-primary cv__button search--form-btn">SUBMIT</button>
</span>
</div>
</form>
<div id="search_results"></div>
<script>
// wrap everything in a closure
(function($){
// get our references
var $form = $('form.searchCV_form'),
$search_field = $('#search_text'),
$results = $('#search_results');
// 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: "search_cv",
search_text: search_text
}),
success: function (response){
console.log(response);
$results.html(response);
}
});
}
// on submit, do the search but return false to stop page refresh
$form.submit(function(e) {
do_search();
return false;
});
})(jQuery);
</script>
Functions.php:
function search_cv()
{
// get the search query
$search_text = ($_POST["search_text"]);
// clean it up
$search_text = sanitize_text_field( $search_text);
// ... do stuff with it
global $wpdb;
$result = $wpdb->get_results( $wpdb->prepare( "SELECT b, c, v, t FROM myTableName WHERE t like %s", $search_text), ARRAY_A );
//output the HTML which will be consumed by $.html()
?><div>You searched for <?php echo $search_text; ?> and we found... <?php
foreach ($result as $row) {
echo $row->t;
}
?></div><?php
// stop doing stuff
die();
}
add_action( 'wp_ajax_search_cv', 'search_cv' );
add_action( 'wp_ajax_nopriv_search_cv', 'search_cv' );
I suspect that the mistake is in my use of $wpdp->prepare or the SQL query, but I have no idea what could be wrong there.
$row->t
where t like "search_text"
instead ofwhere t like "%search_text%"
, i.e. you will only get results if the entiret
field is equal to the search text, not if thet
field only contains the search text.