Problems making an AJAX call in a Wordpress site

2019-07-24 14:37发布

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.

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

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;
}

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.
}

Does anyone have experience with AJAX calls in Wordpress, any advice is appreciated.

2条回答
Emotional °昔
2楼-- · 2019-07-24 14:48

It sounds like the form is submitting before your functions are called. Try moving event.preventDefault() so it is called first, like so:

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

zipcode_search(zip_search_filter());
});    

Check your syntax, =! should instead be !=;

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

Also, your success function returns response, but you are referencing data. Change the code so that the proper object is referenced:

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

or...

 success: function(data) {
        //redirect to new page
        if (data != "") {
                alert("You will now be redirected.");
                window.location = "http://www.example.com/";
        }
查看更多
冷血范
3楼-- · 2019-07-24 15:08

First I had to add a form id:

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;
}

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

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.

查看更多
登录 后发表回答