0

我有一个页面可以在 facebook wall 之类的网站中插入新帖子。

我可以在我的网站中添加新帖子,但是当我插入它时,网站会刷新。

我需要的是,当我插入一个新帖子时,它被添加到页面而不刷新整个页面。

我的控制器:-

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

您的控制器和模型中有大量数据。这次我不想处理。但我想与您分享一个如何在数据库中插入数据然后在您的站点中显示给定数据而不在 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 回答