dshgnt2008 2018-04-04 15:05
浏览 71
已采纳

将AJAX数据作为JSON保存到WP表

I've setup a function and some jQuery that takes a value from a form a user submits, and sends it to the database successfully in it's own table. However, I'm trying to set it up to save the data as JSON instead (so as to make sure my WP table doesn't balloon to an unbearable size in the future).

Function here:

function search_modifications_callback() {

// Ensure we have the data we need to continue
if( ! isset( $_POST ) || empty( $_POST ) || ! is_user_logged_in() ) {

    header( 'HTTP/1.1 400 Empty POST Values' );
    echo 'Could Not Verify POST Values.';
    exit;
}

$user_id = get_current_user_id();  // Get our current user ID
$search_term  = $_POST['saved_search'];

update_user_meta( $user_id, 'saved_search', $search_term ); // Add our user meta


wp_update_user( array(
    'ID'            => $user_id
) );

exit;
}
add_action( 'wp_ajax_nopriv_search_ss', 'search_modifications_callback' );
add_action( 'wp_ajax_search_ss', 'search_modifications_callback' );

jQuery here:

// Form submission listener
jQuery( '#save-search' ).click( function() {

    // Grab our post meta value
    var ss_val = jQuery( '#save_search_term' ).val();
    var user_id = jQuery( '#user_id' ).val();

    // Do very simple value validation
    if( jQuery( '#save_search_term' ).val() ) {
        jQuery.ajax( {
            url : ajax_url,                 
            type: 'POST',                   
            data: {                         
                action  : 'search_ss',          
                id: user_id,
                'saved_search': ss_val,       
            }
        } )
        .success( function( results ) {
            console.log( 'User Meta Updated!' );
            alert('Search saved!');
        } )
        .fail( function( data ) {
            console.log( data.responseText );
            console.log( 'Request failed: ' + data.statusText );
        } );

    } else {

    }

    return false;   // Stop our form from submitting
} );

I understand that instead of using 'update_user_meta' I should probably create an object instead, but am unsure how to properly set that up from here.

Open to other suggestions as well. Thanks!

  • 写回答

1条回答 默认 最新

  • 普通网友 2018-04-04 16:22
    关注

    Taking your comment above into consideration, if you plan to save up to N search terms per user then I'd do something like this:

    function search_modifications_callback() {
    
        // Ensure we have the data we need to continue
        if( ! isset( $_POST ) || empty( $_POST ) || ! is_user_logged_in() ) {
            header( 'HTTP/1.1 400 Empty POST Values' );
            echo 'Could Not Verify POST Values.';
            exit;
        }
    
        $user_id = get_current_user_id();  // Get our current user ID
        $search_term  = $_POST['saved_search'];
    
        // Get user's saved search terms
        $user_saved_search_terms = get_user_meta( $user_id, 'saved_search' );
    
        // User has some previously saved search terms
        if (
            $user_saved_search_terms
            && is_array( $user_saved_search_terms )
            && !empty( $user_saved_search_terms )
        ) {
    
            // This search term doesn't exist in our saved search terms array yet, so let's add it
            if ( !in_array($search_term, $user_saved_search_terms) ) {
                $user_saved_search_terms[] = $search_term;
    
                /**
                 * You'll want to add here some logic
                 * to limit the array to N search terms
                 *
                 * For example:
                 */
    
                /*
                // User has more than 5 saved search terms already,
                // let's remove the oldest one
                if ( count($user_saved_search_terms) > 5 ){
                    $user_saved_search_terms = array_shift( $user_saved_search_terms );
                }
                */
            }
        } // User does not have any search terms saved yet
        else {
            $user_saved_search_terms = array( $search_term );
        }
    
        // Finally, save the data
        update_user_meta( $user_id, 'saved_search', $user_saved_search_terms );
    
        // What is this for?
        wp_update_user( array(
            'ID'            => $user_id
        ) );
    
        exit;
    }
    add_action( 'wp_ajax_nopriv_search_ss', 'search_modifications_callback' );
    add_action( 'wp_ajax_search_ss', 'search_modifications_callback' );
    

    This way, you still will have only one saved_search record per user in your database.

    Please note that this code hasn't been tested, so if you have any questions / comments let me know.

    By the way, what if the user isn't logged-in? Are you checking for this scenario somewhere?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题