2013-08-21 40 views
0

我有一個頁面,插入一個新的職位,像facebook牆在網站。在我的網站中添加文章CodeIgniter中無刷新

我可以在我的網站添加新帖子,但是當我插入它時,網站將刷新。

我需要的是,當我插入一個新帖子時,它被添加到頁面而不刷新整個頁面。

我的控制器: -

<?php 



if (!defined('BASEPATH')) 

    exit('No direct script access allowed'); 



class MyAccount extends MY_Controller { 



    var $data; 
    var $errors; 




    function __construct() { 



     parent::__construct(); 

     $this->template->title('Home'); 



     if(!isset($_SESSION['user_id']) || empty($_SESSION['user_id'])){ 
      redirect('./home'); 
     } 
     else {$this->template->set_layout('myaccount');} 




    } 





    public function index() { 

     if(!isset($_SESSION['user_id']) || empty($_SESSION['user_id'])){ 
      redirect('./home'); 
     } 
     else {$user = new User($_SESSION['user_id']);} 


     $user = new User($_SESSION['user_id']); 

     if($this->input->post()){ 



      $user->username = $this->input->post('name'); 
      $user->address = $this->input->post('address'); 
      $user->phone = $this->input->post('phone'); 
      $user->skype = $this->input->post('skype'); 
      $user->facebook = $this->input->post('facebook'); 
      $user->mobile = $this->input->post('mobile'); 
      $user->tall = $this->input->post('tall'); 
      $user->fullname = $this->input->post('fullname'); 
      $user->wieght = $this->input->post('wieght'); 
      $user->fittnes = $this->input->post('fittnes'); 
      $user->fat = $this->input->post('fat'); 
      $user->email = $this->input->post('email'); 
      $user->birthdate = $this->input->post('birthdate'); 
      $user->gender = $this->input->post('gender'); 
      if(strlen($_FILES['pic']['name']) > 0){ 
       $config['upload_path'] = './uploads/'; 
       $config['allowed_types'] = 'gif|jpg|png'; 
       $config['max_size'] = '2048'; 
       $config['encrypt_name'] = true; 
       $this->load->library('upload', $config); 
       if (!$this->upload->do_upload('pic')) 
       { 
        $error = $this->upload->display_errors(); 
        if(is_array($error)){ 
         foreach($error as $er){ 
          $this->errors[] =$er; 
         } 
        }else{ 
         $this->errors[] =$error; 
        } 
       } 
       else 
       { 
        $updata =$this->upload->data(); 
        $imagePath = './uploads/'.$user->pic; 
        if(file_exists($imagePath)){ 
         @unlink($imagePath); 
        } 
        $user->pic = $updata['raw_name'].$updata['file_ext']; 
       } 
     } 


      if($this->input->post('password') == $this->input->post('confirm')){ 

       $user->password=md5(sha1(sha1($this->input->post('password')))); 

       $user->save(); 

       $this->data['success'] = "Done"; 
      }else{ 
       $this->errors[] = "Error"; 

      } 
     } 



     $this->data['user'] = $user; 

     $this->data['errors'] = $this->errors; 



     $this->template->set_layout('myaccount'); 

     $this->template->build('edit_profile',$this->data); 



    } 


    public function activate(){ 
     $this->template->set_layout('inner'); 

     if($_SESSION['is_verefied'] == 1){ 
      $this->data['status'] = "verified"; 
      $this->template->build('verefication_resend',$this->data); 
     }else 
     $this->template->build('activate',$this->data); 
    } 



    public function do_activate(){ 

     $code = $this->input->post('code',TRUE); 
     $code = strtolower($code); 
     $user = new User(); 
     $user->where('id',$_SESSION['user_id'])->get(); 

     if(strtolower($user->code) == strtolower($code)){ 
      $user->active = 1; 
      $user->save(); 
      echo 1; 
      $_SESSION['is_verefied'] = 1; 

     }else 
     echo 0; 

    } 


     public function profile($user_id) { 

     $check = new User(); 
     $ex = $check->where('id',$user_id)->count(); 
     if($ex == 0){ redirect('./home'); } 
     else { 
     $user = new User($user_id); 


/************************************** Post *******************************************************************/ 
     $this->load->model('blog'); 

     if(isset($_POST['post'])){ 
     if(strlen($_FILES['inputUpProfile']['name']) > 0) 
     { 
     $pic = $this->do_upload('inputUpProfile'); 

     if ($this->input->post('post') == ''){$type="image";} else {$type="image-with-text";} 
     } 

     else {$pic = ""; $type = "text"; } 

      $result = $this->blog->addPost($_SESSION['user_id'], $type , $this->input->post('post'),$pic); 
     } 
     if(isset($_SESSION['user_id']) || !empty($_SESSION['user_id'])){ 
     $result = $this->blog->getPost($user_id, 0 , 10); 
     $this->template->build("profile" , array("response"=>$result));  
     } 
     else{ 
     $this->template->build('registration_view',$this->data); 
     } 


     $this->data['user'] = $user; 
     $this->data['errors'] = $this->errors; 
     $this->template->set_layout('myaccount'); 
     $this->template->build('profile',$this->data); 


     } 
    } 

