Risoluzione errore 400 Bad Request con AJAX su tema WordPress personalizzato
7 mar 2018, 16:40:00
Visualizzazioni: 26.5K
Voti: 1
Sto lavorando su un tema personalizzato in cui sto cercando di implementare una ricerca basata su AJAX. Ho costruito tutto seguendo diversi tutorial e guide, ma ispezionando la chiamata ad admin-ajax, continua a restituire errori 400... Ho esaurito le idee e speravo che qualcuno potesse fare luce su questo problema.
functions.php
// Funzione per caricare i risultati della ricerca
function load_search_results(){
$q = $_REQUEST['query'];
$post_type = $_REQUEST['post_type'];
$args = array(
'post_type' => $post_type,
'post_status' => 'publish',
's' => $q,
);
$search = new WP_Query($args);
if ($search->have_posts()){
echo json_encode('ha dei post');
} else {
echo json_encode('nessun post trovato');
}
wp_die();
}
add_action('wp_ajax_load_search_results', 'load_search_results');
add_action('wp_ajax_nopriv_load_search_results', 'load_search_results');
Registrazione degli script in functions.php
wp_register_script('ajax-search', THEME_DIR .'/assets/js/ajax/search.ajax.js', array('jquery'), '1.0', false);
wp_enqueue_script('ajax-search');
wp_localize_script('ajax-search', 'myAjax', array('ajax_url' =>admin_url('admin-ajax.php')));
search.ajax.js
(function($) {
$(document).on('submit', '.controls-search', function(){
var $form = $(this);
var $input = $form.find('input[name="s"]');
var query = $input.val();
var $content = $('.licence');
$.ajax({
type: 'POST',
post_type: 'shuffle_licence',
url: myAjax.ajax_url,
data: {
action: 'load_search_results',
query: query
},
beforeSend: function(){
$input.prop('disabled', true);
$content.addClass('loading')
},
succes: function(response){
$input.prop('disabled', false);
$content.removeClass('loading');
$content.html(response);
},
dataType: 'html',
contentType: 'application/json',
});
return false;
});
}(jQuery))

Alex Hermans
21
Commenti
Tutte le risposte alla domanda
1
Domande correlate
1
risposte