I'm trying to update my database using AJAX
This is my ajax function
$(document).ready(function() {
$('#submit').click(function (event) {
event.preventDefault();
if($('#category').val()===''){
alert('Please enter a category name.')
}
else{
var category = $('#category').val();
var subcategory = $('#subcategory').val();
alert(category);
alert(subcategory);
$.ajax({
type: "POST",
url: "Admin_controller/insertCategory",
data:{ category:category, subcategory:subcategory },
success: function(data) {
alert('You can now add items.');
}
});
}
});
});
Here is my Admin_controller
public function insertCategory(){
$category = $this->input->post('category');
$subcategory = $this->input->post('subcategory');
$this->form_validation->set_rules('category', 'Category', 'required');
$this->form_validation->set_rules('subcategory', 'Subcategory', 'required');
if($this->form_validation->run() == FALSE){
$this->load->view('ADMIN_ADDCategory');
}
else{
$category_id = $this->admin_model->insertCategory($category);
$this->admin_model->insertSubcategory($category_id, $subcategory);
}
}
Here is my model
function insertCategory($category){
$data = array(
'category' => $category,
'status' => 1
);
$this->db->insert('category', $data);
$this->db->insert('category', $data);
$id = $this->db->insert_id(): //assign the last inserted id to variable $id
return $id;
}
function insertSubcategory($category_id, $subcategory){
$data = array(
'category_id' => $category_id,
'subcategory' => $subcategory,
'status' => 1
);
$this->db->insert('subcategory', $data);
}
When I click the button that is supposed to trigger the AJAX function it shows the alert('You can now add items.');
but it doesn't update my database with my required values.
I already tried doing
var category = $('#category').val();
var subcategory = $('#subcategory').val();
alert(category);
alert(subcategory);
to view if it gets my inputs and yes it does. After the alert it just refreshes my page.
What am i doing wrong? Thanks for the help.