     public function deletePostInProfile($ev_id) { 

     $this->load->model('blog'); 
     $result = $this->blog->deletePost($ev_id); 
     redirect('myaccount/profile/'.$_SESSION['user_id'].''); 


    } 

     public function insertComment($ev_id) { 

      $data['co_comment'] = $this->input->post('comment'); 
      $data['co_postid'] = $ev_id; 
      $data['co_userid'] = $_SESSION['user_id']; 
      $data['co_date'] = date("Y-m-d H:i:s"); 

      $this->load->model('blog'); 
      $insert = $this->blog->insertCommentToDB($data); 

      if ($insert) { 
       //get the last entry data 
       $content = $this->blog->getComment($ev_id); 
       $this->template->build("profile" , array("commentre"=>$content)); 
      } 
     } 


} 

查看: -

<div id="inner-page-my-account"> 

<?php 

    if(isset($success)){ ?> 

    <div class="alert alert-success normal-alert" style="display: block;" id="okmsg"> 

     <p><span class="ico-text ico-alert-success" ></span><?= $success; ?></p> 

    </div> 
<?php 

} 



      if(isset($errors)){ ?> 

      <div class="alert alert-error normal-alert" style="display: block;" id="notokmsg"> 

       <div><span class="ico-text ico-alert-error"></span> 



      <?php 

       if(count($errors) >0){ 

        ?> 

         <ul> 

          <?php 

           foreach($errors as $error){ 

            echo "<li>$error</li>"; 

           } 

          ?> 

         </ul> 

        <?php 

       } 

      ?> 

       <div class="clear"></div> 

       </div> 

      </div> 

      <?php } ?> 

<div id="followbox" style="display:none" class="alert alert-success normal-alert"> 
<div id="show_message"></div> 
</div> 

     <div class="profile"> 
     <div class="rightprofile"> 
     <? if(isset($user->pic)) {?> 
     <div class="picprofile"><img src="uploads/<?=$user->pic?>" width="250px" height="274px" /></div> 
     <? } else { ?> 
     <div><div id="Up-img"></div></div> 
     <? } ?> 
     </div> 
     <div class="leftprofile"> 
     <div class="box-title-profile"> 

     <?php if(!empty($_SESSION['user_id']) && ($user->id != $_SESSION['user_id'])){ ?> 
     <div style="margin:auto"> 

     <div style="float:right;padding-top:5px;"><?php if(isset($user->fullname)) echo $user->fullname; ?></div> 


      <div style="float:left"><? 
      $sql = mysql_query("select * from follow where fo_user_id_follow = '".$user->id."' and fo_user_id = '".$_SESSION['user_id']."' "); 
      if (mysql_num_rows($sql) == '0'){ 
     ?> 
      <input type="button" id="followme" class="followme" value="متابعة" onClick="followuser('<?=$user->id;?>' , 'followme');"> 
      <? } else { ?> 
      <input type="button" id="followme" class="followme" value="إلغاء المتابعة" onClick="nofollowuser('<?=$user->id;?>' , 'nofollowme');"> 
      <? } ?></div> 


     </div> 
     <? } ?> 
<div style="clear:both;"></div> 
     </div> 
     <div class="info"> 
      <div class="inforight">العمـــــــــــــــــــــــــر :</div><div class="infoleft">30 سنة</div> 
     </div>   
     <div class="info"> 
      <div class="inforight">الوزن المثـــــالي :</div><div class="infoleft"><?php if(isset($user->wieght)) echo $user->wieght; ?> كيلو</div> 
     </div> 
     <div class="info"> 
      <div class="inforight">عضو مجموعــة :</div><div class="infoleft">12</div> 
     </div> 
     <div class="info"> 
      <div class="inforight">الوزن المبدئــــي :</div><div class="infoleft"><?php if(isset($user->wieght)) echo $user->wieght; ?> كيلو</div> 
     </div> 
     <div class="info"> 
      <div class="inforight">الوزن الحالــــــــي :</div><div class="infoleft"><?php if(isset($user->wieght)) echo $user->wieght; ?> كيلو</div> 
     </div> 
     <div class="info"> 
      <div class="inforight">نسبة الدهـــــون :</div><div class="infoleft"><?php if(isset($user->fat)) echo $user->fat; ?>%</div> 
     </div> 
     <?php if(!empty($_SESSION['user_id']) && ($user->id == $_SESSION['user_id'])){ ?> 
     <div class="info"> 
      <div class="editinfo"><a href="./myaccount/" >تعديل بياناتي</a></div> 
     </div> 
     <? }?>      
     </div> 
     </div> 
     <div class="clear"></div> 
     <div class="follow"> 
     <div class="followbox"><span class="black" >350</span> <br /> أتابع</div> 
     <div class="followbox"><span class="black" >350</span> <br /> متابعيني</div> 
     <div class="followbox"><span class="green" >- 201</span> <br /> سعرات مفقودة</div> 
     <div class="followboxlast"><span class="red" >+ 325</span> <br /> سعرات موفرة</div> 

     </div> 
     <div class="clear"></div> 
     <div class="wight"><img src="images/wight.png" /></div> 
     <div class="clear"></div> 

