How to use a form to send an ajax request to a php function in wordpress then send the return value of the function (a permalink to a post) back to my ajax function response to open a new tab to that particular post?
My php function in functions.php
:
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;
}
My form, on front page of my website:
<form id="zip_search_form" action="" method="post"><input class="form-control search-input" autocomplete="off" name="zipcode" type="text" value="" placeholder="Enter Zip Code" /></form><input type="submit" />
Javascript I tried:
$("form#zip_search_form").on("submit", function(event) {
$('form#zip_search_form .clear-button').addClass('active');
event.preventDefault();
all_locations_map_ajax_filter();
});
//Our main ajax call
function zip_search_ajax_filter(){
var filters = [];
var zipcode = $('form#zip_search_form input[name="zip_search"]').val();
//process the form
$.ajax({
type: "POST", // define the type of HTTP verb we want to use (POST for our form)
dataType : "json",
url: ajaxcall.ajaxurl,
data: {
"action": "zip_search", //calls the function in the functions.php file
"zipcode": zipcode
},
success: function(response) {
if(response.length > 0){
//remove the current markers
$(this).html(response)
}
}
})}
I tried changing the Javascript around a bit with no luck. I have this contained in a folder called js
with a file name called scripts.js
. I have tried reading the AJAX docs but I'm not really sure how it grabs the form data etc or where exactly I should put it in my file structure. Any advice is appreciated.