简体   繁体   English

Wordpress:Ajax 调用不起作用(错误 400 错误请求)

[英]Wordpress: Ajax call doesn't work (Error 400 Bad Request)

in simple words: Ajax is called from Javascript file, but php function doesn't 'hear' the call.简而言之:从 Javascript 文件调用 Ajax,但 php function 没有“听到”调用。 In my case PHP and Javascript are in separate files.在我的例子中,PHP 和 Javascript 在不同的文件中。 I proved that they are loaded correct in functions.php by:我通过以下方式证明它们在 functions.php 中加载正确:

function LoadScriptsOnSpecificPages(){
    global $wp_query;
    $page_id = intval($wp_query->queried_object->ID);
    
    // Page ID 2614 = Buchung Auswahl Raum, Page ID 2654 = Buchung abschließen
    if (($page_id = 2614) or ($page_id = 2654)) {
        include get_stylesheet_directory() . '/custom/booking.php';
        wp_enqueue_script( 'script', get_stylesheet_directory_uri() . '/custom/booking.js', array( 'jquery' ), 1.1, true);

    }
}
add_action('template_redirect', 'LoadScriptsOnSpecificPages');

In "booking.php" at the top:在顶部的“booking.php”中:

//Define AJAX URL and requests
function define_ajax_url() {
   echo '<script type="text/javascript">
           var ajaxurl = "' . admin_url('admin-ajax.php') . '";
         </script>';
}
add_action('wp_head', 'define_ajax_url');

// Action hooks that work with the WordPress AJAX functionality
// wp_ajax_nopriv_ action Hooks bewirken, dass der Ajax-Request auch bei Website-Besuchern läuft,
// die nicht eingeloggt sind.
add_action( 'wp_ajax_AjaxSessionIDerzeugen', 'AjaxSessionIDerzeugen' );
add_action( 'wp_ajax_nopriv_AjaxSessionIDerzeugen', 'AjaxSessionIDerzeugen' ); 

Problem: Also in the file "booking.php" the function that should be called, but unfortunately is never called:问题:同样在文件“booking.php”中应该调用的 function,但遗憾的是从未调用过:

// Ajax Session ID erzeugen
function AjaxSessionIDerzeugen() {
    $ip_adresse = $_SERVER["REMOTE_ADDR"];

    global $wpdb;
    $wpdb->show_errors();
    
    // $_REQUEST contains the data sent via AJAX from the Javascript call
    if ( isset($_REQUEST) ) {
        $session_id = substr(md5(time()), 0, 10);
        $strsql = sprintf("INSERT INTO tbl_buchungen (session_id) VALUES session_id= '%s'",$session_id);
        $wpdb->query($strsql);

        // Callback
        callback:
        $arr = array();
        $arr['pruefergebnis'] = "ok";
        $arr['session_id'] = $session_id;

        $antwort_json = json_encode($arr);
        echo $antwort_json;
    }
    // Always die in functions echoing AJAX content
   die();
}

In the file "booking.js" there is the Ajax-Call that doesn't work.在文件“booking.js”中,Ajax-Call 不起作用。 Error: Failed to load resource: the server responded with a status of 400 (Bad Request)错误:无法加载资源:服务器响应状态为 400(错误请求)

if ((session_id == '') || (session_id == null)) {
            $.ajax({
                url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
                data: {
                    'action':'AjaxSessionIDerzeugen', // PHP function
                },
    
                // Callback
                success:function(antwort) {
                    let object = JSON.parse(antwort);
                    pruefergebnis = object.pruefergebnis;
    
                    if (pruefergebnis == 'ok') {
                        session_id = object.session_id;
                        document.cookie = "session_id=" + session_id + "; expires=3600000; path=/";
                    } else {
                        window.alert(pruefergebnis);
                    }
                },
                error: function(errorThrown){
                    window.alert(errorThrown);
                }
            });

        }

I checked the.network tab for the Ajax URL. It seems to be ok.我检查了 Ajax URL 的.network 选项卡。它似乎可以。 Am I right?我对吗? 在此处输入图像描述

The admin-ajax URL is available on admin side, for the front end you need to define it, I correct some small error and tested on my local it is working admin-ajax URL 在管理端可用,对于前端你需要定义它,我纠正了一些小错误并在我的本地测试它正在工作

              $.ajax({
              type: "POST",
                url: ajaxurl, //you need to point to correct URL if you are working on frontend
                data: {
                    action:'AjaxSessionIDerzeugen', // PHP function
                },
    
                // Callback
                success:function(antwort) {
                    let object = JSON.parse(antwort);
                    pruefergebnis = object.pruefergebnis;
    
                    if (pruefergebnis == 'ok') {
                        session_id = object.session_id;
                        document.cookie = "session_id=" + session_id + "; expires=3600000; path=/";
                    } else {
                        window.alert(pruefergebnis);
                    }
                },
                error: function(errorThrown){
                    window.alert(errorThrown);
                }
            });

The reason why it didn't work was, that - in functions.php of the theme - I restricted the loading of files booking.php and booking.js to the pages where I need it (by Page ID).它不起作用的原因是,在主题的 functions.php 中,我将文件 booking.php 和 booking.js 的加载限制在我需要的页面(通过页面 ID)。 This was a mistake.这是一个错误。 My code in the functions.php that works now is:我现在可以使用的 functions.php 中的代码是:

include get_stylesheet_directory() . '/custom/booking.php';

function LoadScript() {
    wp_enqueue_script( 'script', get_stylesheet_directory_uri() . '/custom/booking.js', array( 'jquery' ), 1.1, true);
}
add_action('template_redirect', 'LoadScript');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM