duan2428 2018-04-02 21:44
浏览 47

用ajax自动完成字段wordpress

I'm doing a project on WordPress and I'm having some trouble with the auto-complete field on my form. No input is shown and no error in console. I created a small database on one of the WordPress database. I'm not very familiar with AJAX so please be kind :)

jQuery(document).ready(function($) {    

jQuery('#dish').autoComplete({
source: function(name, response) {
    jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        url: 'wp-admin/admin-ajax.php',
        data: 'action=get_listing_names&name='+name,
        success: function(data) {
            response(data);
        }
    });
}
});

});

This is my jQuery code and I added the admin-ajax in the same folder as I was thinking it didn't find it (it's my_serach.js)

function ajax_listings() {
global $wpdb; //get access to the WordPress database object variable

//get names of all businesse
$name = $wpdb->esc_like(stripslashes($_POST['name'])).'%'; //escape for use in LIKE statement
$sql = "select name 
    from $wpdb->global 
    where name like %s 
    and post_type='portfolio' and post_status='publish'";

$sql = $wpdb->prepare($sql, $name);
$results = $wpdb->get_results($sql);

//copy the business titles to a simple array
$titles = array();
foreach( $results as $r )
    $titles[] = addslashes($r->name );

echo json_encode($titles); //encode into JSON format and output
die(); //stop "0" from being output

i add this code on the functions.php on the theme i'm working on

 <form method = "POST">
    <div id = "container">
        <div><label class="plate_label">Dish:</label><input type="text"    name="dish_name[]" id="dish" class="dish" placeholder="Enter plate name" />
            <label class="quantity_label">Quantity:</label><input type="text" name="dish_quantity[]"  class="quantity" placeholder="Enter gram or pieces/slices" /></div>
        </div>

and last the form where it should show the suggestions from the database.

  • 写回答

1条回答 默认 最新

  • doumou5109 2018-04-03 09:33
    关注

    Try this code.

    jQuery(document).ready(function($) {    
    
    jQuery('#dish').autoComplete({
        source: function(name, response) {
        jQuery.ajax({
            type: 'POST',
            dataType: 'json',
            url: 'http://caloriless.com/wp-admin/admin-ajax.php',
            data: 'action=get_listing_names&name='+name,
            success: function(data) {
            response(data);
            }
        });
        }
    });
    

    });

    change ajax url url: 'wp-admin/admin-ajax.php', or url: 'http://caloriless.com/wp-admin/admin-ajax.php',

    评论

报告相同问题?

悬赏问题

  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教