简体   繁体   中英

Wordpress ajax is not calling function in functions.php

I wrote an ajax call in the front end. I wrote the server side in functions.php

function updateCont(){
    global $wpdb;
    $post_id = $_POST['post_id'];
    $key = $_POST['key'];
    $value = $_POST['value'];

    update_post_meta($post_id, $key, $value);
    echo $value;
    die();
}
add_action('wp_ajax_updateCont', 'updateCont');
add_action('wp_ajax_nopriv_updateCont', 'updateCont'); 

My jquery is as follows

jQuery.ajax({
            type:"POST",
            url: "<?php echo admin_url('admin-ajax.php'); ?>",
            data: {"post_id":<?php echo get_the_ID();?>, "key":"top_left_content", "value":"new content"},
            success:function(data){
                console.log(data);// is 0
            }
        });

However, the data returned from the ajax call is always "0" When I searched for it, people say my function is not loaded into wordpress. I don't understand what to do here.

The worpress hook needs a action variable with the function name passed to the php Try:

   jQuery.ajax({
  type: "POST",
  url: "<?php echo admin_url('admin-ajax.php'); ?>",
  data: {
    action: 'updateCont',
    "post_id": <?php echo get_the_ID();?>,
    "key": "top_left_content",
    "value": "new content"

  },
  success: function (data) {
    console.log(data); // is new content
  }
});

You are missing "action": "updateCont" from your ajax data. action specifies what WP ajax action you are targeting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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