Ajax表单成功数据始终为空

时间:2015-02-23 03:03:44

标签: jquery ajax wordpress wpdb

我正在尝试运行wordpress wpdb-> get_results选择查询,我想从文本框中获取搜索条件。我想在没有刷新页面的情况下使用ajax进行表单。无论我做什么,我在搜索文本框中输入的文本框值始终为空。如果我修改我的查询并返回所有结果,则选择查询起作用并显示结果。因此,我需要您的帮助,以解释为什么我无法在搜索查询中获取文本框值。以下是所有代码......谢谢

PHP主要功能($ _POST [' secretcode']值永远不会回到wpdb选择查询它始终为空...如果我显示所有结果,查询都有效)

function wp_hello()
{

$secretcode=$_POST['secretcode'];

//main logic
global $wpdb;
//echo jsonencode($secretcode);

$sql = "SELECT * FROM wp_store_locator WHERE sl_description = '$secretcode' ";
$results = $wpdb->get_results($sql) or die(mysql_error());
$takeit = array();
foreach( $results as $result ) {

 $takeit[]= $result->sl_description;

    }
echo json_encode($takeit);
die();

}

HTML

<form action="" method="get" id="myform">
<input type="text" name="secretcode" style="height:30px;" id="secret"/>
<button id="Submit" type="submit">SUBMIT </button>
</form>
<div id="result"></div>

JQuery的

jQuery(document).ready(function() {  


  jQuery("#myform").submit(function(e){//form is intercepted
        e.preventDefault();
        var sentdata = jQuery(this).serialize();
var secretkey = jQuery('input[name="secretcode"]').val();
        alert(sentdata);

jQuery.post(yes.ajaxurl,{action : 'wp_hello'},
            function( response) {//start of funciton
        var rez = JSON.parse(response);
                jQuery("#result").append(rez);

                return false;
            } //end of function
        );
}); // submit end here
});

php的其他入队和本地化代码

add_action( 'init', 'add_myjavascript' ); 
function add_myjavascript(){  

add_action( 'wp_ajax_wp_hello', 'wp_hello' );
add_action( 'wp_ajax_nopriv_wp_hello', 'wp_hello');
// register & enqueue a javascript file called globals.js
wp_register_script( 'globals', get_stylesheet_directory_uri() . "/js/ajax-implementationn.js", array( 'jquery' ) ); 
wp_enqueue_script( 'globals' );

// use wp_localize_script to pass PHP variables into javascript
wp_localize_script( 'globals', 'yes', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );


} 

谢谢大家!

1 个答案:

答案 0 :(得分:0)

您没有发送secretCode参数,只发送了一个名为action的参数。

jQuery(function ($) {
    $("#myform").submit(function (e) { //form is intercepted
        e.preventDefault();

        //serialize the form which contains secretcode
        var sentdata = $(this).serializeArray();

        //Add the additional param to the data        
        sentdata.push({
            name: 'action',
            value: 'wp_hello'
        })

        //set sentdata as the data to be sent
        $.post(yes.ajaxurl, sentdata, function (rez) { //start of funciton
            $("#result").append(rez);

            return false;
        } //end of function
        ,
        'json'); //set the dataType as json, so you will get the parsed data in the callback
    }); // submit end here
});