sourcetip

Wordpress에서 ajax를 호출하는 방법

fileupload 2023. 3. 9. 22:16
반응형

Wordpress에서 ajax를 호출하는 방법

ajax 콜 출력은 항상 0을 출력으로 나타내고 있습니다.이유는 알 수 없습니다.

»functions.php는 이 있습니다.

function get_data() {
    $abc = '1';
    $result = $wpdb->get_results("SELECT * FROM ".$wpdb->options ." WHERE option_name LIKE '_transient_%'");
    echo  $result; //returning this value but still shows 0
    wp_die();
}

add_action( 'wp_ajax_nopriv_get_data', 'get_data' );
add_action( 'wp_ajax_get_data', 'get_data' );

그리고 내 에이잭스 콜은 자바스크립트로 되어있어

$('body').on("click", ".re-reset-btn", function(e){

    var panel = $('#re-compare-bar');       

    $.ajax({
             type : "GET",
             dataType : "json",
             url : "/wp-admin/admin-ajax.php",
             data : {action: "get_data"},
             success: function(response) {

                   alert("Your vote could not be added");
                   alert(response);
                }
        });   

    $("#re-compare-bar-tabs div").remove(); 
    $('.re-compare-icon-toggle .re-compare-notice').text(0); 

});

플러그인을 사용하지 않고 워드프레스로 Ajax 콜을 하고 있는데 전달받은 것을 얻지 못하고 있습니다.$abc를 출력해도 0으로 표시됩니다.

백엔드에는 WordPress 자체에 의해 정의된 글로벌 아약스루 변수가 있습니다.

이 변수는 프런트엔드에서 WP에 의해 생성되지 않습니다.즉, 프런트엔드에서 AJAX 콜을 사용하는 경우 이러한 변수를 직접 정의해야 합니다.

이를 위해서는 wp_localize_script를 사용하는 것이 좋습니다.

AJAX 콜이 my-ajax-script.js 파일에 있다고 가정하고 다음과 같이 이 JS 파일에 wp_localize_script를 추가합니다.

function my_enqueue() {
      wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/my-ajax-script.js', array('jquery') );
      wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
 }
 add_action( 'wp_enqueue_scripts', 'my_enqueue' );

JS 파일을 현지화한 후 JS 파일에서 my_ajax_object 개체를 사용할 수 있습니다.

jQuery.ajax({
    type: "post",
    dataType: "json",
    url: my_ajax_object.ajax_url,
    data: formData,
    success: function(msg){
        console.log(msg);
    }
});

사실 Word Press에는 관리팩스에 접속할 수 있는 편리한 기능이 포함되어 있습니다.

요구 사항들

  • wp-admin에서는 아무것도 할 필요가 없습니다.js 라이브러리는 항상 로드됩니다.
  • 프런트 엔드에서 스크립트를 큐잉해야 합니다.wp-util 이렇게요.

    add_action( 'wp_enqueue_scripts', 'my_enqueue_function' );
    
    function my_enqueue_function() { 
        // Option 1: Manually enqueue the wp-util library.
        wp_enqueue_script( 'wp-util' );
    
        // Option 2: Make wp-util a dependency of your script (usually better).
        wp_enqueue_script( 'my-script', 'my-script.js', [ 'wp-util' ] );
    }
    

JS 라이브러리

에는 wp-util이 되어 .wp.ajaxAjax:

 wp.ajax.post( action, data ).done( okCallback ).fail( errCallback )

예:

wp.ajax.post( "get_data", {} )
  .done(function(response) {
    alert("Your vote could not be added");
    alert(response);
  });

PHP 코드

까지는 만들 .wp_ajax_*PHP php php php php php php php php php php php 。

add_action( 'wp_ajax_nopriv_get_data', 'my_ajax_handler' );
add_action( 'wp_ajax_get_data', 'my_ajax_handler' );

function my_ajax_handler() {
    wp_send_json_success( 'It works' );
}

힌트:

