2017-07-01 75 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