Bit of background: I am building an autocompleting-search box for a list of Trades (a Custom Taxonomy). I asked this question and very helpfully got a much better understanding of how WordPress and AJAX work together (Thanks G.M)! However, he said that I should use wp_localize_script
so that the PHP isn't accessible on the front-end. I knew about this function but had never used it so with a bit of reluctance I got stuck in.
I found this post which also had an incredibly useful explanation of how WordPress and AJAX work together. I implemented that code provided by Stephen Harris, but I've got an error in my console, whenever I search for anything in the search bar:
TypeError: '["Accountants","Electricians","Painters","Plumbers"]' is not a valid argument for 'in' (evaluating 'b-1 in a')
and here is my PHP code:
wp_enqueue_script("autocomplete", get_template_directory_uri() . '/assets/js/autocomplete.js', array( 'jquery', 'jquery-form', 'json2' ), false, true );
wp_localize_script("autocomplete", "MyAjax_object", array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'myajax_nonce' => wp_create_nonce( 'myajax_nonce_val' ),
'action' => 'myajax-submit'
));
function get_my_suggestions() {
// This function should query the database and get results as an array of rows:
// GET the recieved data: 'term' (what has been typed by the user)
$term = $_GET['term'];
$trades = get_terms( 'trade', array( 'fields' => 'names' ) );
$tradesList = '["' . implode( '","', $trades ) . '"]';
// echo JSON to page and exit.
$response = $_GET["callback"]."(". json_encode($tradesList) .")";
echo $response;
exit;
}
add_action( 'wp_ajax_myajax-submit', 'get_my_suggestions' );
and JavaScript:
$(document).ready(function() {
$(".main-search-field").autocomplete({
source: function( request, response ) {
jQuery.getJSON( MyAjax_object.ajaxurl + "?callback=?&action=myajax-submit", request, function( data ) {
response( jQuery.map( data, function( item ) {
jQuery.each( item, function( i, val ) {
val.label = val.whatever; // build result for autocomplete from suggestion array data
} );
return item;
} ) );
} );
},
minLength: 1,
appendTo: ".search-container"
});
});
Does anyone know why I get that error? The JavaScript loads fine - it adds in the markup for the suggestions list, but it's empty. Also, I've noticed that whenever I search for something in the input box, a class, ui-autocomplete-loading
is added to the input box. Not sure if that's important but it might help someone out.
Thanks for any help :)