Reputation: 81
I want to insert data with the help of bootstrap modal. But I've got an error on the action index. So the button I've added couldn't run. Did I make any wrong thing in coding?
Controller
function user_action(){
if ($_POST['action'] == "Tambah"){
$data=array(
'kodebayar' => $this->input->post('kodebayar'),
'nama' => $this->input->post('nama'),
'harga' => $this->input->post('harga')
);
$this->bpem_m->create($data);
}
}
View Of Modal
<div class="modal fade text-xs-left" id="modalpem" tabindex="-1" role="dialog" aria-labelledby="myModalLabel35" aria-hidden="true">
<div class="modal-dialog modal-sm">
<form method= "post" id="form_pem">
<div class="modal-content">
<div class="modal-header">
</div>
<div class="modal-body">
<fieldset class="form-group floating-label-form-group">
<label for="Kode">Kode <span class="required">*</span></label>
<input type="text" class="form-control" name="kodebayar" id="kodebayar" placeholder="Kode Pembayaran">
</fieldset>
<fieldset class="form-group floating-label-form-group">
<label for="nama">Nama <span class="required">*</span></label>
<input type="text" class="form-control" name="nama" id="nama" placeholder="Nama Pembayaran">
</fieldset>
<fieldset class="form-group floating-label-form-group">
<label for="projectinput7">Biaya Perbulan <span class="required">*</span></label>
<div class="input-group">
<span class="input-group-addon">Rp.</span>
<input type="number" class="form-control" placeholder="Biaya Perbulan" aria-label="Amount (to the nearest dollar)" name="harga" id="harga">
<span class="input-group-addon">.00</span>
</div>
</fieldset>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-warning" name="action" value="Tambah"/>
</div>
</div>
</form>
</div>
</div>
JS
$(document).on('submit','#form_pem', function(event){
event.preventDefault();
var kodebayar = $('#kodebayar').val();
var nama = $('#nama').val;
var harga = $('#harga').val;
var postData = new FormData(this);
if(kodebayar != '' && nama != '' && harga != ''){
$.ajax({
url:"<?=site_url('bpem/user_action')?>",
method: "POST",
data: postData,
contentType: false,
processData: false,
cache: false,
dataType: 'json',
success: function(data, textStatus, jqXHR)
{
alert(data);
$('#form_pem')[0].reset();
$('#modalpem').modal('hide');
dataTable.ajax.reload();
},
error: function(jqXHR, textStatus, errorThrown){
//if fails
}
});
}
else{
alert("Silahkan isikan semua data!");
}
});
Upvotes: 0
Views: 475
Reputation: 1356
You can use serialize()
var datastring = $("#form_pem").serialize();
$.ajax({
type: "POST",
url: "your url.php",
data: datastring,
dataType: "json",
success: function(data) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handing here');
}
});
return type is json
EDIT: I use event.preventDefault
to prevent the browser getting submitted in such scenarios.
Upvotes: 2