Ajax 응답의 경우 WordPress는 두 가지 기능을 제공합니다.

wp_send_json_success( $my_data ) 및 - 두 함수 모두 JSON 개체를 반환하고 요청을 즉시 종료합니다(즉,exit;)

저도 같은 문제가 있었어요.저는 워드프레스를 처음 접했습니다.따라서 모든 신규 학습자가 Ajax가 WordPress에서 어떻게 통화하는지 이해할 수 있도록 여기서 설명합니다.

첫째, 함수에서 함수를 만듭니다.php 파일은 wp-content/selected_folder 아래에 있습니다.여기서 selected_theme 테마명을 선택합니다.

질문에서는 ''라는 으로 함수가 .get_data();

function get_data() {
    echo  "test";
    wp_die();  //die();
}

add_action( 'wp_ajax_nopriv_get_data', 'get_data' );
add_action( 'wp_ajax_get_data', 'get_data' );

위의 두 줄에서

  1. add_action을 됩니다.두 매개 변수를 , 첫 는 '아까부터'입니다.첫 번째는wp_ajax_nopriv_get_data"get_data" "get_data" 입니다.섹션 get_data에 대해 설명합니다.
  2. 번째에서는 두첫 번째는 add_action입니다.첫 번째는wp_ajax_get_data여기서 get_data를 원하는 값으로 대체할 수 있습니다.section 파라미터는 호출하는 함수명인 get_data 입니다.

여기서 사용자가 로그인하지 않은 경우 wp_ajax_nopriv를 호출하고 사용자가 로그인했을 때 wp_ajax를 호출합니다.

jQuery.ajax({
    type: "post",
    dataType: "json",
    url: "/wp-admin/admin-ajax.php", //this is wordpress ajax file which is already avaiable in wordpress
    data: {
        action:'get_data', //this value is first parameter of add_action
        id: 4
    },
    success: function(msg){
        console.log(msg);
    }
});

를 사용하여 admin-ajax.php를 추가합니다.admin_url('admin-ajax.php');

<script type="text/javascript">
    $('body').on("click", ".re-reset-btn", function(e){

        var panel = $('#re-compare-bar');

        $.ajax({
            type : "POST",
            dataType : "json",
            url : "<?php echo admin_url('admin-ajax.php'); ?>",
            data : {action: "get_data"},
            success: function(response) {
                alert("Your vote could not be added");
                alert(response);
            }
        });

        $("#re-compare-bar-tabs div").remove();
        $('.re-compare-icon-toggle .re-compare-notice').text(0);

    });
</script>
<form type="post" action="" id="newCustomerForm">

    <label for="name">Name:</label>
    <input name="name" type="text" />

    <label for="email">Email:</label>
    <input name="email" type="text" />

    <label for="phone">Phone:</label>
    <input name="phone" type="text" />

    <label for="address">Address:</label>
    <input name="address" type="text" />

    <input type="hidden" name="action" value="addCustomer"/>
    <input type="submit">
</form>
<br/><br/>
<div id="feedback"></div>
<br/><br/>

기능들.php

wp_enqueue_script('jquery');

function addCustomer() {

    global $wpdb;

    $name = $_POST['name'];
    $phone = $_POST['phone'];
    $email = $_POST['email'];
    $address = $_POST['address'];

    if ( $wpdb->insert( 'customers', array(
        'name' => $name,
        'email' => $email,
        'address' => $address,
        'phone' => $phone
    ) ) === false ) {
        echo 'Error';
    } else {
        echo "Customer '".$name. "' successfully added, row ID is ".$wpdb->insert_id;
    }
    die();
}
add_action('wp_ajax_addCustomer', 'addCustomer');
add_action('wp_ajax_nopriv_addCustomer', 'addCustomer');

자바스크립트

<script type="text/javascript">
jQuery('#newCustomerForm').submit(ajaxSubmit);

