I use select2 and ajax to query my database for terms under a specific taxonomy, but when I search in search boxes it just freezes when I search, without getting any results.
This is my html
<select multiple="" name="regions1[]" id="regions1" class="job-manager-multiselect select2-hidden-accessible" required="" tabindex="-1" aria-hidden="true"></select>
My jquery:
<script>
jQuery(function($) {
$(document).ready(function() {
$( "#regions1" ).select2({
ajax: {
url: "/ajax/connect.php",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term
};
},
processResults: function (data) {
return {
results: data
};
},
cache: true
},
minimumInputLength: 2
});
});
});
</script>
and my php code to query the database, I am looking to get all the term names in the taxonomy "job_listing_region"
<?php
$servername = "localhost";
$username = "myusername";
$password = "mypassword";
try {
$conn = new PDO("mysql:host=$servername;dbname=mydatabase", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
layer of security but fits needs for this tutorial
$search = strip_tags(trim($_GET['q']));
$query = $conn->prepare("
SELECT * FROM (
SELECT wp_terms.name
FROM wp_terms
JOIN wp_term_taxonomy
ON wp_term_taxonomy.term_id = wp_terms.term_id
WHERE taxonomy = 'job_listing_region'
AND count = 0
) as T"
);
$query->execute(array(':search'=>"%".$search."%"));
$list = $query->fetchall(PDO::FETCH_ASSOC);
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['name'], 'text' => $value['name']);
}
} else {
$data[] = array('id' => '0', 'text' => 'No Products Found');
}
echo json_encode($data);
And, as you can see, I retrieve my data, but the search just freezes.

Thanks in advance.
source
share