Reload a part of php page without refreshing whole page

前端 未结 1 375
栀梦
栀梦 2021-01-27 07:30

i\'m using Wordpress as content management system and my template has a div with box class, and contains a dropdown list . my goal is getting the value of this drop

相关标签:
1条回答
  • 2021-01-27 08:25
       <select id="select-dropdown">
         <option value="1">Item 1</option>
         <option value="2">Item 2</option>
         <option value="3">Item 3</option>
         <option value="4">Item 4</option>
        </select> 
    

    For this to achieve you should have knowledge of Admin Ajax in wordpress.

    Admin Ajax: in your header.php

    <script type="text/javascript">
     var ajax_url = '<?php echo admin_url('admin-ajax.php'); ?>';
    </script>
    

    in you custom js file

    my-custom.js, enqueue the js file

    jQuery(document).ready(function(){
      jQuery(body).on('change','#select-dropdown', function(){
         var selected_item  = jQuery(this).val();
         jQuery.ajax({
           type: "POST",
           url: "ajax_url",
           data: {
                 action: 'load_posts',
                 selected_item: selected_item,
               },
           success: function(res){
             console.log(res);
             //append the result in frontend
             jQuery('.box').html(res);
            },
    
    
         })
      })
    });
    

    In your function.php

    function _boom_load_posts(){
     //get your results here as per selected option
     if(!empty($_POST['selected_item'])){
      $selected_item = $_POST['selected_item'];
      $output = '';
      //rest of the code as per selected_item, store result in $output
      $args = array(
    
        "meta_query" => array(
                array(
                    'key' => 'meta',
                    'value' => '$select_value',
                    )
            )
    );
    
    query_posts( $args );
    if ( have_posts() ) : while ( have_posts() ) : the_post();
    
            $output .= get_the_content();
    endwhile; else: 
    
             $output .= "<p>sorry no post found with this value.</p>"
    
      endif; 
    
      echo $output;//you result here
      die(1);
     }
    }
    add_action('wp_ajax_load_posts', '_dot1_load_posts');
    add_action('wp_ajax_no_priv_load_posts', '_dot1_load_posts');
    

    make the required changes, as I can't post the whole code for you, make some efforts and the above code will help you get an idea that how it's going to work.

    0 讨论(0)
提交回复
热议问题