Hướng dẫn wordpress pass javascript variable to php - wordpress chuyển biến javascript sang php

  • Tôi đã gọi một cái móc từ trang nhận được và muốn thu thập dữ liệu JS từ người dùng và chuyển nó trở lại PHP để sử dụng biến.

    Tôi đã cố gắng gọi với:

    
          jQuery.ajax[{
          type: "POST",
          url: window.location,
          data: { test:"test" },
          success: function[ data ] {
            alert[data];
          }
        }];
    

    Và điều này để có được

    echo $_POST['test'];

    Nhưng nó không hoạt động, dữ liệu được đăng thành công nhưng PHP không thể đọc các biến. Có ai biết làm thế nào để làm điều đó không? Cảm ơn bạn đã giúp đỡ
    Anybody know how to do it? Thanks for your help

    • Chủ đề này đã được sửa đổi 1 năm, 11 tháng trước bởi Steven Stern [Sterndata].
      Steven Stern [sterndata].

  • Đôi khi, làm việc trên tùy chỉnh trong WordPress, chúng ta cần chuyển giá trị PHP cho giá trị JavaScript hoặc JavaScript cho PHP. Hôm nay tôi sẽ chia sẻ cách chuyển giá trị JavaScript cho PHP trong WordPress.how to pass JavaScript value to PHP in WordPress.

    Hãy nói rằng chúng tôi có một biểu mẫu tiêu chí trong đó người dùng có thể tìm nạp dữ liệu theo tiêu chí. Dữ liệu sẽ truy vấn từ cơ sở dữ liệu bằng PHP và hiển thị trên màn hình như hiển thị bên dưới. Chúng tôi thực sự lấy ví dụ từ một trong những bài đăng của tôi có tên là Building WordPress Plugin với khái niệm hướng đối tượng.

    Ví dụ - Mẫu tiêu chí [ảnh chụp màn hình]

    Trang giao dịch với biểu mẫu tiêu chí

    Thêm móc hành động

    Trong PHP, chúng tôi sẽ thêm các hành động dưới đây.PHP, we will add the actions below.

    // add the scripts and style on the backend ONLY
    add_action[ 'admin_enqueue_scripts', array[ $this,'reports_admin_scripts'] ];  
    add_action[ 'wp_ajax_get_job_applications', array[ $this, 'get_job_applications'] ];

    Nơi để thêm móc hành động

    Bạn có thể thêm hook hành động trong các chức năng.php trong chủ đề hiện tại của bạn. Hoặc bạn có thể thêm móc hành động trong tệp plugin chính của bạn.

    Tạo một cuộc gọi lại chức năng cho hook script

    Tiếp theo, chúng tôi sẽ tạo ra các kiểu và tập lệnh trong báo cáo của chúng tôi_admin_scripts Gọi lại mà chúng tôi nối chức năng này thông qua hành động admin_enqueue_scripts.reports_admin_scripts function callback which we hook this function via admin_enqueue_scripts action.

    /**
      * add jquery ui datepicker widget
      * 
      */
    public function reports_admin_scripts[] 
    {
      // add the script and style on our plugin only
      if [isset[$_GET['page']] && $_GET['page'] === 'mct-reports'] {
    
        // # load style
        // load datepicker plugin style
        // @link //gist.github.com/miwahall/7028640
        wp_enqueue_style['mct-reports-bootstrap-style', MCT_REPORTS_PLUGIN_URL . 'css/datepicker-bootstrap3.css' ];
        
        // load datatable plugin style
        wp_enqueue_style['mct-reports-datatable-style', MCT_REPORTS_PLUGIN_URL . 'lib/DataTables/datatables.min.css' ];
    
        // load custom style
        wp_enqueue_style['mct-reports-style', MCT_REPORTS_PLUGIN_URL . 'css/mct-reports.css' ];
    
    
    
        // # load scripts
        // datepicker plugin
        wp_enqueue_script[ 'mct-reports-datepicker' , MCT_REPORTS_PLUGIN_URL . 'js/jquery-ui.min.js', array['jquery'] ,true];
        wp_enqueue_script[ 'mct-reports' , MCT_REPORTS_PLUGIN_URL . 'js/mct-reports.js', array['jquery','mct-reports-datepicker'] ,true];
        wp_localize_script[ 'mct-reports', 'mctReportsAjax', array[
            'ajaxurl' => admin_url['admin-ajax.php']
        ]];
        // Important note: wp_localize_script[] is a key function that we use for passing the JS values[JS values from the mct-reports.js] to PHP via ajax. In wp_localize_script function, you must use the same handle of attached script[mct-reports.js], in this case, it's 'mct-reports'. So WP can send the correct JS values. wp_localize_script[] must be called AFTER the registered script using wp_register_script[] or wp_enqueue_script[]. Finally, you need to pass the ajax script from WP core. So that in your JS script, you can use ajax.
    
        // datatable plugin
        wp_enqueue_script[ 'mct-reports-datatable' , MCT_REPORTS_PLUGIN_URL . 'lib/DataTables/datatables.min.js', array['jquery'] ,true];
      }
    }

    Lưu ý quan trọng

    WP_LOCISIning_script [] là một hàm chính mà chúng tôi sử dụng để chuyển các giá trị JS [các giá trị từ báo cáo mct.js] sang PHP thông qua AJAX. Trong chức năng WP_LOCISIZE_SCRIPT, bạn phải sử dụng cùng một tay cầm của tập lệnh đính kèm [mct-reports.js], trong trường hợp này, nó có thể báo cáo lại MCT. Vì vậy, WP có thể gửi các giá trị JS chính xác. WP_LOCISION_SCRIPT [] phải được gọi sau tập lệnh đã đăng ký bằng wp_register_script [] hoặc wp_enqueue_script []. Cuối cùng, bạn cần chuyển tập lệnh Ajax từ WP Core. Vì vậy, trong tập lệnh JS của bạn, bạn có thể sử dụng AJAX.mct-reports‘. So WP can send the correct JS values. wp_localize_script[] must be called AFTER the registered script using wp_register_script[] or wp_enqueue_script[]. Finally, you need to pass the ajax script from WP core. So that in your JS script, you can use ajax.

    Biểu mẫu gửi từ Frontend và Nonce

    Đối với một biểu mẫu gửi từ Frontend, bạn nên tạo Nonce cho biểu mẫu của mình, sau đó kiểm tra Nonce trước khi sử dụng dữ liệu đã gửi. Đó là một lý do bảo mật.

    Dưới đây là mã ASGREEPPHP: WP_LOCISION_SCRIPT [‘MTM-script,‘ MTM_AJAXOBJ
    PHP code:
    wp_localize_script[ ‘mtm-script’, ‘mtm_ajaxobj’, array[
    ‘ajaxurl’ => admin_url[‘admin-ajax.php’],
    ‘ajaxnonce’ => wp_create_nonce[‘load_more_posts’]]
    ];

    Mã JS: Trong mã AJAX, bạn sẽ vượt qua ‘mtm_ajaxobj.ajaxnonce, làm đối tượng dữ liệu cùng với thuộc tính hành động bạn đang truyền. Dưới đây là một ví dụ.
    In ajax code, you will pass the ‘mtm_ajaxobj.ajaxnonce’ as data object along with action attribute you are passing. Below is an example.
    data: {
    action: ‘PHP_function_name’,
    security: ‘mtm_ajaxobj.ajaxnonce’
    }
    The security label can be any name you want.

    Mã PHP: Trong chức năng PHP_FUNCTION_NAME, bạn có thể kiểm tra Ajaxnonce với chức năng WP_VERIFY_NONCE. Dưới đây là một ví dụ. }}
    In PHP_function_name function, you can check the ajaxnonce with wp_verify_nonce function. Below is an example.
    function PHP_function_name {
    // Verify nonce
    if [! wp_verify_nonce[$_POST[‘ajaxnonce’], ‘load_more_posts’]] {
    return false;
    }
    }

    Tạo một cuộc gọi lại chức năng cho Ajax Hook

    Tiếp theo, chúng tôi sẽ gọi chức năng GET_JOB_APPLACES thông qua AJAX. Hãy nhớ rằng, chúng tôi kết nối chức năng GET_JOB_APPLACES với hành động WP_AJAX_GET_JOB_APPLACES.get_job_applications function via ajax. Remember, we hook the get_job_applications function with wp_ajax_get_job_applications action.

    /**
      * get data from db
      */
    public function get_job_applications[] 
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'job_applications'; // do not forget about tables prefix
        $status = 'active';
        $orderby = 'date_created, firstname';
        $order = 'asc';
    
        // # the parameters from ajax are $_POST['start_date'] and $_POST['end_date']
        // set the query condition and convert date format for using in query
        $start_date = strtr[ $_POST['start_date'], '/', '-' ];
        $start_date = strtotime[$start_date];
        $start_date = date['Y-m-d',$start_date];  
    
        $end_date = strtr[ $_POST['end_date'], '/', '-' ];
        $end_date = strtotime[$end_date];
        $end_date = date['Y-m-d',$end_date];
    
        // get current user id
        $user_id = get_current_user_id[];        
        
        // get user role
        $user_meta = get_userdata[ $user_id ];
        $user_roles = $user_meta->roles;
    
        // query data from the custom table
        $query_result = $wpdb->get_results[
          $wpdb->prepare["SELECT * FROM $table_name WHERE status = '$status' AND date_created BETWEEN '$start_date' AND '$end_date' ORDER BY %s %s", array[ $orderby, $order ] ]
          , OBJECT];
        
        
        // add post meta into the query result so we can use these values in ajax call
        foreach[ $query_result  as $value ] {
            // get post meta
            $job_localtion_id = get_post_meta[ $value->id_job_opp, 'job_location', true ];
            $position_type_id = get_post_meta[ $value->id_job_opp, 'job_type_position', true ];
            $specialty_id = get_post_meta[ $value->id_job_opp, 'job_specialty', true ];    
    
            // get post title from custom post type
            $job_location = get_the_title[ $job_localtion_id ];
    
            // get term name by ID
            $position_type = get_term_by[ 'id' , $position_type_id, 'job_types_position' ]->name;
            $specialty = get_term_by[ 'id' , $specialty_id, 'job_specialty' ]->name;
    
            // add 3 additional columns for row grouping table
            $value->job_location = [ trim[$job_location]==='' ? 'No Location' : $job_location ];
            $value->position_type = [ trim[$position_type]==='' ? 'No Position Type' : $position_type ];
            $value->specialty = [ trim[$specialty]==='' ? 'No Specialty' : $specialty ];
        }
    
        // echo as json object to ajax calling
        echo json_encode[$query_result];
    
        // # MUST add wp_die[] here to avoid the 0 number that appends to the result json object and send back to ajax calling
        wp_die[];
    }

    Luôn trả về dưới dạng JSON và thêm wp_die [] ở cuối hàm

    Đối với hàm PHP mà chúng tôi sẽ nhận được các giá trị JS thông qua AJAX, nếu bạn muốn trả lại giá trị trở lại AJAX, bạn phải trả về giá trị dưới dạng JSON. Nguyên nhân, trong AJAX, bạn cũng phải đặt kiểu dữ liệu là JSON. Khi kết thúc hàm PHP, bạn phải thêm wp_die [] để tránh số 0 sẽ nối vào đối tượng JSON kết quả. Vui lòng cố gắng sử dụng hàm WordPress [wp_die []] thay vì hàm PHP [die []]. Vì vậy, tất cả các móc và bộ lọc sẽ hoạt động đúng.

    Giải thích cho các hành động biểu mẫu tiêu chí

    • Sau khi người dùng nhấp vào nút báo cáo tại biểu mẫu Tiêu chí, sự kiện nhấp chuột được kích hoạt.criteria form, the click event is triggered.
    • Trong mã JavaScript, chúng tôi sẽ gửi các giá trị tiêu chí từ biểu mẫu Tiêu chí đến hàm PHP thông qua AJAX bằng mã JavaScript bên dưới. Mã JavaScript nằm trong MCT-reports.js mà chúng tôi đã giới thiệu trong Reports_Admin_Scripts Chức năng gọi lại.mct-reports.js which we enqueue in reports_admin_scripts function callback.
    jQuery[document].ready[function [$] {
    
      // ------- START Report button is triggered --------- //
      $['#btn_report'].on['click', function [e] {
    
        // some JS code...
    
        // # getting db via PHP function
        // we pass the javascript values via data attribute. this way, get_job_application function[PHP function] can use these value. In PHP, you can access the javascript values by $_POST variable.
        // Note that: we use $_POST because in ajax, we use post method. If you use get method in ajax, in PHP, you will use $_GET to access the passing values.
        $.ajax[{
          method: 'post',
          url: mctReportsAjax.ajaxurl,  // don't forget to pass ajax which we send by data object via wp_localize_script[]. otherwise the ajax is not working.
          cache: false,
          dataType: 'json',  // we need the result back to ajax with json data type.
          data: {
            action: 'get_job_applications',  // we hook get_job_application function to wp_ajax_get_job_applications earlier.
            start_date: $txtStartDate.val[].trim[],  // send JS value
            end_date: $txtEndDate.val[].trim[],  // send JS value
          },
          beforeSend: function [] {
            // some JS code...
          },
          success: function [response] {
             // display the result data from response variable into the screen
             // it will return the response as json which we set the dataType as json.
          },
          error: function [xhr, status, error] {
            var err = eval["[" + xhr.responseText + "]"];
            console.log[err.Message];
          }
        }];
    
      }];
      // ------- END Report button is triggered --------- //
    
    }];
    • Trong hàm GET_JOB_APPLACES [mã PHP], chúng tôi sẽ truy vấn dữ liệu được lọc bởi các giá trị tiêu chí.get_job_applications function[PHP code], we will query the data which is filtered by the criteria values.
    • Chúng tôi chuyển đổi dữ liệu thành JSON để quay lại AJAX.
    • Tại AJAX, chúng tôi sẽ hiển thị dữ liệu kết quả trong hàm thành công.

    Sự kết luận

    Chuyển các giá trị JS cho PHP, về cơ bản chúng tôi gửi các giá trị từ phía trước đến phụ trợ. Không dễ để làm trong mã PHP bình thường. Nhưng với WordPress, nó cung cấp chức năng wp_localize_script mà bạn có thể chuyển các giá trị JS thông qua AJAX một cách dễ dàng. Trong hướng dẫn này, chúng tôi chỉ sử dụng AJAX tại phần phụ trợ. Để chúng tôi sử dụng hook wp_ajax _ {$ action}. Nếu bạn muốn sử dụng AJAX trên frontend cho người dùng đăng xuất, bạn sẽ sử dụng wp_ajax_nopriv _ {$ action} hook. Bạn có thể sử dụng cả hai móc nếu bạn muốn sử dụng AJAX trên cả Frontend và phụ trợ.WordPress, it provides the wp_localize_script function which you can pass the JS values via ajax easily. In this tutorial, we use ajax at the backend only. So that we use the wp_ajax_{$action} hook. If you want to use ajax on the frontend for logged-out users, you will use wp_ajax_nopriv_{$action} hook. You can use both hooks if you want to use ajax on both frontend and backend.

    Tôi có thể chuyển biến JavaScript sang PHP không?

    Cách để chuyển biến JavaScript sang PHP là thông qua yêu cầu. Loại URL này chỉ hiển thị nếu chúng ta sử dụng hành động Get, hành động bài đăng ẩn thông tin trong URL. Phía máy chủ [PHP]: Trên trang PHP phía máy chủ, chúng tôi yêu cầu dữ liệu được gửi bởi biểu mẫu và hiển thị kết quả. $ result = $ _get ['dữ liệu'];through a request. This type of URL is only visible if we use the GET action, the POST action hides the information in the URL. Server Side[PHP]: On the server side PHP page, we request for the data submitted by the form and display the result. $result = $_GET [ 'data' ];

    Làm thế nào sử dụng biến JavaScript trên cùng một trang trong PHP?

    Bạn có thể dễ dàng nhận được giá trị biến JavaScript trên cùng một trang trong PHP. Hãy thử codel sau. var res = "thành công"; var res = "success";

    Bài Viết Liên Quan

    Chủ Đề