I have a search form which searches the DB and returns back some data. I have managed to use WordPress wpdb to connect and use select statement on the table and retrieve data. Everything works fine..But..I have page refresh issue. I want to add AJAX code in order to get my data without refreshing. So, I have followed along with this, this and tutorials. But,I’m facing some problems with them. So, here’s what I got:
My JS code:
var search_text = j$(".cv__text").val();
j$.post({
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: ({
action: "search_cv", search_text: search_text
}),
success: function (response){
console.log(response);
j$("#search_results").html(response);
}
});
My functions.php:
function search_cv(){
$search_text = ucfirst($_POST["search_text"]);
//Creating New DB Connection
$database_name = "employee_cv";
$mydb = new wpdb(DB_USER, DB_PASSWORD, $database_name, DB_HOST);
$mydb -> show_errors();
if ($_POST["search_text"] != null){
$result = $mydb -> get_results(
$mydb -> prepare(
'SELECT * FROM employee
WHERE Experience = %s',
$search_text
)
);
}
foreach ($result as $employee){
//Here I just echo html blocks (divs, paragraphs etc.)
}
die();
}
add_action( 'wp_ajax_search_cv', 'search_cv' );
add_action( 'wp_ajax_nopriv_search_cv', 'search_cv' );
My HTML:
<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>
So, after all this changes, I still get the refresh on page and also, my query is not working at all. I’m not sure what I’m doing wrong here. I’ve used AJAX before on my projects but never with WordPress and php.