Reputation: 71
I want to show a specific div
class in my view ... but first I have to check whether sepecific data is successfully entered into the data base through ajax and if not then other dive error class will appear above for some time and then hide.
Here is my view JavaScript code. Here I am popping a dialog box if event occur suceesfully which I want to turn into a div class that if something true is happened then "div success message" else div failure message. I think I have to pass a specific parameter from controller to view but I dont know how to do it.
<script type="text/javascript">
$('#btn').click(function() {
var item_name = $('#item_name').val();
var cat_id = $('#cat_id').val();
if (!item_name || item_name == 'Name') {
alert('Please enter Category Name');
return false;
}
var form_data = {
item_name: $('#item_name').val(),
cat_id: $('#cat_id').val(),
ajax: '1'
};
$.ajax({
url: "<?php echo site_url('itemsController/additems'); ?>",
type: 'POST',
data: form_data,
success: function(msg) {
//$('#message').html(msg);
alert("items added successfully");
$('#item_name').val("");
}
});
return false;
});
</script>
this is my controller
function additems(){
//getting parameters from view
$data = array(
'item_name' => $this->input->post('item_name'),
'cat_id' => $this->input->post('cat_id')
);
$is_ajax = $this->input->post('ajax'); //or use this line
//$this->input->is_ajax_request();
$this->load->model('itemsModel');
$query = $this->itemsModel->addItemstoDB($data);
if ($query && $is_ajax){ //if the user c validated
//data variable is created becx we want to put username in session
$page['main_content'] = 'itemsView';
$this->load->view('dashboardTemplate/template',$page);
}
else
{
echo "not added";
}
}
}
model
class ItemsModel extends CI_Model {
public function addItemstoDB($data){
$successfull = $this->db->insert('item',$data);
if ($successfull){
return true;
}else{
return false;
}
}
}
Upvotes: 1
Views: 1813
Reputation: 8528
this is not how to deal with ajax in your controller at all:
first I''m going to assume that your model is returning true
if inserted and false
if not then:
your controller:
function additems(){
//your processing goes here.
$result = array();
$this->load->model('itemsModel');
$query = $this->itemsModel->addItemstoDB($data);
//var_dump($query); the results will be desplayed either on your page or you can see it using firebug in firefox
if ($query ){ //&& any other condition
$result['res'] = 1;//process successful - replace 1 with any message
}
else
{
$result['res'] = 0;//process failed - replace 0 with any message
}
echo json_encode($result);//at the end of the function.
}
then your ajax part:
$.ajax({
url: "<?php echo site_url('itemsController/additems'); ?>",
type: 'POST',
data: form_data,
dataType: 'json',
success: function(msg) {
if(msg.res == 1)
{
$("your div").removeClass("error").addClass("ok");
}
else{
$("your div").removeClass("ok").addClass("error");
}
}
});
Upvotes: 1