ajax in wordpress to pass data

2019-04-17 13:37发布

People, I have a code that I need to include in Wordpress. Can you please tell me how to change these codes to work in wordpress???

Non wordpress code is:

JS

$(document).ready(function() {
  $('#example').ratings(5).bind('ratingchanged', function(event, data) {
    $('#example-rating').text(data.rating);

     $.ajax({
        url : 'rating_plugin.php',
        type : 'POST',
        data : { rating : data.rating },
        success : function(response){
        console.log("successfull");     

        }
    });
  });
});

PHP

if ($_SERVER['REQUEST_METHOD'] == 'POST')
      {
       echo $_POST['rating']'
      }

Thanks.

1条回答
爷的心禁止访问
2楼-- · 2019-04-17 14:37

In wordpress in general its better to use the built in ajax functions that come with wordpress

so add the rating to your functions.php (something on these lines)

function rateAjax()
    {
     require( get_template_directory() . '/rating_plugin.php' );  
    } 
    add_action('wp_ajax_nopriv_PostAjax', 'rateAjax');
    add_action('wp_ajax_PostAjax', 'rateAjax');

Jquery:

$(document).ready(function() {
  $('#example').ratings(5).bind('ratingchanged', function(event, data) {
    $('#example-rating').text(data.rating);

     $.ajax({
        url : '<?php echo admin_url('admin-ajax.php');?>',
        type : 'POST',
        data: { action : 'PostAjax', rating : data.rating },  
        success : function(response){
        console.log("successfull");     

        }
    });
  });
});
查看更多
登录 后发表回答