function ajaxSubmit() {
    var newCustomerForm = jQuery(this).serialize();

    jQuery.ajax({
        type: "POST",
        url: "/wp-admin/admin-ajax.php",
        data: newCustomerForm,
        success: function(data){
            jQuery("#feedback").html(data);
        }
    });

    return false;
}
</script>

만약 당신이 그것을 얻으려면0응답에서는, Ajax 콜이 정상적으로 동작하고 있는 것을 의미합니다.단, get_data 함수에 $wpdb를 글로벌 변수로 정의하지 않았습니다.에러 로그를 확인해 주세요.에러가 표시되고 있는 것이 틀림없습니다.시험:

function get_data() {
    global $wpdb;
    $abc = '1';
    $result = $wpdb->get_results("SELECT * FROM ".$wpdb->options ." WHERE option_name LIKE '_transient_%'");
    echo  $result; //returning this value but still shows 0
    wp_die();
}

스텝 1: 함수 파일에 다른 'wp_enqueue_script' 또는 'wp_enqueue_style' 파일을 추가해야 하는 아약스 'wp_enqueue_script' 파일을 추가합니다.

wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/my-ajax- script.js', array('jquery') );
    wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );

스텝 2: 이제 응답을 얻을 함수를 만들어야 합니다.다음 예시를 참조해당 함수는 다음과 같습니다.

 add_action('wp_footer','add_ajaxex_in_footer');
   function add_ajaxex_in_footer()
    { ?>

<script type="text/javascript">
    jQuery('#sbmtbtn').click(function(){
    jQuery.ajax({
    type:"POST",
    url:my_ajax_object.ajax_url,
    data: {action:'my_special_ajax_call_enroll_cours'},
    success:function(res){
     console.log(res);
    }
   });
  });</script><?php 
 }

3단계: 이제 쿼리를 작성해야 하는 함수를 만들어야 합니다.

add_action('wp_ajax_my_special_ajax_call_enroll_cours', 'enroll_cours');
add_action('wp_ajax_nopriv_my_special_ajax_call_enroll_cours', 'enroll_cours');

 function enroll_cours()
 { 
     echo "Here you van write Query or anything"; 
     exit;
 }

=> onClick 버튼 후 Ajax 요청을 실행하려면 버튼 ID를 전달하기만 하면 됩니다.

<input type="button" id="sbmtbtn" name="Save">

다음은 WordPress에서 AJAX 호출을 일반 바닐라 js로 작성하는 방법입니다.

var urlToajax=jsajaxe_S.ajaxurl;


function P_lifg(){ 

 var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
  document.getElementById("demo").innerHTML = this.responseText;
  document.getElementById("demo2").innerHTML = urlToajax+ "?action=testfirst";
  }
};


  xmlhttp.open("GET", urlToajax+ "?action=testfirst", true);    
  xmlhttp.send(0);

}

이 블로그에서 기능을 추가하는 방법을 참조하십시오.이 작업을 수행하기 위한 php 및 template html, 또한 jQuery와 달리 vanilja js에 데이터가 없고 액션만 있는 이유를 설명합니다.

함수의 add_actions를 나타냅니다.php:

add_action( 'wp_ajax_testfirst', __NAMESPACE__ .'\\FunctionTF' );       
add_action( 'wp_ajax_nopriv_testfirst', __NAMESPACE__ .'\\FunctionTF');

여기에 이 함수를 추가합니다.이 함수는 다음과 같습니다.

 function FunctionTF(){

 exit( "Hola hola" );
    
} 

이유를 참조하십시오. 내 블로그의 "종료" 코드

여기에 이 html을 일부 wp-template에 추가합니다.

 <div id="demo"></div>
 <div id="demo2"></div>
 <button id="spesial_button" onclick="P_lifg()">I am spesial</button>

자세한 것은, https://praybook2.blogspot.com/2021/03/AJAX-plain-vanilla-js-wp-and-namespace.html 를 참조해 주세요.

언급URL : https://stackoverflow.com/questions/43557755/how-to-call-ajax-in-wordpress

반응형