<div class="clear"></div> 
<? if(!empty($_SESSION['user_id'])) { ?> 
<div class="acceptlisttitle">مـــاذا تعمل الان</div> 
<div class="clear"></div>   

<?php if(!empty($_SESSION['user_id']) && ($user->id == $_SESSION['user_id'])){ ?> 
<div id="postprofile"> 
<div id="massge" style="float:right"> 
<form method="post" action="<?php echo site_url('myaccount/profile/'.$user->id.'')?>" enctype="multipart/form-data"> 
<div class="upimgstatus"> 

</div> 
<div class="textstatus"> 
<input id="inputUpProfile" name="inputUpProfile" class="inputUpProfile hidefile" type="file" /> 
<input type="button" id="PicUpProfile" class="sentpic" value="اضافة صورة"> 

<input name="post" type="text" id="textprofile" placeholder="اكتب رسالتك هنا ..."> 
<input type="submit" id="sent" name="sent" value="إرسال"> 
</div> 
</form> 
</div> 
<? } ?> 

<div style="clear: both"></div> 

<ol class="timeline2 clear"> 
    <li class="spine"> 

    </li> 

    <?php 
    $counter=0; 
    //print_r($response); 
    foreach ($response as $row) { 
    if($counter % 2 == 0){$class= "left";} else $class="right"; 
    ?> 

    <li class="<?=$class ?>"> 
    <i class="pointer"></i> 
    <div class="unit"> 

     <!-- Story --> 
     <div class="storyUnit"> 
     <div class="imageUnit"> 
     <? if (empty($row->pic)) { ?> 
      <a href="#"><img width="32" height="32" alt="" src="images/nopic.png"></a> 
      <? } else { ?> 
      <a href="#"><img width="32" height="32" alt="" src="uploads/<?php echo $row->pic; ?>"></a> 
      <div id="delpost" style="float:left"> 
      <a href="./myaccount/deletePostInProfile/<?=$row->ev_id;?>" id="deletepost">X</a> 
      </div> 
      <? } ?> 
      <div class="imageUnit-content"> 
      <h4><a href="./myaccount/profile/<?php echo $row->id; ?>"><?php echo $row->fullname; ?></a></h4> 
      <p><?php echo $row->ev_date ?></p> 
      </div> 

     </div> 

     <p> <?php echo $row->ev_text; ?><br /> 
     <? if (!empty($row->ev_pic)) { ?> 
     <img src="uploads/<?php echo $row->ev_pic ?>" width="250" height="250"</p> 
     <? } ?></p> 

     </div> 
     <!--/Story --> 

     <!-- Units --> 
     <ol class="storyActions"> 
<? 
$selectComment = mysql_query("select * from comment,users where 
comment.co_postid = '".$row->ev_id."' 
and comment.co_userid = users.id "); 
while($rows=mysql_fetch_array($selectComment)){ 
?> 
     <div id="resultcomment1"></div> 
     <div id="resultcomment"> 
     <a href="./myaccount/profile/<?php echo $rows['id']; ?>"> 
     <img src="uploads/<?=$rows["pic"];?>" width="32" height="32" class="rightc" /> 
     </a> 
     <b><a href="./myaccount/profile/<?php echo $rows['id']; ?>"><?=$rows["fullname"]; ?></a></b> 
     <span>&nbsp;&nbsp;</span> 
     <span><?=$rows["co_comment"]; ?></span> 
     <br /> 
     <span class="commentdate"><?=$rows["co_date"]; ?></span></br></div> 
<? } ?>  

     <form action="" method="post" accept-charset="utf-8"> 
     <input type="text" id="comment" name="comment" size="41" /> 
     <button type="button" id="submit" onclick="add_comment()">ارسل</button> 
     </form> 

     </ol> 
     <!--/Units --> 

    </div> 
    </li> 

    <?php $counter++; } ?> 
    <div class="clear"></div> 
</ol> 

<? } ?> 

</div> 

</div> 

<script type="text/javascript"> 


      function add_comment() { 

       //get input data as a array 
       var post_data = { 
        'comment': $("#comment").val(), 
        '<?php echo $this->security->get_csrf_token_name(); ?>': '<?php echo $this->security->get_csrf_hash(); ?>' 
       }; 

       $.ajax({ 
        type: "POST", 
        url: "<?php echo base_url(); ?>myaccount/insertComment/<?=$row->ev_id;?>", 
        data: post_data, 
        success: function(comment) { 
         // return success message to the id='result' position 
         $("#resultcomment1").html(comment); 
        } 
       }); 



     } 
    </script> 

**這裏我發評論,但它給我的錯誤**

A PHP Error was encountered 

Severity: Notice 

Message: Trying to get property of non-object 

Filename: views/profile.php 

和其負載所有網站,,,我需要只有在點擊發送添加評論到數據庫,並返回名稱和註釋

+0

這是太普遍的一個問題。你需要嘗試一下你的一些Ajax,並試着當你的卡住somwhere。對於初學者來說,嘗試做一個動作,在那裏只傳遞文章(格式化的HTML),而不是佈局的其餘部分。然後使用ajax獲取此信息,並在需要刷新時用此數據替換您的帖子部分 –

+0

需要使用AJAX將數據發佈到服務器而無需刷新表單。你可以爲此使用Jquery。 – Nishanthan

+0

那麼怎麼能這樣做,任何幫助或例子 –

回答

1

您的控制器和型號中有很多數據。這次我不想處理這個問題。但我想與您分享如何在數據庫中插入數據的示例,然後在您的站點中顯示CodeIgniter中沒有刷新頁面的給定數據。我認爲這會有所幫助。

下面是示例圖 -

<form action="" method="post" accept-charset="utf-8"> 

     <table align="center"> 

      <tr> 
       <td>Message :</td> 
       <td> 
        <textarea name="message" id="message" placeholder="Write here the message"></textarea> 
       </td> 
      </tr> 

      <tr> 
       <td>&nbsp;</td> 
       <td id="result"> </td> 
      </tr> 

      <tr> 
       <td>&nbsp;</td> 
       <td> 
        <button type="button" id="submit">Submit</button> 
       </td> 
      </tr> 

     </table> 

    </form> 

這裏是控制器 -

/* 
* this is just to load you view page call test.php from your view folder (Which is my given view file) 
*/ 

public function test() { 
    $this->load->view('test'); 
} 

/* 
* this is for insert data via Ajax and get the data 
*/ 

public function insertByajax() { 

    $data['message'] = $this->input->post('message'); 

    $insert = $this->YOURMODEL_NAME->insertDataToDB($data); 

    if ($insert) { 
     //get the last entry data 
     $content = $this->YOURMODEL_NAME->getLastEnrtyData(); 
     echo $content->message; 
    } 
} 

模型文件 -

/* 
* Insert data to the content table 
*/ 
public function insertDataToDB($data) { 
    return $this->db->insert('content', $data); 
} 


/* 
* Get the Inserted data from content table 
*/ 
public function getLastEnrtyData() { 
    $this->db->from('content'); 
    $last_id = $this->db->insert_id(); 
    $this->db->where('id', $last_id); 

    return $this->db->get()->row(); 
} 

喏,這就是最迷人的Javascript代碼 - 只需在查看文件末尾添加了這個

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 

    <script type="text/javascript"> 
     $(function() { 

      $('#submit').click(function() { 

       //get input data as a array 
       var post_data = { 
        'message': $("#message").val(), 
        '<?php echo $this->security->get_csrf_token_name(); ?>': '<?php echo $this->security->get_csrf_hash(); ?>' 
       }; 

       $.ajax({ 
        type: "POST", 
        url: "<?php echo base_url(); ?>YOUR_CONTROLLER/insertByajax", 
        data: post_data, 
        success: function(message) { 
         // return success message to the id='result' position 
         $("#result").html(message); 
        } 
       }); 

      }); 

     }); 
    </script> 

這裏是我使用MySQL表 -

CREATE TABLE IF NOT EXISTS `content` (`id` int(11) NOT NULL AUTO_INCREMENT, `message` text NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; 

那麼試試這個。希望工作,對你有幫助。讓我知道發生了什麼事。

+0

謝謝,但當點擊提交它不做任何想法?爲什麼 –

+0

它顯示我在調試500內部服務器錯誤 –

+0

Plz告訴我完整的錯誤。不過,我認爲你面臨着來自CSRF保護的問題。 在配置文件中執行以下操作 $ config ['csrf_protection'] = TRUE; $ config ['csrf_token_name'] ='YOUR_TOKEN'; $ config ['csrf_cookie_name'] ='YOUR_COKIE_NAME'; – Sharif

0

試試這個

$.ajax({ 
    type: "POST", 
    url: url, 
    data: data, 
    success: function(res){ 
     // do stuff 
    }, 
}); 

這裏是docs

我希望這將有助於開始使用jQuery post或get