2016-03-28 17 views
-1

Temel bir MVC yapısı kullanan küçük bir web sitem var. Veritabanına iki değer ekleyen bir kodum var, ekleme işlemi sorunsuz bir şekilde çalışıyor, ancak yeni verileri görmek istiyorsanız genellikle sayfayı yenilemem veya başka bir sayfaya gidip sonra geri dönmem gerekiyor. Bu işi yapmak için JQuery/Ajax kullanmam gerektiğini, ancak PHP işlevleriyle nasıl yapılacağını gerçekten anlamadığımı anlıyorum.Veri yenileme ve bilgi yenilikleri gösterme

söz konusu kod aşağıda:

PHP Fonksiyonu:

<?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) { 

     } 
    } 
} 

?> 

Sayfa Kullanıcının göreceği:

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> 

Kontrolör sınıfı:

<?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; 

?> 

olarak yukarıda söyledim. Ekleme iyi çalışıyor. Ancak verileri yenilemek yerine anında görünmesini istiyorum.

Herhangi bir fikrin var mı? Saf php ile

Teşekkür

+0

ajax (jQuery veya başka türlü) örneklerine baktınız mı? Orada çok şey var. – Rasclatt

+0

@Rasclatt Ya anlayamıyorum ya da anlayamadım ya da – resontant81

+0

fonksiyonu ile çalışmasını sağlayamadım Ne denediğini yaz, kaçırdığın bir şey olabilirdi. – Rasclatt

cevap

0

sayfa yenileme olmadan bunu yapamaz. Yani AJAX kullanın! İşte

biraz örnek

<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> 

var Ve gibi your_process_file.php görünebilir:

kimlik adı adresi

: Bir db tabloda bazı veriler var

$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']; 
} 

Ve varsayarak

1 abc address1

2 def address2

Sonra

, tablodan tüm satır Sayfayı yenilemeden <div id="response"></div> içine iade edilecektir abc metin, fe, içinde yazarken.

OBS: Test ettiğim gibi kodda bazı hatalar olabileceğini varsayalım.

+0

nswer ama bir fonksiyon ile model sınıfını kullanıyorum. Bunu Ajax dosyasında nasıl arardım? – resontant81

+0

@ resontant81 Bu sınıfta ne var? Bazı kodları göster ... –

+0

Orijinal gönderiyi, veri eklemek ve seçmek için tam sınıfı dahil etmek üzere düzenledim – resontant81

1

Gerçekten de bir tarayıcı gibi davranıyor ve arka planda bu sayfaya çarpıyor. İsterseniz verileri geri aramayı seçebilir veya yapamazsınız, ancak sanki tarayıcınız o sayfaya gittiyse, başka bir sayfa gibi davranırsınız. Bu sadece bir hack kesme ve yapıştırma ama bu muhtemelen yakındır: (İlk sayfa denir ne olursa olsun)

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> 

sayfa2.php (işlem sayfası):

<?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); 
İlgili konular