2017-07-01 72 views
0

每次運行此代碼時,都會收到「VALUE IS EMPTY」消息。意味着變量不會從Jquery傳遞給PHP變量$value。我需要將它傳遞給PHP。幫我!無法從Jquery發送值到PHP

#popup是一個div它出現在單擊表TR時)

HTML + PHP代碼:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

<div id="popup"> 

    <?php 
     if (isset($_POST['val']) && !empty($_POST['val'])) 
     { 
     $value = $_POST['val']; 
     echo $value; 
     } 
     else{ 
      echo "VALUE IS EMPTY"; 
      //each time I get this msg.. means it won't take the variable value to PHP 
     } 
    ?> 
</div> 

的JQuery/Javascript代碼:

$(document).ready(function(){ 
    $('#tableview tbody tr').click(function(){ 

    var a=[]; 
    $(this).find('td').each(function(){ 
    a.push($(this).text()); 

    }); 

      $('#popup').show(); 
      $.ajax({ 
       url:'addfile.php', 
       data:{'val': a[1] }, 
       type:'post', 
       success:function(res){ 
       //Is there an error due to this function? or what? 
       } 

      }); 
}); 
}); 

- >沒有必要插入代碼的表..希望這可以澄清我的問題

+0

你使用模型彈出或簡單的div? –

+0

所以'console.log(a)',你看到了什麼? –

+0

@MuhammadUsman ..很簡單div –

回答

1

OK,所以這裏有一個快速,基本原則:

你的HTML頁面,讓我們將其命名爲index.html的(PHP腳本不同!):

// index.html 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

<div id="popup"></div> 
<script> 
$(document).ready(function(){ 
    $('#tableview tbody tr').click(function(){ 

     var a=[]; 
     $(this).find('td').each(function(){ 
      a.push($(this).text()); 
     }); 

     $('#popup').show(); 
     $.ajax({ 
      url:'addfile.php', 
      // HERE's A CRITICAL CHANGE: 
      // val MUST NOT be in quotes. You're creating a plain object here 
      data:{ val: a[1] }, 
      // you can change that from type to method (default is get) - though type is an alias for method, so both should work. 
      method:'post', 
      success:function(res){ 
       // here you have your data back from php, do with that what ever you need. 
       console.log(res); // will show value of a[1] in console 
       // my guess is, you want to show it in #popup 
       $('#popup').html(res); 
      }, 
      error: function(error, status, errorString) { 
       // allways check for possible errors! 
       console.log(error); 
       console.log(errorString); 
      } 
     }); 
    }); 
}); 
</script> 

你的PHP腳本

<?php 
// adfile.php 
if (isset($_POST['val']) && !empty($_POST['val'])) { 
     $value = $_POST['val']; 
     echo $value; 
} else { 
     echo "VALUE IS EMPTY"; 
} 
// don't add a closing tag.... 

最後:請閱讀有關ajax如何工作並閱讀manuals

+0

謝謝..我讀到了關於ajax和我發現的是'ajax代碼'中的'url'指定了你希望變量被測試的地方,例如你將變量傳遞給另一個php頁面,並且在變量完成一些處理之後,以$ _POST ['val']的形式返回變量。 但在這裏,我不希望變量傳遞給另一個頁面。我在同一頁面上,想要jQuery變量被髮送到我點擊一個TR的同一頁面,所以我也從AJAX代碼中刪除了'url'部分,但是沒有工作 –

+0

檢查這個,你就完全明白了。 imgur.com/ye4Y1Wd.png 屏幕截圖2:http://i.imgur.com/oj64l5o.png –

+0

您無法將變量傳遞迴同一頁面(如php var),因爲不再涉及php了。頁面加載,沒有更多的PHP ... PHP是在服務器上只有版本。去我的代碼片段,並填寫#popup_after_你得到的變數。 – Jeff