Home > other >  Wordpress: Ajax call doesn't work (Error 400 Bad Request)
Wordpress: Ajax call doesn't work (Error 400 Bad Request)

Time:01-27

in simple words: Ajax is called from Javascript file, but php function doesn't 'hear' the call. In my case PHP and Javascript are in separate files. I proved that they are loaded correct in functions.php by:

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:

//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:

// 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. Error: Failed to load resource: the server responded with a status of 400 (Bad Request)

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. Am I right? enter image description here

CodePudding user response:

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

              $.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);
                }
            });

CodePudding user response:

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). This was a mistake. My code in the functions.php that works now is:

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');
  • Related