2015-09-25 5 views
0
<form action="" method="post"> 
    <div id="wrapper"> 
     <p> 
      <label> Please Enter the JCID No </label> 
      <input type="text" name="txt_jcid_no" id="txt_jcid_no"/> 
      <input type="submit" name="submit" value="Search" class="bg-primary"/> 
     </p> 
     <table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%"> 
      <thead> 
       <tr> 
        <th>Name</th> 
        <th>Position</th> 
        <th>Office</th> 
        <th style="display: none"></th> 
        <th style="display: none"> </th> 
        <th style="display: none"></th> 
       </tr> 
      </thead> 
      <?php 
      if (isset($_POST['submit'])) { 
       echo 'Hi'; 
       echo '<tbody>'; 
       echo '</tbody>'; 
      } 
      ?> 
     </table> 
     <!-- /#page-content-wrapper --> 
    </div> 
</form> 

Дорогие друзья я хочу, чтобы мой PHP код для отображения значения на той же странице, так что я делаю здесь, это получить input(txt_jcid_no) от пользователя и обработать запрос и отображать значение в табличном формате , Но когда я использую функцию if isset(), она отображает значение, пока страница загружает i.e перед нажатием кнопки submit, но мое требование - это значение, которое должно отображаться в таблице после нажатия кнопки отправки.PHP Показать результат на той же странице

+2

использовать AJAX для этого – guradio

+0

Вы видели окно подтверждения браузера с вопросом о данных для отправки во время загрузки страницы –

+0

$ _POST ['submit'] не будет установлен до тех пор, пока вы не разместите форму. Просто обновите страницу и получите чек (не повторная отправка формы). – MaK

ответ

0

Вы могли бы пойти одним из двух способов.

Первый будет включать некоторую логику, определить бы была ли отправлена ​​форма для себя, как так:

<body> 
    <?php if($receivedResult): ?> 
    <form action="" method="post"> 
     <div id="wrapper"> 
      <p> <label> Please Enter the JCID No </label> 
      <input type="text" name="txt_jcid_no" id="txt_jcid_no"> 
      <input type="submit" name="submit" value="Search" class="bg-primary"> 
     </p> 
     <table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%"> 
      <thead> 
       <tr> 
        <th>Name</th> 
        <th>Position</th> 
        <th>Office</th> 
        <th style="display: none"></th> 
        <th style="display: none"> </th> 
        <th style="display: none"></th> 
       </tr> 
      </thead> 
     </table> 
    </div> 
    <?php else; ?> 
     <h1>you submitted a result</h1> 
     ... 
    <?php endif; ?> 
</div> 
<!-- /#page-content-wrapper --> 
</div> 
</body> 
</form> 

или, вы могли бы установить конечную точку AJAX и имеют вид не выполнить стандартную почту и вместо этого отправлять и получать данные с этой конечной точки AJAX и динамически обрабатывать ответ в Javascript (в этом примере используется jquery).

<body> 
    <form action="" method="post"> 
     <div id="wrapper"> 
      <label> Please Enter the JCID No </label> 
      <input type="text" name="txt_jcid_no" id="txt_jcid_no"> 
      <input type="submit" name="submit" value="Search" class="bg-primary"> 
     </div> 
    </form> 

    <script> 
     $('input[type=submit]').submit(function (ev) { 
      ev.preventDefault(); 

      .ajax({ 
       url: 'some/end/point', 
       type: 'post', 
       contentType: 'application/x-www-form-urlencoded', 
       success: function(data, textStatus, jQxhr){ 
        alert(data); 
       }, 
       error: function(jqXhr, textStatus, errorThrown){ 
        console.log(errorThrown); 
       } 
      }); 
     }); 
    </script> 
</body> 
</form> 
0

Как правило, после отправки формы и обновления страницы будет повторно отправлена ​​форма. Поэтому вам нужно нажать enter из адресной строки. Вы можете поместить следующий код под тегом </thead>. Либо вы не хотите идти с Ajax, либо не включать другую страницу.

<?php 
if (isset($_POST['submit'])) 
{ 
    $con = mysql_connect('localhost','username','password') or die(mysql_error());; 
    mysql_select_db('db',$con) or die(mysql_error()); 
    //process your query here 
    //e.g. $sql = "selelct * FROM tablename WHERE columnname = ". $_POST['txt_jcid_no']; 
    //fetch query as per your choice 
    //and print outpout here.. 

echo '<tbody>'; 
foreach($result as $_value){ 
    echo "<tr>"; 
    echo "<td>". $_value['name'] . "</td>"; 
    echo "<td>". $_value['position'] . "</td>"; 
    echo "<td>". $_value['office'] . "</td>"; 
    echo "</tr>"; 
} 
echo '</tbody>'; 
mysql_close(); 
} 
?> 
1

Было бы лучше всего сделать это с помощью ajax. Вы все еще можете иметь весь код на одной странице, и просто иметь Аякса вызов второй экземпляр страницы, как так:

Working demo

<?php 
// at the top of your file have your response logic 
if (isset($_POST['txt_jcid_no'])){ 
    echo '<tbody><tr><td colspan="6">I was echoed here because you submitted the form</td></tr></tbody>'; 
    exit; // dont load the rest of the page if this was hit, we just want the above to be returned 
} 
?> 
<!doctype html> 
<html> 
<head> 
<meta charset="UTF-8"> 
<title>Untitled Document</title> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> 
</head> 
<body> 
<form action="index.php" method="post"> 
    <div id="wrapper"> 
    <p> 
    <label> Please Enter the JCID No </label> 
    <input type="text" name="txt_jcid_no" id="txt_jcid_no"> 
    </p> 
</form> 
<input type="button" value="Search" id="submit" class="bg-primary"> 
<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%"> 
    <thead> 
    <tr> 
     <th>Name</th> 
     <th>Position</th> 
     <th>Office</th> 
    </tr> 
    </thead> 
    <tbody id="result"> 
    </tbody> 
</table> 
</div> 
</div> 
<!-- /#page-content-wrapper --> 
</div> 
<script> 
$(function(){ 
    $('#submit').click(function(){ 
      var dataString = 'txt_jcid_no=' + $('#txt_jcid_no').val();; 

      $.ajax({ 
      type: "POST", 
      url: "withajax.php", 
      data: dataString, 
      success: function(result) { 
       $('#result').html(result); 
      }, 
      error: function() { 
      } 
     }); 


    }); 
}); 
</script> 
</body> 
</html> 

Если вы действительно хотите сделать это путем размещения форма, это будет работать:

Working demo

<!doctype html> 
<html> 
<head> 
<meta charset="UTF-8"> 
<title>Untitled Document</title> 
</head> 
<body> 
<form action="index.php" method="post"> 
    <div id="wrapper"> 
    <p> 
    <label> Please Enter the JCID No </label> 
    <input type="text" name="txt_jcid_no" id="txt_jcid_no"> 
    <input type="submit" name="submit" value="Search" class="bg-primary"> 
    </p> 
</form> 
<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%"> 
    <thead> 
    <tr> 
     <th>Name</th> 
     <th>Position</th> 
     <th>Office</th> 
     <th style="display: none"></th> 
     <th style="display: none"> </th> 
     <th style="display: none"></th> 
    </tr> 
    </thead> 
    <?php 
if (isset($_POST['submit'])) 
{ 
echo '<tbody><tr><td colspan="6">I was echoed here because you submitted the form</td></tr></tbody>'; 
} 
?> 
</table> 
</div> 
</div> 
<!-- /#page-content-wrapper --> 
</div> 
</body> 
</html> 
Смежные вопросы