I'm trying to submit form data from view to controller using Ajax post and return success message.And ajax in my view send data to function in controller successfully but controller function does not return response back to ajax success function.
my Controller - profile.php
function save()
{
$response = array();
$this->form_validation->set_rules('fname', 'Title cant be empty ', 'required');
if ($this->form_validation->run() == TRUE)
{
$param = $this->input->post();
unset($param['submit']);
$param['rid']=$this->session->userdata('id');
$profile_id = $param['profile_id'];
unset($param['profile_id']);
if($profile_id == 0)
{
$inserts = $this->profile_model->insert($param);
if( $inserts>0){
$response['status'] = TRUE;
$response['notif'] ="success add profile details";
}else{
$response['status'] = FALSE;
$response['notif'] = 'Server wrong, please save again';
}
}else{
}
}else{
$response['status'] = FALSE;
$response['notif'] = validation_errors();
}
echo json_encode($response);
}
view - profile_new_user.php
?>
<form method="POST" id="form_profile" action="<?php echo base_url().'profile/save'; ?>">
<input type="hidden" name="profile_id" value="0"><!-------event id---------->
<div class="form-group">
<label>Prefix</label>
<select name="prefix" class="form-control">
.
.
.
</div>
<div class="form-group">
<input type="submit" name="submit" value="Save" class="btn btn-info" />
</div>
</form>
<script type="text/javascript">
$(document).ready(function() {
$("#form_profile").submit(function(event){
event.preventDefault();
$.ajax({
method: "POST",
url: $(this).attr("action"),
dataType :'JSON',
data: $(this).serialize(),
success: function(data)
{
if(data.status){
alert('ok');
}else{
alert('not ok');
}
}
})
});
});
model - profile_model.php
function insert($data)
{
$this->db->insert('user_profile', $data);
return $this->db->insert_id();
}
after I click submit button page redirect to url - http://localhost/ptm6/profile/save and page shows
{"status":true,"notif":"success add profile details"}
in plain text.
I expect to show alert message without any redirection.