LoginSignup
0
0

More than 3 years have passed since last update.

WordPressでjQueryを使ってAjax

Posted at

いつも忘れるので自分の備忘録として。各引数は適宜変更すること。

jsファイルの読み込み

functions.php
wp_register_script( 
    'sample-js', 
    plugins_url( 'js/sample.js', __FILE__ ), 
    array('jquery'), 
    null, 
    true 
);  
wp_enqueue_script('sample-js'); 

$config_array = array( 
    'ajaxURL' => admin_url('admin-ajax.php'), 
    'ajaxActions' => 'sample_response', 
    'ajaxNonce' => wp_create_nonce('sample-nonce'), 
); 
wp_localize_script('sample-js', 'ajaxConf', $config_array); 

読み込むjsファイル

sample.js
$.ajax({
    type: 'POST',
    url: ajaxConf.ajaxURL,
    data: {
        'action': ajaxConf.ajaxActions,
        'nonce': ajaxConf.ajaxNonce,
        'dataType': 'json',
        'name': 'hoge',
        'age': 27
    } 
}) 
.then( 
// 成功時
function (data) { 
    console.log(data); 
}, 
// 失敗時 
function (data, textStatus, jqXHR) {
    console.log(data);
    console.log(textStatus);
    console.log(jqXHR);
}); 

レスポンスの処理

functions.php
add_action( 'wp_ajax_ sample_response', 'sample_response' ); 
add_action( 'wp_ajax_nopriv_sample_response', 'sample_response' ); 

function  sample_response() { 
    $nonce = $_POST['nonce']; 
    if(!wp_verify_nonce($nonce, 'sample-nonce') ) die('Unauthorized request!'); 
    echo json_encode($_POST); 
    die(); 
} 

動かない場合

  • JSONがおかしくないか
  • admin-ajax.phpのIP制限確認
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0