2016-09-27 72 views
0

我有這個變量$type,我希望它是monthyear。 應該通過按div進行更改。Ajax更改php變量

我試着用ajax調用創建一個onclick事件。

ajax呼叫和variable是在同一個腳本(index.php

內部的onclick功能:

var curr_class = $(this).attr('class'); 


$.ajax({ 
    type: "POST", 
    url: "index.php", 
    data: { 
     type: curr_class 
    }, 
    dataType: 'text', 
    success: function(data) { 
     // Test what is returned from the server 
     alert(data); 
    } 
}); 

但警告返回整個 HTML頁面。 當我CONSOLE.LOG數據(創建var data = { type:curr_class }) and console.log *that data* it returns類型= month`(這是正確的)

,而我只是希望它返回個月

所以頁面我頂可撥打

if(empty($_POST['type'])){ 
    $type = 'month'; 
} else { 
    $type = $_POST['type']; 
} 

並更改PHP變量,所以我可以在我的腳本的其餘部分使用它。

但我怎麼能ACC忘記這個?

隨着親切的問候,

+0

你不應該讓一個Ajax請求你的'index.php',如果你不希望的'index.php'返回的內容。相反,編寫一個單獨的腳本來處理你的ajax請求。 – jeroen

+0

但是,如何更改* PHP變量*呢? @jeroen – EG47

+1

沒有* PHP變量*這樣的東西。每個變量只在腳本執行期間設置,在腳本完成後它不存在(除非使用會話,數據庫等來存儲信息)。 – jeroen

回答

0

爲你發送請求到同一頁面,從而導致整個頁面是返回。你必須把它發送到另一個頁面,從該頁面返回變量類型

if(empty($_POST['type'])){ 
$type = 'month'; 
} else { 
    $type = $_POST['type']; 
    echo $type; 

保持在單獨的文件中的代碼,使一個AJAX調用該網頁

+0

只使用jquery代碼而不是php bcoz我們無法在php – ImBS

+0

中獲得運行時變量值,以及如何*在代碼的不同部分使用該變量? – EG47

+0

將其保存在會話可變數據庫中 – Shahrukh

0
//Try This It's Work 
<a href="Javascript:void(0);" class="btn-my" data-title="month">Get Value</a> 
<a href="Javascript:void(0);" class="btn-my" data-title="year">Get Value</a> 
$(".btn-my").click(function(){ 
    var curr_class = $(this).data('title'); 
    $.ajax({ 
     type: "POST", 
     url: "index.php", 
     data: { 
      type: curr_class 
     }, 
     dataType: 'text', 
     success: function(data) { 
      // Test what is returned from the server 
      alert(data); 
     } 
    }); 
}); 
+0

返回整個html頁面 – EG47

+0

現在您可以查看該代碼 – ImBS

0

做,在這種方式

確保數據在DOM中可用。然後做下一步。

if(empty($_POST['type'])){ 
    $type = 'month'; 
    $monthOrDate = '<span id="date">'.$type.'</span>'; 
    echo $monthOrDate; 
} else { 
    $type = $_POST['type']; 
     $monthOrDate = '<span id="date">'.$type.'</span>'; 
    echo $monthOrDate; 
} 

然後在JavaScript中使用

$('#date').click(function(){ 
    alert($(this).val()); // if not then comment it use below one 
    alert($(this).text()); 
});