2016-03-28 4 views
-1

У меня есть небольшой веб-сайт, в котором используется базовая структура MVC. У меня есть код, который вставляет два значения в базу данных, вставка прекрасно работает без каких-либо проблем, однако, если я хочу видеть новые данные, я обычно должен обновлять страницу или переходить на другую страницу, а затем обратно. Я понимаю, что мне нужно использовать JQuery/Ajax для выполнения этой работы, но не знаю, как это сделать с функциями PHP.Отправить данные и отображение без обновления страницы

Код в вопросе ниже:

PHP Функция:

<?php 
session_start(); 
require_once('../Config/config.php'); 

class Readings 
{ 
    public $dbconn; 

    public function __construct() 
    { 
     $database = new Database(); 
     $db = $database->dbConnection(); 
     $this->dbconn = $db; 
    } 

    public function enterElecReadings($eUsage) 
    { 
     try 
     {  
      $estmt = $this->dbconn->prepare(" 
       INSERT INTO elec_readings 
        (ElecUsage, DateAdded, AccountNumber) 
       VALUES 
        (:eUsage, NOW(), :accNum)"); 
      $estmt->bindparam(":eUsage", $eUsage); 
      $estmt->bindparam(":accNum", $_SESSION['user_session']); 
      $estmt->execute(); 
      return $estmt; 
     } 
     catch(PDOException $e) 
     { 
      echo $e->getMessage(); 
     } 
    } 

    public function getElecReadings(){ 
     try { 
      $stmt = $this->dbconn->prepare("SELECT ElecUsage, DateAdded FROM elec_readings WHERE AccountNumber = '" . $_SESSION['user_session'] . "'"); 
      $stmt->execute(); 
      return $stmt; 
     } catch (Exception $e) { 

     } 
    } 
} 

?> 

страницу, что пользователь увидит:

класс
if(isset($_POST['btn-submitElecUsage'])) 
    { 
     $eUsage = strip_tags($_POST['txtElecUsage']); 

     try { 
      if($newReading->enterElecReadings($eUsage)){  
       $elecNotif[] = "Reading successfully entered."; 
      } 
     } catch (Exception $e) { 
      echo $e->getMessage(); 
     } 
    } 

<div class="elecUsage"> 
     <form id="elecRead" method="POST"> 
      <h2>Electricity Usage</h2> 

      <?php 
      if(isset($elecError)) 
      { 
       foreach($elecError as $elecError) 
       { 
        ?> 
        <div class="alert alert-danger"> 
         <?php echo $elecError; ?> 
        </div> 
        <?php 
       } 
      } 

      if(isset($elecNotif)) 
      { 
       foreach($elecNotif as $elecNotif) 
       { 
        ?> 
        <div class="alert alert-danger"> 
         <?php echo $elecNotif; ?> 
        </div> 
        <?php 
       } 
      } 
      ?> 

      Please enter your latest electricity meter reading: 
      <br> 
      <input type="text" name="txtElecUsage" required/> 
      <br> 
      <input type="submit" name="btn-submitElecUsage" value="Submit"/> 

     </form> 


     <br> 
     Your previous Electricity meter readings: 
     <br> 

     <div id="previousElecReadings"> 
      <br> 

      <table class="tableElec" > 
       <thead> 
        <tr> 
         <th>Usage</th> 
         <th>Date Added</th>  
        </tr> 
       </thead> 
       <?php 
       foreach ($elec_readings as $elec_reading): ?> 
       <tbody> 
        <tr> 
         <td><?php echo $elec_reading['ElecUsage']; ?></td> 
         <td><?php echo $elec_reading['DateAdded']; ?></td> 
        </tr> 
        <?php 
        endforeach; 
        ?> 
       </tbody> 
      </table> 
     </div> 
    </div> 

Контроллер:

<?php 
require_once('../Model/readingsModel.php'); 
require_once('../Tool/DrawTool.php'); 

$newReading = new Readings(); 
// instantiate drawing tool 
$draw = new DrawTool(); 
// parse (render) appliance view 
$renderedView = $draw->render('../View/meterReadings.php', array('elec_readings' => $newReading->getElecReadings()), 
    array('gas_readings' => $newReading->getGasReadings())); 

echo $renderedView; 

?> 

Как я сказал выше. Вставка работает нормально. Но я хочу, чтобы данные отображались мгновенно, а не обновлялись.

Любые идеи?

Благодаря

+0

Вы искали какие-либо примеры ajax (jQuery или иначе)? Там много чего. – Rasclatt

+0

@ Rasclatt У меня есть или все они не могут понять это или не могут заставить его работать с функцией – resontant81

+0

Опубликовать то, что вы пробовали, возможно, было что-то простое, что вы пропустили. – Rasclatt

ответ

0

С чистого PHP вы не можете сделать это без перезагрузки страницы. Поэтому используйте AJAX!

Вот небольшой пример

<html> 
    <head> 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> 
    </head> 
    <body> 
     <input type="text" id="name"/> 
     <input type="submit" id="submit" value="Send"><br/><br/> 
     <div id="response"><div> 

