I try jquery autocomplete with wordpress but i don't understand where is my error 500 in my code :
I think its my code in php.
$('#search_type_fiche').autocomplete({
source: function(search, response) {
$.ajax({
type: 'POST',
dataType: 'json',
url: MyAjax.ajaxurl,
data: 'action='+MyAjax.action+'&search='+search.term,
success: function(data) {
response($.map(data, function(item) {
return {
label: item,
value: item
}
}));
//$("p#resultat").html(response(data));
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$("div#ajax-response").removeClass().addClass('error').html('error');
}
});
console.log(data);
}
});
Callback php :
public $search;
public function __construct()
{
global $wpdb;
$this->wpdb = $wpdb;
}
public function SearchTypeFiche($search){
$this->search = $search;
$datas = $wpdb->get_results(
$wpdb->prepare(
"SELECT slug,id FROM {$this->wpdb->prefix}fiches_type WHERE slug LIKE %s",
$this->esc_like(stripslashes($this->search)).'%'
)
);
$results = array();
foreach($datas as $key){
$arr = array();
$arr['label'] = addslashes($key->slug);
$arr['value'] = $key->id;
$results[] = $arr;
};
return json_encode($results);
}
$data_search = $_POST['search'];
parent::SearchTypeFiche($data_search);
Thx for help !
ps : i searched in stackoverflow but no posts resolve my problem..
I have try too, where is the problem ? :
public function search_type_fiche() {
$search_data = $wpdb->get_results(
$wpdb->prepare(
"SELECT id,slug FROM {$wpdb->prefix}fiches_type WHERE slug LIKE %s",
'%'.$_REQUEST['term'].'%'
)
);
$suggestions=array();
foreach ($search_data as $post):
$suggestion = array();
$suggestion['label'] = $post->slug;
$suggestion['link'] = $post->id;
$suggestions[]= $suggestion;
endforeach;
echo $_GET["callback"] . "(" . json_encode($suggestions) . ")";
die();
}
$("#search_type_fiche").autocomplete({
delay: 0,
minLength: 3,
source: function(req, response){
$.getJSON(MyAjax.ajaxurl+'?callback=?&action='+MyAjax.action, req, response);
},
select: function(event, ui) {
window.location.href=ui.item.link;
},
}
);
Why not work ?
Wordpress have this and work fine :
<script type="text/javascript">
jQuery(document).ready(function ($){
var ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ); ?>';
var ajaxaction = '<?php echo self::$action ?>';
$("#secondary #searchform #s").autocomplete({
delay: 0,
minLength: 3,
source: function(req, response){
$.getJSON(ajaxurl+'?callback=?&action='+ajaxaction, req, response);
},
select: function(event, ui) {
window.location.href=ui.item.link;
},
});
});
</script>
private function autocomplete_suggestions() {
$posts = get_posts( array(
's' => $_REQUEST['term'],
) );
$suggestions=array();
global $post;
foreach ($posts as $post):
setup_postdata($post);
$suggestion = array();
$suggestion['label'] = esc_html($post->post_title);
$suggestion['link'] = get_permalink();
$suggestions[]= $suggestion;
endforeach;
echo $_GET["callback"] . "(" . json_encode($suggestions) . ")";
exit;
}