Chuyên mục
Java - JQuery Wordpress

JQuery gọi hàm PHP trong WordPress

JQuery gọi hàm PHP, một cách để truyền dữ liệu động từ server đến client một cách nhanh chóng. Trong Wordpress, việc này khá đơn giản bởi nó hỗ trợ khá nhiều, hầu như có sẵn để chúng ta dùng.

JQuery gọi hàm PHP, một cách để truyền dữ liệu động từ server đến client một cách nhanh chóng. Trong WordPress, việc này khá đơn giản bởi nó hỗ trợ khá nhiều, hầu như có sẵn để chúng ta dùng.

JQuery gọi hàm PHP trong WordPress
JQuery gọi hàm PHP trong WordPress

Viết một hàm PHP trong /[MY_THEME]/functions.php

Viết một hàm PHP gần như một hàm thông thường, và một chút khác biệt:

  • Cho phép thực thi bởi AJAX
  • Giá trị trả về là JSON object

Ví dụ 1: hàm sau đây get 1 post và trả về: title và excerpt

<?php
// 2 dòng add_action cho phép gọi hàm từ ajax
add_action( 'wp_ajax_nopriv_vnlink_get_post', 'vnlink_get_post' );
add_action( 'wp_ajax_vnlink_get_post', 'vnlink_get_post' );

function vnlink_get_post(){
    $postid = $_POST['postid'];
    $postid = intval($postid);
    if( $postid ) {
        $post = get_post($postid);
        if( $post ) {
            wp_send_json_success(array(
                'title'     => $post->post_title,
                'excerpt'   => $post->post_excerpt
                ));
            exit;
        } else {
            wp_send_json_error( 'Không tìm thấy bài viết!' );
            exit;
        }
    }
    wp_send_json_error( 'postid phải > 0' );
    exit;
    
    // Tham số truyền vào hàm wp_send_json_success và wp_send_json_error là giống nhau
    // Có thể là 1 array hoặc 1 string
    // cũng chính là giá trị trả về cho JQuery / Ajax
}

Tại template/template_part sẽ thực hiện như sau:

<div class="entry-title"></div>
<div class="entry-excerpt"></div>
<div class="error"></div>

<script>
    jQuery(document).ready(function($){
            var $pid = 100;
            var $params={'action': 'vnlink_get_post', 'postid': $pid}
            $.ajax({
                url: '<?php echo admin_url('admin-ajax.php'); ?>',
                type: 'POST',
                dataType: "json",
                data: $params,
                beforeSend: function(){
                    // thực hiện lệnh trước khi gọi hàm PHP 
                },
                success: function(response){
                    if(response.success){
                        // được trả về bởi hàm wp_send_json_success
                        $( '.entry-title' ).html(response.data.title);
                        $( '.entry-excerpt' ).html(response.data.excerpt);
                    }else{
                        // được trả về bởi hàm wp_send_json_error
                        $( '.error' ).html(response.data);
                    }
                },
                error: function (request, status, error) {
                    console.log(error);
                }
                
            });
    });
</script>

Lưu ý khi xuất dữ liệu Json data (dữ liệu trả về từ hàm PHP):

  • Nếu truyền vào tham số array() cho hàm wp_send_json_success hoặc wp_send_json_error, thì truy xuất là: response.data.key_name
  • Nếu tham số truyền vào là một chuỗi, thì truy xuất là: response.data

Ví dụ 2: cập nhật thông tin 1 user

Điểm khác nhau với ví dụ 1 là tham số truyền đến hàm PHP trong WordPress nhiều hơn 1 (2 tham số). Khi truyền nhiều hơn nữa các tham số thì chỉ cần thực hiện cú pháp tương tự.

<?php
add_action( 'wp_ajax_nopriv_vnlink_update_address', 'vnlink_update_address' );
add_action( 'wp_ajax_vnlink_update_address', 'vnlink_update_address' );
function vnlink_update_address(){
    // bạn cần một số thao tác kiểm tra điều kiện trước khi thực hiện update
    [......]
    
    $userid =   $_POST['userid'];
    $address =  $_POST['address'];
    
    // kiểm tra hợp lệ của dữ liệu truyền vào ở đây
    [......]
    
    $metaid = update_user_meta($userid, 'Address', $address);
    if( $metaid > 0 ) {
        wp_send_json_success('Cập nhập địa chỉ thành công!');
        exit;
    }
    wp_send_json_error('Không thể cập nhật địa chỉ!');
    exit;
}

Kế tiếp, JQuery gọi hàm PHP

<div class="message"></div>

<script>
    jQuery(document).ready(function($){
            var $userid = 100;
            var $address = 'Nguyễn Huệ, Q.1, TP. HCM';
            var $params={'action': 'vnlink_update_address', 'userid': $userid, 'address': $address}
            $.ajax({
                url: '<?php echo admin_url('admin-ajax.php'); ?>',
                type: 'POST',
                dataType: "json",
                data: $params,
                beforeSend: function(){
                    // thực hiện lệnh trước khi gọi hàm PHP 
                },
                success: function(response){
                    if(response.success){
                        // được trả về bởi hàm wp_send_json_success
                        $( '.message' ).html(response.data);
                    }else{
                        // được trả về bởi hàm wp_send_json_error
                        $( '.message' ).html(response.data);
                    }
                },
                error: function (request, status, error) {
                    console.log(error);
                }
                
            });
    });
</script>

Các hàm được sử dụng trong ví dụ JQuery gọi hàm PHP

Trả lời