2013-05-17 67 views
3

我有一個名爲bargraph.php的php文件,它創建了一個條形圖圖像。我在使用seprate文件graph.php進口bargraph.php如何使用會話變量創建PHP圖像

<img src='bargraph1.php'> 

但我需要使用會話變量來創建條形圖。我需要傳遞可變年份值以在bargraph.php中生成圖像。但它不顯示圖形。我甚至嘗試過使用ajax。它沒有發生。

graph.php

<script> 
    alert(<?php echo $year ?>); 
    var ids = $year; 

    if (ids == "") { 
     document.getElementById("graph").innerHTML=""; 
     return; 
    } 
    if (window.XMLHttpRequest) { 
     // code for IE7+, Firefox, Chrome, Opera, Safari 
     xmlhttp=new XMLHttpRequest(); 
    } else { 
     // code for IE6, IE5 
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    var data = "year=" + ids ; 
    //var year ="year=" +id1; 
    xmlhttp.open("POST", "bargraph1.php", true); 
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");     
    xmlhttp.send(data); 

    xmlhttp.onreadystatechange=function() { 
     if (xmlhttp.readyState==4 && xmlhttp.status==200) 
     { 
      document.getElementById("graph").innerHTML=xmlhttp.responseText; 
     } 
    } 
</script> 

bargraph1.php

我使用下面的代碼:

$year = $_POST['year']; 
$sql = "SELECT dt,dist,cal FROM demo where YEAR(dt)='$year'"; 
$result = mysql_query($sql,$con); 
+0

爲什麼不通過GET提供年,即'bargraph1.php?year = 2012'。更簡單,更直觀(每年都有獨特的URL)。 – dtech

+0

我試過使用這個,但仍然是我的一年值沒有得到bargraph1.php..plz建議其他方法,如果可能的話... – shivani

回答

0

由於從AJAX請求默認響應是純文本的,我是不確定您可以使用以下方式顯示圖片:document.getElementById("graph").innerHTML=xmlhttp.responseText;

我建議另一種解決方案寫在磁盤上的圖像,並檢索JS圖片: 在你bargraph1.php

$img = /* Image creation*/ 
$filename = "images/generatedFilename.png"; 
imagepng($img, $filename); 
echo $filename; 

您可以測試你的PHP代碼獨立,以確保它的工作原理之前,請嘗試使用它從JS。

在您的Ajax請求

if (xmlhttp.readyState==4 && xmlhttp.status==200) 
     { 
      var img = new Image(); 
      img.src = xmlhttp.responseText; 
      document.getElementById("graph").appendChild(img); 
     } 

編輯: 檢索年的部分是不是JS有效。

alert(<?php echo $year ?>); 
var ids = <?php echo $year; ?>; 
+0

我的形象越來越顯示,但我想要的是創建條形圖圖像的幫助由用戶提供的年份價值。今年的價值需要傳遞給「bargraph.php」,以便爲特定年份生成圖表。但我無法通過ajax或會話將年份值從「graph.php」傳遞到「bargraph.php」。請幫助 – shivani

+0

我對這個問題的理解不好。要從graph.php到bargraph.php年@dtech建議一個簡單的解決方案'' – Marcassin

+0

我試過使用這個,但仍然是我的年值不會在bargraph1.php..plz中獲取提示其他方法如果可能.. – shivani