2013-01-31 24 views
1

我想顯示具有基於文章ID使用模態窗口的特定信息的HTML表單,但我努力傳遞價值/ ID到我的自定義PHP函數。 所以,這裏的HTML/PHP的一部分jquery和php更新使用模式對話框

while(...) : 
     <a href="#" id="$row['id']" class="button">Edit</a> 
    endwhile; 

現在JS,

$("a.button").on("click", function() { 
     $("#modal").reveal(); 
     return false; 
    }); 

HTML和PHP函數

<div id="modal"> 
     <?php echo showForm($needThisIDbasedOnClick); ?> 
    </div> 

希望這一切讓你的感覺,我掙扎的得到一定的id並傳遞給php函數

我試過刪除了return false;和href屬性<a href="?id=17"> ...並獲取值使用$ _GET ['id'] showForm($_GET['id'])但這種解決方案只是不按我想要的方式工作,它重新加載頁面...

+0

您是否嘗試過使用AJAX,當用戶點擊文章,然後顯示它之後加載模式DIV內容? –

+0

showForm($ needThisIDbasedOnClick); ..它顯示了什麼? – shnisaka

+0

@Mt。 Shneiders是的,我試過了,這就是我想要的,但無法得到相關的ID爲了顯示值的形式 –

回答

2

頁面與你PHP代碼在服務器端執行。解釋PHP,然後將內容發送到您的瀏覽器。在收到數據後,你的JS代碼在客戶端執行(感謝你的瀏覽器的JS機器)。

如果你想顯示信息,而無需重新加載任何東西,你有2個解決方案:

  • PHP的處理過程中嵌入在網頁中的所有信息,並保持它的隱藏,顯示出良好的一個用JS代碼依賴於點擊鏈接。 (錯誤的解決方案)

  • 使用帶參數中ID的AJAX請求,該參數將調用返回指定行信息的新短PHP腳本。

如果我恢復過程可能是:

1)的第一個要求是在你的主腳本main.php

2)頁面顯示所有項目(僅嵌入ID)並且包含信息容器(隱藏且空的)

示例

<!-- Your list of link with article ID --> 
<div> 
    <a class="articleLink" id="123" href="#">View</a> 
    <a class="articleLink" id="124" href="#">View</a> 
    <a class="articleLink" id="125" href="#">View</a> 
</div> 

<!-- The bloc that will contain info and will be shown in a popup later (hidden) --> 
<div id="divInfo"> 
    <input type="text" name="name" value=""/> 
    <input type="text" name="description" value=""/> 
</div> 

<script> 

    $(document).ready(function() { 

     // add listener to all link 
     $(".articleLink").click(function(mouseEvent) { 

      // Retrieve the article ID     
      var myId = $(this).attr('id'); 

      // Ajax call with the id of the link 
      // onSuccess, fill the divInfo and show it 
      $.ajax('getInfo.php', { 
       dataType: 'json', 
       type: 'POST', 
       data: { 
        articleId: myId 
       }, 
       success: function(data, status, xhrObj) { 

        // The data is received, update the info container 
        $("#divInfo input[name=name]").val(data.name); 
        $("#divInfo input[name=description]").val(data.desc); 

        // Show the div in a popup 
        //... 
       } 
      }); 

      return false; 
     }); 
    }); 

</script> 

3)你點擊一個鏈接,它會運行一個AJAX調用第二個PHP腳本:getInfo.php,給指定的ID

4)腳本檢索數據庫中的數據並最終返回信息(以JSON爲例)

假設您的PHP getInfo。PHP將返回JSON

{"name":"an article name","description":"the article description"} 

注意:您可以在PHP從陣列產生容易JSON與功能

json_encode() 

5)你的Ajax調用的方法的onSuccess被調用時收到的數據,你可以使用這些數據來填寫你的表單(這是唯一的,已經存在於頁面中 - 並且被隱藏)。

好運

+0

感謝兄弟這可能會幫助很多 –