Проблемы с вызовом AJAX на сайте Wordpress - PullRequest
0 голосов
/ 29 октября 2018

Я сталкиваюсь с некоторыми проблемами в части AJAX функции сайта Wordpress, которая принимает почтовый индекс, введенный в форму, использует функцию PHP, чтобы определить, ссылается ли почтовый индекс на определенное местоположение и возвращает постоянную ссылку на это местоположение.

Мой первый вопрос был о форме, которую я построил. Прямо сейчас у меня есть бланк действия формы, потому что я не хочу, чтобы форма действительно куда-либо уходила, просто сделайте вызов AJAX. Что еще нужно сделать в форме, чтобы указать, что введенные данные должны перейти в функцию AJAX?

<form id="zipcode" action="" method="post"><input class="form-control search-input" autocomplete="off" name="zipcode" type="text" value="" placeholder="Enter Zip Code" />

Следующий вопрос, который у меня есть, касается функции фильтра в моем файле functions.php. Я не уверен, как именно получить данные формы, передаваемые в данные фильтра, это то, что я попробовал ниже, я также включил функцию zip_search, которая возвращает постоянную ссылку.

/**
* LOCATION SEARCH FILTER AJAX
* 
* call location search filter ajax
*
* @return ajax json data via function.
*/
add_action( 'wp_ajax_locations_search', 'prefix_ajax_locations_search' );
add_action( 'wp_ajax_nopriv_locations_search', 'prefix_ajax_locations_search' ); //used for handling AJAX requests from unauthenticated users

function prefix_ajax_zip_search_filter() {
    // Handle request then generate response using WP_Ajax_Response
    $zipcode = $_POST[ 'zipcode' ];

    //return our filtered location data
    echo zip_search($zipcode);

    wp_die(); // this is required to terminate immediately and return a proper response 
}

//Function that contains zip code search functionality
function zip_search($userZip){

    $args = array(
    'posts_per_page'    => -1,
    'post_type'         => 'Locations'
    );

$wp_query = new WP_Query($args); 

if( $wp_query->have_posts() ): while( $wp_query->have_posts() ) : $wp_query->the_post();
      $zipField=get_field('zip_codes_services');

          $zipString = $zipField . ', ';        

          $array = explode(', ' , $zipString); //split string into array seperated by ', '

        foreach($array as $value) //loop over values
        {

            if($value==$userZip){
                $post_id = get_the_ID();
                $permalink=get_permalink($post_id);                 
                return ($permalink); //print
           }    

        }
       endwhile; 
       wp_reset_postdata(); 
endif;
}

Наконец, я создал отдельную папку js, содержащую нижеприведенный файл scripts.js, показанный ниже, а сейчас я просто хотел, чтобы он перенаправлял на пример сайта, если моя форма не пуста. Прямо сейчас единственное, что происходит, когда я отправляю почтовый индекс в форму, это обновление страницы.

    $("form#zipcode").on("submit", function(event) {
    $('form#zipcode .clear-button').addClass('active');
    event.preventDefault();

    zipcode_search(zip_search_filter());
    });    

function zipcode_search(zip_search_filter) {
    //add ajax loader
    $("form#zipcode .ajax-content-loader").addClass("active");

    //process the form
    $.ajax({
        type: "POST", // define the type of HTTP verb we want to use (POST for our form)
        url: ajaxcall.ajaxurl,
        data: {
            action: "locations_search", //calls the function in the functions.php file
            zip_search_filter: zip_search_filter
        },
        success: function(response) {
            //redirect to new page
            if (response != "") {
                    alert("You will now be redirected.");
                    window.location = "http://www.example.com/";
            }

            //remove the loader
            $("#zipcode .ajax-content-loader").removeClass(
                "active"
            );
        }
    });

    return false; //prevents the form from submitting to a new page.
}

Кто-нибудь имеет опыт работы с вызовами AJAX в Wordpress, любой совет приветствуется.

Ответы [ 2 ]

0 голосов
/ 29 октября 2018

Сначала я должен был добавить идентификатор формы:

Затем я сделал несколько правок в functions.php:

