Problem:
Hi friend i am inserting data into mysql database table via textbox using ajax in codeIgniter and at the same time, i am displaying existing data in front end from database.
Once i insert data into database, i am getting two input textbox and two outputs. So plz tell me how to display one input textbox and output.
My Original Codes as follows:
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> </td>
<td id="result"> </td>
</tr>
<tr>
<td> </td>
<td>
<button type="button" id="submit">Submit</button>
</td>
</tr>
</table>
</form>
<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: "http://192.168.1.17/ci_civic_soft/index.php/sample_control/index",
data: post_data,
success: function(message) {
// return success message to the id='result' position
$("#result").html(message);
}
});
});
});
</script>
sample_control:
<pre>
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Sample_control extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('sample_model');
}
public function index()
{
$this->load->view('sample_view');
$data['message'] = $this->input->post('message');
$insert = $this->sample_model->insertDataToDB($data);
if ($insert)
{
$tree_menu = $this->sample_model->getLastEnrtyData(); //getting tree from DB
foreach($tree_menu as $tv)
{
echo $tv['message'];
}
}
}
}
</pre>
sample_model:
<pre>
Class sample_model extends CI_Model
{/*
* 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()
{
$query = $this->db->query("CALL content()");
return $query->result_array();
}
}
</pre>
Move your insert code into a separate function like saveMessage(). You are loading the view in the index thus it wil be returned by ajax.
public function saveMessage(){
$data['message'] = $this->input->post('message');
$insert = $this->sample_model->insertDataToDB($data);
if ($insert)
{
$tree_menu = $this->sample_model->getLastEnrtyData(); //getting tree from DB
foreach($tree_menu as $tv)
{
echo $tv['message'];
}
}
}