     <script> 
     $(document).ready(function(){ 
      $('#submit').click(function(e){ 
       e.preventDefault(); 
       var value = $('#name').val(); 
       if (value != ''){ 
        $.ajax({ 
         type: "POST", 
         url: "your_process_file.php", 
         data: { name:value }, 
         success: function(data){ 
          $('#response').html(data); 
         }, 
         fail: function(data){ 
          $('#response').html('There is an error!'); 
         } 
        }); 
       } 
      }); 
     }); 
     </script> 
    </body> 
</html> 

И your_process_file.php может выглядеть следующим образом:

$name = $_POST['name']; 
$stmt = $db->prepare('SELECT * FROM tblName WHERE name=?'); 
$stmt->execute([$name]); 
while ($row = $stmt->fetch()){ 
    echo $row['col1'],' ',$row['col2'],' ',$row['colN']; 
} 

И если у вас есть какие-то данные в таблице БД:

имя идентификатора адрес

1 abc address1

2 Защиты address2

Затем, когда вы пишете в текстовом поле, Fe, а вся строка из таблицы будет возвращено внутри <div id="response"></div> без обновления страницы.

OBS: Я предполагаю, что в коде могут быть ошибки, поскольку я не тестировал их.

+0

Спасибо за nswer, но im использует класс модели с функцией. Как я могу назвать это в файле Ajax? – resontant81

+0

@ resontant81 Что в этом классе? Показать код ... –

+0

Отредактировано мое исходное сообщение, чтобы включить полный класс для вставки и выбора данных – resontant81

1

Все это действительно действует как браузер, а на заднем плане - эта страница. Вы можете либо выбрать перезвонить данные, либо нет, но это как если бы ваш браузер перешел на эту страницу, поэтому вы относитесь к ней как к любой другой странице. Это просто хак вырезать и вставлять, но это, вероятно, близко:

index.php (независимо от вашей начальной страницы называется):

<!-- use the id to target the form --> 
    <form id="elecRead" method="POST"> 
     <h2>Electricity Usage</h2> 
     <!-- You just have an empty container where your ajax will return --> 
     <div id="errors"></div> 
     Please enter your latest electricity meter reading: 
     <br> 
     <input type="text" name="txtElecUsage" required/> 
     <br> 
     <input type="submit" name="btn-submitElecUsage" value="Submit"/> 

    </form> 
    ...etc... 

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

    <script> 
    // When page is done loading 
    $(document).ready(function(){ 
     // When this particular form is submitted 
     $('#elecRead').submit(function(e){ 
      // Stop normal refresh of page 
      e.preventDefault(); 
      // Use ajax 
      $.ajax({ 
       // Send via post 
       type: 'post', 
       // This is your page that will process the update 
       // and return the errors/success messages 
       url: "page2.php", 
       // This is what compiles the form data 
       data: $(this).serialize(), 
       // This is what the ajax will do if successfully executed 
       success: function(response){ 
        // It will write the html from page2.php into an 
        // element with the id of "errors", in our case 
        // it's a div 
        $('#errors').html(response); 
       }, 
       // If the ajax is a failure, this will pop up in the console. 
       error: function(response){ 
        console.log(response); 
       } 
      }); 
     }); 
    }); 
    </script> 

page2.php (страница обработка):

<?php 
// Page two just contains the processing of the update 
// so include everything that you need to do that 
session_start(); 
require_once(__DIR__.'/../Config/config.php'); 
require_once(__DIR__.'/../Model/readingsModel.php'); 
// Check for the post 
if(isset($_POST['btn-submitElecUsage'])){ 
     // Create the instance of your class that does the update and error 
     // handling/rendering 
     $newReading = new Readings(); 
     $eUsage = strip_tags($_POST['txtElecUsage']); 

     try { 
      if($newReading->enterElecReadings($eUsage)){  
       $elecNotif[] = "Reading successfully entered."; 
      } 
     } catch (Exception $e) { 
      echo $e->getMessage(); 
     } 
    } 
// I am just using a buffer, but you don't need it 
ob_start(); 
    // I presume this variable is on an included page, I don't see it 
    // anywhere but if you include the same stuff as your initial page, 
    // it should show up here fine 
    if(isset($elecError)){ 
     foreach($elecError as $elecError){ 
      ?> 
      <div class="alert alert-danger"> 
       <?php echo $elecError; ?> 
      </div> 
      <?php 
     } 
    } 

    if(isset($elecNotif)){ 
     foreach($elecNotif as $elecNotif){ 
      ?> 
      <div class="alert alert-danger"> 
       <?php echo $elecNotif; ?> 
      </div> 
      <?php 
     } 
    } 

$data = ob_get_contents(); 
ob_end_clean(); 
// Just print the contents of the page and your ajax on page 1 
// will take this content and place it in the <div id="errors"><div> 
die($data); 
Смежные вопросы