I am trying to save records using AJAX Form Submit for CodeIgniter 4.
This is my Controller:
`<?php
namespace AppControllers;
use CodeIgniterController;
use AppModelsPeopleModel;
class PreRegController extends Controller
{
public function index()
{
helper(['form']);
$data = [];
echo view('pregistration', $data);
}
public function store()
{
$transacttype = 'Add';
helper(['form']);
$rules = [
'firstname' => 'required|min_length[2]',
'midinitial' => 'required|min_length[1]|max_length[3]',
'lastname' => 'required|min_length[2]|max_length[50]',
//'cooperativeid' => 'required|min_length[1]|max_length[100]',
//'positionid' => 'required|min_length[1]|max_length[100]',
'email' => 'required|min_length[4]|max_length[50]|valid_email|is_unique[people.email]',
'repcontactno' => 'required|min_length[10]|max_length[13]',
//'boardresolution' => 'required',
'contactperson' => 'required',
'cooperativeaddress' => 'required',
'cooperativecontactnumber' => 'required|min_length[10]|max_length[13]'
];
if ($this->validate($rules)) {
$model = new PeopleModel();
$data = [
'firstname' => $this->request->getVar('firstname'),
'midinitial' => $this->request->getVar('midinitial'),
'lastname' => $this->request->getVar('lastname'),
//'cooperativeid' => $this->request->getVar('cooperativeid'),
//'positionid' => $this->request->getVar('positionid'),
'email' => $this->request->getVar('email'),
'repcontactno' => $this->request->getVar('repcontactno'),
//'boardresolution' => $this->request->getVar('boardresolution'),
'contactperson' => $this->request->getVar('contactperson'),
'cooperativeaddress' => $this->request->getVar('cooperativeaddress'),
'cooperativecontactnumber' => $this->request->getVar('cooperativecontactnumber'),
'transacttype' => $transacttype
];
$data = $model->save($data);
return redirect()->to('/pregistration');
} else {
$data['validation'] = $this->validator;
echo view('pregistration', $data);
}
$data = [
'data' => $data,
];
return $this->response->setJSON($data);
}
}`
And this is my View:
`<!doctype html>
<head>
<?php echo view('head'); ?>
<title>Pre-Registration</title>
</head>
<body>
<div class="container">
<div class="row justify-content-md-center">
<div class="col-6">
<h3>Pre-Registration</h3>
<?php if(isset($validation)):?>
<div id="alert_message" class="d-none alert alert-info">
<?= $validation->listErrors() ?>
</div>
<?php endif;?>
<div id="alertmessage" class="d-none alert alert-info"></div>
<!--<form action="<?php //echo base_url(); ?>/PreRegController/store" method="post">-->
<form action="javascript:void(0)" name="pregform" id="pregform" method="post">
<div class="mb-3">
<select class="form-control select2" id="coop" style="width: 100%;">
<!--<option data-value="0" selected="selected">Select Cooperative...</option>-->
<!--<option data-value="1">Alabama</option>
<option data-value="2">Alaska</option>
<option data-value="3">California</option>
<option data-value="4">Delaware</option>
<option data-value="5">Tennessee</option>
<option data-value="6">Texas</option>
<option data-value="7">Washington</option>-->
</select>
</div>
<div class="mb-3">
<input type="text" name="firstname" placeholder="Firstname" value="<?= set_value('firstname') ?>" class="form-control" >
</div>
<div class="mb-3">
<input type="text" name="midinitial" placeholder="Middle" value="<?= set_value('midinitial') ?>" class="form-control" >
</div>
<div class="mb-3">
<input type="text" name="lastname" placeholder="Lastname" value="<?= set_value('lastname') ?>" class="form-control" >
</div>
<div class="mb-3">
<select class="form-control select2" id="position" style="width: 100%;">
<!--<option data-value="0" selected="selected">Select Cooperative...</option>-->
<!--<option data-value="1">Alabama</option>
<option data-value="2">Alaska</option>
<option data-value="3">California</option>
<option data-value="4">Delaware</option>
<option data-value="5">Tennessee</option>
<option data-value="6">Texas</option>
<option data-value="7">Washington</option>-->
</select>
</div>
<div class="mb-3">
<input type="email" name="email" placeholder="Email" value="<?= set_value('email') ?>" class="form-control" >
</div>
<div class="mb-3">
<input type="text" name="repcontactno" placeholder="Representative Contact Number" value="<?= set_value('repcontactno') ?>" class="form-control" >
</div>
<div class="mb-3">
<input type="file" id="boardresolution" name="boardresolution" accept="image/*,.pdf" class="form-control" >
</div>
<div class="mb-3">
<input type="text" name="contactperson" placeholder="Contact Person" value="<?= set_value('contactperson') ?>" class="form-control" >
</div>
<div class="mb-3">
<input type="text" name="cooperativeaddress" placeholder="Cooperative Address" value="<?= set_value('cooperativeaddress') ?>" class="form-control" >
</div>
<div class="mb-3">
<input type="text" name="cooperativecontactnumber" placeholder="Cooperative Contact Number" value="<?= set_value('cooperativecontactnumber') ?>" class="form-control" >
</div>
<button type="submit" id="submit_preg" class="btn btn-danger">Register</button>
<p>Has existing account? <a href="<?php echo base_url(); ?>/login">Login</a></p>
</form>
</div>
</div>
</div>
<?php echo view('scripts'); ?>
<script>
$('#coop').select2({
placeholder: "Select Cooperative...",
/* ajax: {
url: '<?php //echo base_url('LiveSearchController/getRecords');?>',
dataType: 'json',
delay: 355,
cache: true,
processResults: function (records) {
return {
results: records
};
}
} */
});
$('#coop').on('select2:select', function () {
var selCoopVal = $('#coop').find(':selected').data('value');
//alert(selCoopVal);
});
$('#position').select2({
placeholder: "Select Position...",
/* ajax: {
url: '<?php //echo base_url('LiveSearchController/getRecords');?>',
dataType: 'json',
delay: 355,
cache: true,
processResults: function (records) {
return {
results: records
};
}
} */
});
$('#position').on('select2:select', function () {
var selPositionVal = $('#position').find(':selected').data('value');
//alert(selPositionVal);
});
</script>
<script>
if ($("#pregform").length > 0) {
$("#pregform").validate({
rules: {
firstname: {
required: true,
},
midinitial: {
required: true,
maxlength: 3,
},
lastname: {
required: true,
},
email: {
required: true,
maxlength: 50,
email: true,
},
repcontactno: {
required: true,
maxlength: 13,
},
contactperson: {
required: true,
},
cooperativeaddress: {
required: true,
},
cooperativecontactnumber: {
required: true,
maxlength: 13,
},
},
messages: {
firstname: {
required: "Please enter Firstname",
},
midinitial: {
required: "Please enter Middle Initial",
},
lastname: {
required: "Please enter Lastname",
},
email: {
required: "Please enter valid email",
email: "Please enter valid email",
maxlength: "The email name should less than or equal to 50 characters",
},
repcontactno: {
required: "Please enter Contact Number",
},
},
submitHandler: function(form) {
$('#submit_preg').html('Sending..');
$.ajax({
url: "<?php echo base_url(); ?>/PreRegController/store",
type: "POST",
data: $('#pregform').serialize(),
dataType: "json",
success: function( response ) {
console.log(response);
//console.log(response.success);
$('#submit_preg').html('Submit');
$('#alertmessage').html('Successfully Registered!');
$('#alertmessage').show();
$('#alertmessage').removeClass('d-none');
document.getElementById("pregform").reset();
setTimeout(function(){
$('#alertmessage').hide();
$('#alertmessage').html('');
},10000);
},
error: function(xhr, status, response){
var errorMessage = xhr.status + ': ' + xhr.statusText;
console.log(errorMessage);
console.log(response);
},
});
}
})
}
</script>
</body>
</html>`
When I click submit, the record will be save on database (MySQL). But there is a AJAX error.
I can’t see the mistake, hopefully somebody could help.
TIA
I expect it will have no error the submit button’s label will go back to "Submit"
2
Answers
I got it. I try removing the validation on controller. since I already had one on ajax. It works! :)
I think you enabled CodeIgniter developer mode. So it returns some HTML data for debug with response. So it is not valid JSON. Try enabling production mode. It will send only JSON response.