WordPress Ajax Search приводит к "... status 400 (Bad Request)" - PullRequest
0 голосов
/ 15 июня 2019

Я создал форму поиска, которая будет содержать несколько текстовых полей, выпадающих списков и флажков. Вывод - таблица под формой поиска. Я хочу, чтобы он выполнял поиск по каждому клику, замене или ключевому слову vai AJAX. У меня это работало как прямое PHP-приложение. Когда я переместил код в WordPress, возникла проблема.

При выполнении WordPress-способа я получаю сообщение «Не удалось загрузить ресурс: сервер ответил с состоянием 400 (неверный запрос)» и, похоже, не может найти причину. Когда я вызываю код для обработки ajax POST и вывода результатов. На странице правильно отображается, за исключением того, что между формой и таблицей результатов имеется второе меню WP.

Я сократил код из полного приложения до простой формы / плагина, который ищет и отображает таблицу пользователя WP.

Как мне лучше устранить неисправность "неверного запроса?

см. Выше

$var1 = admin_url("admin-ajax.php");
$formAction = " action=\"$var1\"";  // i.e. WP's admin-ajax.php

// Used by WP ajax and is in a hidden <input> field names "action"
function asi2_LTCfetchAll_ajax(){ 
    global $asi2_plugin_dir;
    require($asi2_plugin_dir . "/asi2-test/asi2_searchResults.php");
}
add_action( "wp_ajax_asi_LTCfetchAll_ajax", "asi2_LTCfetchAll_ajax" );          // admin users
add_action( "wp_ajax_nopriv_asi_LTCfetchAll_ajax", "asi2_LTCfetchAll_ajax" );   // non-logged in users

// enqueue the WP ajax script
wp_enqueue_script( 'asi2_ajax_script',    plugin_dir_url( __FILE__ )  . 'asi2_ajax_action.js',    array('jquery'), 1.1,true);

// Uncomment to test DavesWay where ajax almost works ;=}
//require($asi2_plugin_dir . "/asi2-test/asi2_DavesWay.php"); // Override WP's strange Ajax rules

// The Form follows below 
/*
 * Form notes: all <input>'s & <select>'s have both an "id" and "name". id's are used by JavaScript and name's with $_POST.
 * The match the MySQL field name and with the beginning $ are used as a PHP variable.
 * Ideally inputs that are not fieldnames (like _rowsPerPage) should begin with a leading underscore to indicate they are not 
 * MySQL fieldsnames.
 * */
?>
<script> 
    var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>

<div id="asi_container" class="asi_container" >
    <noscript><h2 class="warning">This site requires Javascript and cookies to function.</h2></noscript>
    <div id="searchForm">
        <form id="asi_search_form" name="asi_search_form" method="post" 
            <?php echo $formAction; ?>>
        <input type="hidden" id="action" name="action" value="asi2_LTCfetchAll_ajax"> 
        <?php wp_nonce_field('my_searchForm_action'); ?>
        <table id="testTable" class="asi_table" >
            <tbody>   
            <tr class="asi_ltc DataGrid_Header">

'''javascript
function setById(id, value) { // Used to set vales by Id
    x = document.getElementById(id).value;
    x.value = value;
}

function submitPg1(theForm) {
    // Used with onChange from "most" form elements, but not on those that change the page
    // rather than the select criteria. Such as pageNumber.
    setById("pageNo", "1"); // set inital page. ie all changes in search criteria start with page 1
    mySubmit();        
}
function mySubmit(theForm) { // The actual ajax submit
    //alert("Got to mySubmit");
    jQuery.ajax({ // create an AJAX call...
    data: jQuery("#asi_search_form").serialize(),       // get the data from the form
    type: jQuery("#asi_search_form").attr("method"),    // GET or POST from the form
    url:  jQuery("#asi_search_form").attr("action"),    // the file to call from the form
    success: function (response) {                      // on success..
        jQuery("#result").html(response);               // update the DIV #result
    }     
})
}
  /* 1st submit with blank selection */
jQuery(document).ready(function () { submitPg1(this.form); });

jQuery( document.body ).on( 'post-load', function () {
    // New content has been added to the page.
} );


"Failed to load resource: the server responded with a status of 400 (Bad Request)"
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...