在 Wordpress 站点中进行 AJAX 调用的问题 [英] Problems making an AJAX call in a Wordpress site
问题描述
我在 Wordpress 站点功能的 AJAX 部分遇到了一些问题,该功能接受表单上输入的邮政编码,使用 PHP 函数查找邮政编码是否指向特定位置并返回指向该位置的永久链接.
I am running into some issues with the AJAX portion of a Wordpress site feature that takes a zip code entered on a form uses a PHP function to find if the zip code refers to a specific location and returns a permalink to that location.
我的第一个问题是关于我构建的表单.现在我有表单操作空白,因为我不希望表单真的去任何地方,只需进行 AJAX 调用.我需要在表单中做什么额外的事情来指示输入的数据应该转到 AJAX 函数吗?
My first question was about the form I built. Right now I have the form-action blank because I don't want the form to really go anywhere, just make the AJAX call. Is there anything extra I need to do in the form to indicate the data entered should go to an AJAX function?
<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 函数.
The next question I have is about the filter function in my functions.php file. I'm not sure exactly how to go about getting the form data passed inot the filter data, this is what I have tried below, I also included the zip_search function which returns the permalink.
/**
* 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,现在我只是想让它重定向到一个示例站点,如果我的表单不是空白的.现在,当我将邮政编码提交到表单中时,唯一发生的事情就是页面刷新.
Lastly I created a separate js folder containing the below scripts.js seen below, for now I just wanted it to redirect to an example site if my form is not blank. Right now the only thing that happens when I submit a zipcode into the form is the page refreshes.
$("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 调用,不胜感激.
Does anyone have experience with AJAX calls in Wordpress, any advice is appreciated.
推荐答案
首先我必须添加一个表单 ID:
First I had to add a form id:
然后我在 functions.php
中做了一些
Then I made a number of edits, in 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 文件:
I also had to include my custom jquery file and my AJAX file in the enqueue_scripts
function 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
函数获得的永久链接.
Finally in scripts.js
I made the following changes and instead of redirecting to http://example.com I redirected to the permalink I get from my zip_search
function seen above.
/*
* 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 */
所有这些都解决了我的问题,搜索表单现在可以按照我的需要工作.
Doing all of this solved my problem and the search form now works how I need it to.
这篇关于在 Wordpress 站点中进行 AJAX 调用的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!