简体   繁体   English

如何在 Wordpress 中调用 ajax

[英]How to call ajax in Wordpress

My ajax call output is always showing 0 as output don't know why我的 ajax 调用输出总是显示 0 作为输出不知道为什么

In functions.php I have this codefunctions.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' );

And my ajax call is in a javascript我的 ajax 调用是在 javascript 中

$('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); 

});

I'm making ajax call in wordpress without use of plugin but not getting what I'm passing.Even If I output $abc still it shows 0.我在不使用插件的情况下在 wordpress 中进行 ajax 调用,但没有得到我正在传递的内容。即使我输出 $abc 仍然显示 0。

In backend there is global ajaxurl variable defined by WordPress itself.在后端有由 WordPress 本身定义的全局 ajaxurl 变量。

This variable is not created by WP in frontend.这个变量不是由 WP 在前端创建的。 It means that if you want to use AJAX calls in frontend, then you have to define such variable by yourself.这意味着如果你想在前端使用 AJAX 调用,那么你必须自己定义这样的变量。

Good way to do this is to use wp_localize_script.这样做的好方法是使用 wp_localize_script。

Let's assume your AJAX calls are in my-ajax-script.js file, then add wp_localize_script for this JS file like so:让我们假设您的 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' );

After localizing your JS file, you can use my_ajax_object object in your JS file:本地化 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);
    }
});

Actually, WordPress comes with a handy function to access admin-ajax.实际上,WordPress 带有一个方便的功能来访问 admin-ajax。

Requirements要求

  • In wp-admin you do not need to do anything, the js library is always loadedwp-admin 中你不需要做任何事情,js 库总是被加载
  • In the front-end you need to enqueue the script wp-util , like this:前端,您需要将脚本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' ] ); }

The JS Library JS 库

The wp-util script contains the wp.ajax object that you can use to make ajax requests: wp-util 脚本包含可用于发出 ajax 请求的wp.ajax对象:

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

Your example:你的例子:

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

PHP code PHP代码

Of course, you still need to create the wp_ajax_* hooks in your PHP script.当然,您仍然需要在 PHP 脚本中创建wp_ajax_*钩子。

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' );
}

Tip:提示:

For Ajax responses WordPress provides two functions:对于 Ajax 响应,WordPress 提供了两个功能:

wp_send_json_success( $my_data ) and wp_send_json_error( $my_data ) - both functions return a JSON object and instantly terminate the request (ie, they exit; ) wp_send_json_success( $my_data )wp_send_json_error( $my_data ) - 这两个函数都返回一个 JSON 对象并立即终止请求(即,它们exit;

<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/>

functions.php函数.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');

javascript javascript

<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>

I had the same problem.我有同样的问题。 I was new to WordPress.我是 WordPress 的新手。 Therefore, I am explaining here so that every new learner can understand how ajax is calling in WordPress.因此,我在这里进行解释,以便每个新学习者都能了解 ajax 是如何在 WordPress 中调用的。

First, create a function in function.php file that resides under wp-content/theme/selected_theme folder.首先,在 wp-content/theme/selected_theme 文件夹下的 function.php 文件中创建一个函数。 Here, selected_theme maybe your theme name.在这里, selected_theme 可能是您的主题名称。

In the above question, a function is created with the name get_data() ;在上面的问题中,创建了一个名为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' );

in the above two lines,在上面两行中,

  1. The add_action method is used to implement the hook. add_action 方法用于实现钩子。 Here, I am passing the two parameters, first is wp_ajax_nopriv_get_data .在这里,我传递了两个参数,第一个是wp_ajax_nopriv_get_data Here, you can replace get_data with your choice.在这里,您可以用您的选择替换 get_data。 and the section parameter is get_data which is the function name that you want to call.并且 section 参数是 get_data,它是您要调用的函数名称。
  2. In the second add_action, I am passing the two parameters, first is wp_ajax_get_data .在第二个 add_action 中,我传递了两个参数,第一个是wp_ajax_get_data Here, you can replace get_data with your choice.在这里,您可以用您的选择替换 get_data。 and the section parameter is get_data which is the function name that you want to call.并且 section 参数是 get_data,它是您要调用的函数名称。

Here, wp_ajax_nopriv call if the user is not logged in and wp_ajax called when the user is logged in.这里,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);
    }
});

Add admin-ajax.php by using admin_url('admin-ajax.php');使用admin_url('admin-ajax.php');添加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>

If you are getting 0 in the response, it means your ajax call is working correctly.如果您在响应中得到0 ,则表示您的 ajax 调用工作正常。 But, you have not defined $wpdb as a global variable in your function get_data.但是,您还没有在函数 get_data 中将 $wpdb 定义为全局变量。 Check your error log, you must be seeing error there.检查您的错误日志,您一定在那里看到错误。 Try:尝试:

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();
}

Step 1: Add ajax 'wp_enqueue_script' file in function file where you have to add other 'wp_enqueue_script' or 'wp_enqueue_style' files步骤 1:在函数文件中添加 ajax 'wp_enqueue_script' 文件,您必须在其中添加其他 'wp_enqueue_script' 或 'wp_enqueue_style' 文件

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' ) ) );

Step 2:Now you need to to create function, where you want to get response,using ajax eg below第 2 步:现在你需要创建函数,在那里你想得到响应,使用 ajax 例如下面

 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 
 }

Step 3: Now you have to create function where you have to write query,第 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;
}

=> If you want fire ajax request after onClick button,just pass the button ID => 如果您想在 onClick 按钮后触发 ajax 请求,只需传递按钮 ID

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

Here how to make in plain vanilla js the AJAX call in WordPress.这里如何在普通的 vanilla js 中创建 WordPress 中的 AJAX 调用。

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);

}

See on this blog, what to add functions.php and template html to get this work, also reasonings why there is no data in vanilja js unlike jQuery, but just action 请参阅此博客,添加 functions.php 和模板 html 以完成此工作,以及与 jQuery 不同的 vanilja js 中没有数据的原因,而只是操作

Here add_actions in functions.php:这里在functions.php中add_actions:

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

Add this function over that, here now this function:在上面添加这个函数,现在这个函数:

 function FunctionTF(){

 exit( "Hola hola" );
    
} 

See explanation why? 看解释为什么? code in "exit" in my blog 我博客中“退出”中的代码

Here add this html on some wp-template这里在一些 wp 模板上添加这个 html

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

See rest in: https://praybook2.blogspot.com/2021/03/AJAX-plain-vanilla-js-wp-and-namespace.html 见休息:https://praybook2.blogspot.com/2021/03/AJAX-plain-vanilla-js-wp-and-namespace.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM