0

Facebook ウォールのようなサイトに新しい投稿を挿入するページがあります。

サイトに新しい投稿を追加できますが、挿入するとサイトが更新されます。

必要なのは、新しい投稿を挿入すると、ページ全体を更新せずにページに追加されることです。

私のコントローラー:-

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

そして、すべてのサイトをロードします,,, クリックしてデータベースにコメントを追加し、名前とコメントを返す必要があります

4

2 に答える 2

1

コントローラーとモデルには大量のデータがあります。今回は扱いたくない。しかし、DB にデータを挿入し、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 ;

だからこれを試してください。仕事とあなたのお役に立てば幸いです。そして、何が起こっているのか教えてください。

于 2013-08-21T08:36:25.583 に答える
0

これを試して

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

ここにドキュメントがあります

jquery postまたはgetから始めるのに役立つことを願っています

于 2013-08-21T07:07:08.653 に答える