doumu8911 2016-12-01 08:06
浏览 66

WordPress中的AJAX表单提交无法正常工作(conti ...)

This is a continuation of my question here. I have custom page template with a form with 2 dropdown and 1 input submit. When the user submit the form, the result will be displayed, this is working properly. But I have a problem, the browser is reload when fetching the data in the database.

I'm trying to use AJAX to prevent refreshing browser. I just updated the AJAX function in functions.php and JS. The page is not refreshing now when the user click the submit button. But the results are not displayed. I'm using is_page, to displayed different result in the specific pages

How to fix this? How can I call the custom PHP file in the AJAX?

AJAX (functions.php)

function ajax_enqueue_sl(){
    wp_enqueue_script('ajax_load_sl', get_template_directory_uri().'/js/alternate-dropdown.js', array('jquery'));
    wp_localize_script('ajax_load_sl', 'ajax_object', array('ajax_url' => admin_url( 'admin-ajax.php')));
}
    add_action('wp_enqueue_scripts', ajax_enqueue_sl);

add_action('init', 'registerFormAction');
function registerFormAction(){
    // To handle the form data we will have to register ajax action. 
    add_action('wp_ajax_nopriv_submitAjaxForm','submitAjaxForm_callback');
    add_action('wp_ajax_submitAjaxForm','submitAjaxForm_callback');
}

function submitAjaxForm_callback(){
    global $wpdb;
    if(is_page(9208)){
        //ROCK ON!
        if (isset($_POST['store_list']) && $_POST['store_list'] != 'Select by Store'){
        $store_list = $_POST['store_list'];
        $stores= $wpdb->get_results($wpdb->prepare("SELECT street FROM tablename WHERE stores= '" . $store_list . "' AND col IN ('test') ORDER BY street ASC", OBJECT));
        foreach ($stores as $record_s){
            echo '<div class="records">';
            echo '<div><span class="icons-tabbed-store icon-icon-stores">' . $record_s->street . '</span></div>';
            echo '</div>';
        }
    } elseif (isset($_POST['mall_list']) && $_POST['mall_list'] != 'Select by Mall'){
        $mall_list = $_POST['mall_list'];
        $street = $wpdb->get_results($wpdb->prepare("SELECT stores FROM tablename WHERE street= '" . $street_list . "' AND col IN ('test') ORDER BY stores ASC", OBJECT));
        foreach ($street as $record_m){
            echo '<div class="records">';
            echo '<div><span class="icons-tabbed-store icon-icon-stores">' . $record_m->stores . '</span></div>';
            echo '</div>';
        }
    }
    }
    wp_die();
}

PHP w/ HTML (test.php)

$results_street = $wpdb->get_results('SELECT DISTINCT street FROM tablename WHERE code IN ("test1") ORDER BY street ASC', OBJECT);
$results_stores = $wpdb->get_results('SELECT DISTINCT stores FROM tablename WHERE code IN ("test2") ORDER BY stores ASC', OBJECT);

<form action='' method='post' name='myform' id="myform">
<div class="pos-div">
<select name="street_list" id="filterbystreet">
    <option name="default" class="filter_by" value="Select by">Select by</option>
    <?php
    foreach($results_street as $option){
        if(isset($_POST['street_list']) && $_POST['street_list'] == $option->street)
            echo '<option name="street_list" class="filter_by" selected value="'. $option->street .'">'. $option->street .'</option>';
        else    
         echo '<option name="street_list" class="filter_by" value="'. $option->street .'">'. $option->street .'</option>';
     };
    ?>
</select>
</div>
<span class="or">or</span>
<div class="pos-div">
<select name="store_list" id="filterby">
    <option name="default" class="filter_by" value="Select by">Select by</option>
    <?php 
    foreach($results_stores as $option){
        if(isset($_POST['store_list']) && $_POST['store_list'] == $option->stores)
            echo '<option name="store_list" class="filter_by" selected value="'. $option->stores .'">'. $option->stores .'</option>';
        else    
         echo '<option name="store_list" class="filter_by" value="'. $option->stores .'">'. $option->stores .'</option>';
     };
    ?>
</select>
</div>
<input type="submit" value="List all partner stores" class="pos-submit"/>
</form>

if (isset($_POST['store_list']) && $_POST['store_list'] != 'Select by Store'){
        $store_list = $_POST['store_list'];
        $stores= $wpdb->get_results($wpdb->prepare("SELECT street FROM tablename WHERE stores= '" . $store_list . "' AND code IN ('test3') ORDER BY street ASC", OBJECT));
        foreach ($stores as $record_s){
            echo '<div class="records">';
            echo '<div><span>' . $record_s->street. '</span></div>';
            echo '</div>';
        }
    } elseif (isset($_POST['street_list']) && $_POST['street_list'] != 'Select by'){
    $street_list = $_POST['street_list'];
    $streets = $wpdb->get_results($wpdb->prepare("SELECT street FROM tablename WHERE street_list= '" . $street_list. "' AND code IN ('test3') ORDER BY stores ASC", OBJECT));
    foreach ($streets as $record_m){
        echo '<div class="records">';
        echo '<div><span>' . $record_m->stores . '</span></div>';
        echo '</div>';
    }
}

ajax_js.js

    jQuery(document).ready(function($){
    //$('#myform').submit(ajaxFormSubmit);

    $('#filterbystreet').change(function(){
        $('#filterbystore').prop('selectedIndex','Select by Store');
    });

    $('#filterbystore').change(function(){
        $('#filterbystreet').prop('selectedIndex','Select by');
    });

    jQuery('.pos-submit').on('click',function(e){ 
        e.preventDefault(); 
        var myform = jQuery('#myform').serialize(); 

        jQuery.ajax({ 
            type:"POST", 
            // Get the admin ajax url which we have passed through wp_localize_script(). 
            url: ajax_object.ajax_url, 
            action: "submitAjaxForm", 
            data: myform, 
            success:function(data){ 
                jQuery(".records").html(data); 
                console.log(data);
            } 
        }); 
    });
});
  • 写回答

1条回答 默认 最新

  • duannao3819 2016-12-01 08:27
    关注

    First at all wp_enqueue_scripts function and wp_localize_script, you should register then enqueue the handle in the function, as the example in the codex

      // Register the script
      wp_register_script( 'ajax_load_sl', get_template_directory_uri().'/js/alternate-dropdown.js', array('jquery'));
    
      wp_localize_script('ajax_load_sl', 'ajax_object', array('ajax_url' => admin_url( 'admin-ajax.php'))););
    
      // Enqueued script with localized data.
      wp_enqueue_script( 'ajax_load_sl');
    

    Details and example here

    In your php script, you didn't mentioned if it stands in a function (I think so, and assuming this), at the top of the function, you need to add

    global $wpdb;
    

    Then you could use $wpdb

    tablename, will never be recognize, your need to put wp_posts where wp_ is your table prefix, or $wpdb->prefix.'posts' if you don't want to matter about the prefix.

    global $wpdb;
    
    $results_street = $wpdb->get_results('SELECT DISTINCT street FROM wp_posts WHERE code IN ("test1") ORDER BY street ASC', OBJECT);
    $results_stores = $wpdb->get_results('SELECT DISTINCT stores FROM wp_posts WHERE code IN ("test2") ORDER BY stores ASC', OBJECT);
    

    Change wp_posts with you right db name.

    Tell me if it works after!

    评论

报告相同问题?

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)