dqm7854
dqm7854
2013-08-21 06:24
浏览 67

在我的网站中添加帖子而不在CodeIgniter中刷新

I have a page that inserts a new post in site like facebook wall.

I can add new post in my site, but when I insert it, the site will refresh.

What I need is, when I insert a new post, it is added to the page without refreshing the whole page.

My Controller :-

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


}

View:-

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

** here i send comment but its show me error **

A PHP Error was encountered

Severity: Notice

Message: Trying to get property of non-object

Filename: views/profile.php

and its load all site ,,, i need only after click send add comment to database and return the name and comment

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duanfan8699
    duanfan8699 2013-08-21 08:36
    已采纳

    Your have lots of data in you controller and model. I don't want to handle that this time. But I want to share with you a sample of How to insert data in DB and then show the given data in your site without refresh page in CodeIgniter. I think this will be helpful.

    Here is sample view -

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

    Here is the controller -

    /*
    * 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;
        }
    }
    

    The model file -

    /*
    * 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();
    }
    

    And now here is the most charming Javascript code - Just added this at the end of the view file

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

    And here is my used Mysql table -

      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 ;
    

    So try this. Hope work and helpful for you. And let me know what's going on.

    点赞 评论
  • dtoqa66028
    dtoqa66028 2013-08-21 07:07

    Try this

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

    here is the docs

    I hope it will help to start with jquery post or get

    点赞 评论

相关推荐