2016-05-21 31 views
0

我的腳本是:沒有獲得ajax值到一個PHP變量?

<script> 
$(document).ready(function(){ 

    $(".states").on('click','option',function(){ 

     var selValue = $("select[id='stateId'] option:selected").val(); 

      $.post('<?php echo get_template_directory_uri(); ?>/ajax.php', 'val=' + selValue, function (response) { 

       $variable = response; 
       //alert("Variable value is: "+$variable); 

      }); 

    }); 

}); 

選擇活動地點 選擇國家 選擇國家 選擇城市
<div class="col-sm-9"> 


     <?php 
     $a2 = $variable; 
     print_r($a); die; 
     $args = array(
      'meta_key' => 'state', 
      'meta_value' => $a2, 
      'post_type' => 'event', 
      'posts_per_page' => -1 
     ); 
     $the_query = new WP_Query($args); 

     // The Loop 
     if ($the_query->have_posts()) { 
      echo '<ul>'; 
      while ($the_query->have_posts()) { 
       $the_query->the_post(); 
       echo '<li><h2>' . get_the_title() . '</h2></li><br>'; 
      } 
      echo '</ul>'; 
     } else { 
      echo 'no posts found'; 
     } 
     /* Restore original Post Data */ 
     wp_reset_postdata(); 

     //echo do_shortcode('[qem]'); ?>   

    </div> 
</div> 
+0

更改''val ='+ selValue'爲{val:selValue} –

+0

實際上我想根據狀態過濾帖子。並通過ajax post()獲取狀態值。我需要把它變成一個php變量。或者將這個值傳遞給數組值''meta_value'=> $ a2「。 – Saral

+0

首先你需要改變我的建議,並且比它自己填充的變量要多。但如果它是一個PHP變量,你不能。 –

回答

0

做這樣的事情:

你需要像{ val : selValue }送價值,並在ajax.php你必須存儲的值$_POST當你經過它IKE $.post,絕返回響應。

返回響應後,它被設置爲H1標籤文本。

阿賈克斯:

$.post('<?php echo get_template_directory_uri(); ?>/ajax.php', { val : selValue }, function (response) { 
    variable = response; 
}); 

PHP

$variable = "<script>document.write(variable);</script>"; 

你可以試試這個,讓我知道發生什麼事。

+0

是的,先生在h1中獲得選定的值。但如何可以將它傳遞到的$ args =陣列( \t \t \t \t 'meta_key'=> '狀態', \t \t \t \t 'meta_value'=> $ A2, \t \t \t \t 'post_type'=>'事件」, \t \t \t \t 'posts_per_page'=> -1 \t \t \t);在「$ a2」的地方 – Saral

+0

** _你無法按照你想的方式完成這項工作。_ ** –

+0

但您可以使用表單值來提交,以便您可以在該數組中獲取它。 –