在Wordpress网站中进行AJAX调用时遇到问题

时间:2018-10-29 17:45:30

标签: javascript php ajax wordpress

我遇到了一个Wordpress网站功能的AJAX部分的问题,该功能使用在表单上输入的邮政编码使用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文件中的filter函数。我不确定如何使表单数据通过过滤器数据,这是我在下面尝试过的方法,我还包括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.
}

任何人都具有在Wordpress中进行AJAX调用的经验,可以提出任何建议。

2 个答案:

答案 0 :(得分:0)

听起来像是在调用函数之前提交表单。尝试移动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/";
        }

答案 1 :(得分:0)

首先,我必须添加一个表单ID:

然后我在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;
}

我还必须在enqueue_scripts函数functions.php中包含我的自定义jquery文件和AJAX文件:

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

所有这些都解决了我的问题,现在搜索表单可以按我需要的方式工作。