0

I would like to know how can I dynamically change content of a div when I click on a button, using PHP.

With the code below, I can print out the posts of that category (videos) with a custom HTML, thanks to "echo".

foreach ($posts as $post) { 

        $image = get_post_meta($post->ID, 'thumbnail', true);
        $imageData = base64_encode(file_get_contents($image));

        $post_date = get_the_date('', $post->ID);
        $post_content = get_post($post_id);
        $content = $post_content->post_content;


            echo '<li class="tab" data-tab="tab-6">';
                echo '<div class="miao">';
                    echo '<div class="img"> <img style="max-width:100px;" src="data:image/jpeg;base64,'.$imageData.'"> </div>';
                    echo '<div class="title">' . the_title( "<h6>", "</h6>" ) . '</div>';
                    echo '<div class="who">' . $content .  '</div>';
                    echo '<div class="time">'  . $post_date  . '</div>';
                echo '</div>';
            echo '</li>';

    }   

If I am not clear, please comment below. Thanks

UPDATE

I'm trying to get a response from my Ajax call but it doesn't work. It returns "Error 500"

$.ajax({
           url: '../../wp-content/themes/medical-cure/create_filters.php',
           type: "POST",
           data: {  
                    action: 'create_posts',
                    a: a
                },
            success:function(response) {
                console.log(response);
                $(".sub-tabs-a").append(response);
             },
            error: function(e, xhr, opt){
                alert("Error requesting " + opt.url + ": " + xhr.status + " " + xhr.statusText);
            } 
        })

UPDATE 2 - D.Dan - Hint

The code below shows the "View" and its "shows" all posts required from Ajax call:

<?php get_header(); ?>
<?php
//echo "POST VARIABLE: " . $_POST['action'];

if (is_string($_POST['a'])) {

  $name = $_POST['a'];
  //echo $name;

}

if ($_POST['action'] == 'create_posts') {
  create_posts();
} 

/*
function get_category_id($cat_name){
  $term = get_term_by('name', $cat_name, 'category');
  return $term->term_id;
}

$custom_category_id = get_category_id('Video Gallery - HPB');*/

//echo "string";

function create_posts() {

  //echo "appena";

try {
  $posts = get_posts( [
        'numberposts' => 5,
        'category' => 81, 
        'orderby' => 'date',
        'order' => 'DESC'
    ]
  );
} catch (Exception $e) {
  echo $e;
}

  //echo $posts;

  $response = '';

  //echo "entrato";

  foreach ($posts as $post) {  
    // the_content();

    $image = get_post_meta($post->ID, 'thumbnail', true);
    $imageData = base64_encode(file_get_contents($image));

    $post_date = get_the_date('', $post->ID);
    // $post_content = the_post();
    $post_content = get_post($post_id);
    $content = $post_content->post_content;



      $response .= '<li class="tab" data-tab="tab-6">';
    $response .= '<div class="miao">';
      $response .= '<div class="img"> <img style="max-width:100px;" src="data:image/jpeg;base64,'.$imageData.'"> </div>';
      $response .= '<div class="title">' . the_title( "<h6>", "</h6>" ) . '</div>';
      $response .= '<div class="who">' . $content .  '</div>';
      $response .= '<div class="time">'  . $post_date  . '</div>';
    $response .= '</div>';
      $response .= '</li>';

    //$response[] = ['img' => $imageData, 'content' => $content, 'date' => $date];

  }  
    
    echo $response;
}
?>

The code below shows it's the Ajax call:

$('.cat-item').click(function(){
        // var tab_id = $(this).attr('data-tab');
        $('.cat-item').removeClass('current_selected');
        // $('.tab-content').removeClass('current');
        $(this).addClass('current_selected');
        // $("#"+tab_id).addClass('current');
        var a = $(".current_selected")[0].innerText;
        console.log(a);

  

    // $('.cat-item').click(function() {

    //     // var search_filter = $(this).find('current_selected').text();

    //     // console.log(search_filter);

    //     $(this).load("/wp-content/themes/medical-cure/test.php");
    // })
        /*$.ajax({
           url: '../../wp-content/themes/medical-cure/create_filters.php',
           type: "POST",
           data: {  
                    action: 'create_posts',
                    a: a
                },
            success:function(response) {
                console.log(response);
                $(".sub-tabs-a").append(response);
             },
            error: function(e, xhr, opt){
                alert("Error requesting " + opt.url + ": " + xhr.status + " " + xhr.statusText);
            } 
        })*/


        //JQuery function 
            var ajax_url = ajax_params.ajax_url;
            var data = {
                'action': 'create_posts',
                'a': a
            };

        $.post(ajax_url, data, function(response) {
            $(".sub-tabs-a").append(response);
        });

The code below shows the method from where I add the script and is located in "functions.php"

function add_our_script() {

wp_register_script( 'memberlist-js', get_template_directory_uri() . '../../wp-content/themes/medical-cure/video-filters.php', array( 'jquery' ), '', true );
wp_localize_script( 'memberlist-js', 'ajax_params', array( 'ajax_url' => '/wp-content/themes/medical-cure/create_filters.php' ) );
wp_enqueue_script( 'memberlist-js' );

}
add_action( 'wp_enqueue_scripts', 'add_our_script' );
  • 1
    If you use PHP, you'll have to reload the page. You could have the button go to the same URL with a query string, and then echo different content based on the query string. Or, if you don't want people to have to reload the page, you could go with JavaScript instead, using an Ajax call to truly "dynamically" update the page. – WebElaine Jan 24 '18 at 14:12
  • True that, I have updated my question, Thanks for your hint – Elle Jan 24 '18 at 15:34
  • 1
    It would be better to not define the url like that. You can add an url to one of your js files with wp_localize_script ( for example the admin-ajax.php) which is part of WP, and that way you can process the whole thing in functions through WP. – D. Dan Jan 24 '18 at 15:42
  • @D.Dan Ok thanks, but can you please give me an example about the usage of "wp_localize_script"? thanks man. – Elle Jan 24 '18 at 15:47
  • 1
    About wp localize script. Basically you need the ajax code to be in a js file. The you can pass it through WP the location of admin-ajax.php. And if you specify the action like in the above example then in your functions.php you can make a function that that ajax call will call. And the contents of create filters.php can be in that function. – D. Dan Jan 24 '18 at 18:50
0

If you were to localize admin-ajax.php then if you add these functions to functions.php:

    add_action( 'wp_ajax_nopriv_create_posts', 'my_create_posts' );
    add_action( 'wp_ajax_create_posts', 'my_create_posts' );

function my_create_posts(){
    if (is_string($_POST['a'])) {

  $name = $_POST['a'];
  //echo $name; and soo on...

}
}

The 'action' in the ajax call is needed for defining to which ajax call to pair your function, defined in add_action.

Other thing is I don't understand what are you doing with a, because $name is not used anywhere.

And if you want to check is a is being passed why not use isset($_POST['a'])

You would need to change in localize script the ajax url to:

'ajax_url' => admin_url( 'admin-ajax.php' )
  • "a" is the variable that I'm trying to "pass through". Next step will be from 'category' => 81 to 'category' => a – Elle Jan 25 '18 at 11:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.