1

I have a code here of inserting and displaying record without refreshing web page using ajax and plain php but I don't know how to set this up using codeigniter. Please help. Here are the codes

inserting.php

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
 libs/jquery/1.3.0/jquery.min.js">
</script>
<script type="text/javascript" >
$(function() {
$(".comment_button").click(function() {

var test = $("#content").val();
var dataString = 'content='+ test;

if(test=='')
{
  alert("Please Enter Some Text");
}
else
{
 $("#flash").show();
 $("#flash").fadeIn(400).html('<img src="ajax-loader.gif" align="absmiddle">
  <span class="loading">Loading Comment...</span>');

  $.ajax({
   type: "POST",
   url: "demo_insert.php",
   data: dataString,
   cache: false,
   success: function(html){
   $("#display").after(html);
   document.getElementById('content').value='';
   document.getElementById('content').focus();
   $("#flash").hide();
   }
 });
  } return false;
});
});
</script>
// HTML code
<div>
<form method="post" name="form" action="">
<h3>What are you doing?</h3>
<textarea cols="30" rows="2" name="content" id="content" maxlength="145" >
</textarea><br />
<input type="submit" value="Update" name="submit" class="comment_button"/>
</form>
</div>
<div id="flash"></div>
<div id="display"></div>

demo_insert.php PHP Code display recently inserted record from the database.

<?php
  include('db.php');
  if(isSet($_POST['content']))
  {
   $content=$_POST['content'];
   mysql_query("insert into messages(msg) values ('$content')");
   $sql_in= mysql_query("SELECT msg,msg_id FROM messages order by msg_id  desc");
    $r=mysql_fetch_array($sql_in);
   }
  ?>
 <b><?php echo $r['msg']; ?></b>
Eli
  • 1,256
  • 4
  • 29
  • 59

1 Answers1

0

In your wellcome controller you can add the following:

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

public function process()
{
    $content=$this->input->post('content'); 
 if($this->db->insert('mytable', array('msg' => $content))){
    echo "<b>{$content}</b>";
 } 

You should then use inserting.php as your view, in application/views, and the ajax url would be /process.

Didn't test it, but this should do the trick. Also, you should check this example http://runnable.com/UXczcazDrMMiAAGl/how-to-do-ajax-in-codeigniter-for-php

Vali S
  • 1,471
  • 2
  • 10
  • 18