I'm trying to insert a row into my repair_history table from a form inside a dialog box using ajax.
Here is the function that opens the dialog box with the form:
<script>
$(function() {
$( "#repair-dialog" ).dialog({
autoOpen: false,
height: 300,
width: 450,
modal: true,
buttons: {
"Save": function() {
insert(
$( "#repair-dialog-date" ).val(),
$( "#repair-dialog-id" ).val(),
$( "#repair-dialog-comment" ).val(),
$( "#repair-dialog-save_type" ).val()
);
$( this ).dialog( "close" );
setTimeout(function(){location.reload(true);},500);
},
"Cancel": function() {
$( this ).dialog( "close" );
}
},
close: function() {
}
});
$( "#record_repair" ).click(function() { $( "#repair-dialog" ).dialog( "open" ); });
});
function insert(date,id,comment,save_type) {
mydata = {
"date" : date ,
"id" : id ,
"comment" : comment ,
"camera_id" : "<?php= $products['camera_id']?>" };
$.ajax({
type: "POST",
url: "localhost/cibs/index.php/api/record_save/"+save_type,
data: {data:JSON.stringify(mydata)},
dataType: "json",
cache : false
});
}
and here is the function inside the api.php controller that tries to insert:
function record_save()
{
$this->load->database();
$mydata = $this->input->post('data');
$date = $mydata['date'];
$comment = $mydata['comment'];
$id = $mydata['id'];
$camera_id = $mydata['camera_id'];
$table = "repair_history";
$data = array("camera_id" => $camera_id, "repair_id" => $id, "date" => $date, "comment" => $comment);
$this->db->insert($table,$data);
}
and heres the dialog box:
<div id="repair-dialog" title="Add New Repair" style="font-size: 15px;">
<form id="repair">
<input style="height:0px; top:-1000px; position:absolute" type="text" value="">
Repair id: <input type="text" id="repair-dialog-id" /><br>
Repair date: <input type="text" id="repair-dialog-date" /><br>
Comment: <input type="text" id="repair-dialog-comment" /><br>
<input type="hidden" value="repair" id="repair-dialog-save_type">
</form>
</div>
Any replies really appreciated! Thanks! :)
I'm not sure how your function $this->input->post('data')
works, but you are posting the data as a json string, so you should make sure that you json_decode that data first.
Replace
$mydata = $this->input->post('data');
By
$mydata = json_decode($this->input->post('data'), true);
You don't need stringify your object:
$.ajax({
type: "POST",
url: "http://localhost/cibs/index.php/api/record_save/"+save_type,
data: mydata,
dataType: "json",
cache : false
});
And in php:
function record_save()
{
$this->load->database();
$table = "repair_history";
$data = array(
"camera_id" => $this->input->post('camera_id'),
"repair_id" => $this->input->post('id'),
"date" => $this->input->post('date'),
"comment" => $this->input->post('comment')
);
$this->db->insert($table,$data);
}