Passing variable with Ajax in WordPress

I am trying to pass variable when user click on link to page single.php

Here is my code

Read More
<a href='#' id='8' class='clickme' style='font-weight:bold;color:white;font-size:16px;'>";

In function.php, I put this code:

/////////////////////////////////////////////////////////
add_action( 'wp_head', 'myajaxcall' );

function myajaxcall(){ ?>
<script type="text/javascript">

jQuery(document).ready(function($) {
        jQuery(".clickme").click( function() {

    // We'll pass this variable to the PHP function example_ajax_request
   var id = $('.clickme').attr('id');

    // This does the ajax request
    $.ajax({
        url: <?php echo admin_url( 'admin-ajax.php'); ?>,
        data: {
            'action':'get_sidebar_request',
            'page_id' : id
        },

      //  beforeSend: function (jqXHR, settings)
      //  {
        //   alert( url = settings.url);
          //},

        success:function(data){
            alert(data);
        },

        error: function(errorThrown){
            //alert(errorThrown);

        }
    });
});
});
</script>
<?php }

add_action( 'wp_ajax_get_sidebar_request', 'idAjax' );
add_action( 'wp_ajax_nopriv_get_sidebar_request', 'idAjax' );

function idAjax()
    {
     require( get_template_directory() . '/single.php' );  
    } 

/////////////////////////////////////////////////////////////////////

And in file `single.php, when I want to get the passed variable, I put this code:

$page_id=0;
$page_id =  $_REQUEST['page_id'];
echo "page_id=".$page_id;

But the variable isn’t passing to single.php. I try to echo it, and nothing happens.

Can you help me?

Related posts

Leave a Reply

2 comments

  1. You can use Network tool in Google Chrome to debug and see sent/received data.
    If “id” is not null when you send it, try to use $_POST to output your data in your php file, like this :

    var_dump($_POST);
    
  2. check this :

     $.ajax({
        url: <?php echo admin_url( 'admin-ajax.php'); ?>,
        data: {
            'action':'get_sidebar_request',
            'page_id' : id
        },
    

    and add double quote to url value

    $.ajax({
        url: "<?php echo admin_url( 'admin-ajax.php'); ?>",
        data: {
            'action':'get_sidebar_request',
            'page_id' : id
        },
    

    if you don’t see your ajax call, it’s a javascript error in your code.

    Do you have any error in browser Console ?