/**
* LOCATION SEARCH FILTER AJAX
* 
* call location search filter ajax
*
* @return ajax json data via function.
*/
add_action( 'wp_ajax_locations_search', 'prefix_ajax_locations_search' );
add_action( 'wp_ajax_nopriv_locations_search', 'prefix_ajax_locations_search' ); //used for handling AJAX requests from unauthenticated users

function prefix_ajax_locations_search() {
    // Handle request then generate response using WP_Ajax_Response
    $zipcode = $_POST[ 'zipcode' ];

    //return our filtered location data
    echo zip_search($zipcode);

    wp_die(); // this is required to terminate immediately and return a proper response 
}

//Function that contains zip code search functionality
function zip_search($userZip){

    $args = array(
    'posts_per_page'    => -1,
    'post_type'         => 'Locations'
    );

$wp_query = new WP_Query($args); 

if( $wp_query->have_posts() ): while( $wp_query->have_posts() ) : $wp_query->the_post();
      $zipField=get_field('zip_codes_services');

          $zipString = $zipField . ', ';        

          $array = explode(', ' , $zipString); //split string into array seperated by ', '

        foreach($array as $value) //loop over values
        {

            if($value==$userZip){
                $post_id = get_the_ID();
                $permalink=get_permalink($post_id);                 
                return ($permalink); //print
           }    

        }
       endwhile; 
       wp_reset_postdata(); 
endif;
}

Мне также пришлось включить свой пользовательский файл jquery и мой файл AJAX в функцию enqueue_scripts functions.php:

wp_enqueue_script( 'custom-js', get_stylesheet_directory_uri() . '/js/scripts.js', array('jquery'), '', true );
    wp_localize_script( 'custom-js', 'ajaxcall', array('ajaxurl' => admin_url( 'admin-ajax.php' )));

Наконец, в scripts.js я внес следующие изменения и вместо перенаправления на http://example.com я перенаправил на постоянную ссылку, которую я получаю из моей zip_search функции, показанной выше.

/*
 * Put all your regular jQuery in here.
 * Within this funtion you can use the namespace $ instead of jQuery
 * ex. use this $('#id') ... NOT jQuery('#id')
*/
jQuery(document).ready(function($) {

    $("form#zipcode").on("submit", function(event) {
        event.preventDefault();

        $('form#zipcode .clear-button').addClass('active');

        //get the entered zipcode value to pass through our function.
        var zipcode = $(this).find('input[name="zipcode"]').val();

        zipcode_search(zipcode);

    });    

    function zipcode_search(zipcode) {
        //add ajax loader
        $("form#zipcode .ajax-content-loader").addClass("active");

        //process the form
        $.ajax({
            type: "POST", // define the type of HTTP verb we want to use (POST for our form)
            url: ajaxcall.ajaxurl,
            data: {
                action: "locations_search", //calls the function in the functions.php file
                zipcode: zipcode
            },
            success: function(response) {
                //redirect to new page
                if (response != "") {
                        //alert("You will now be redirected.");

                        window.location = response;
                }

                //remove the loader
                $("#zipcode .ajax-content-loader").removeClass(
                    "active"
                );
            }
        });

        return false; //prevents the form from submitting to a new page.
    }

}); /* end of as page load scripts */

Выполнение всего этого решило мою проблему, и теперь форма поиска работает так, как мне нужно.

0 голосов
/ 29 октября 2018

Похоже, что форма отправляется до вызова ваших функций. Попробуйте переместить event.preventDefault(), чтобы он назывался первым, например:

$("form#zipcode").on("submit", function(event) {
event.preventDefault(); //call this first
$('form#zipcode .clear-button').addClass('active');

zipcode_search(zip_search_filter());
});    

Проверьте ваш синтаксис, вместо =! должно быть !=;

//correct syntax
if (data != "") {
    alert("You will now be redirected.");
    window.location = "http://www.example.com/";
}

Кроме того, ваша success функция возвращает response, но вы ссылаетесь на data. Измените код так, чтобы на него ссылались на соответствующий объект:

 success: function(response) {
        //redirect to new page
        if (response != "") {
                alert("You will now be redirected.");
                window.location = "http://www.example.com/";
        }

или ...

 success: function(data) {
        //redirect to new page
        if (data != "") {
                alert("You will now be redirected.");
                window.location = "http://www.example.com/";
        }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...