I post data via ajax to my controller which does some validating and sends it off to the model. My table has a unique index to prevent duplicates. Unique inserts work fine, my problem is I can’t seem to catch the duplicate error and deal with it.
Model Code:
function insert($data) {
//die($this->db->last_query);
try{
$query = $this->db->insert('subscriber',$data);
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
if($query){
return true;
} else {
return false;
}
}
jQuery ajax call:
function runAjax() {
$('#theform').append('<p id="loading"><img src="<?php echo base_url();?>' + 'images/loader.gif"/>');
$.ajax({
type: "POST",
cache: false,
url: "<?php echo base_url();?>" + 'contact/mail',
data: 'fname=' + $('#fname').val() + '&lname=' + $('#lname').val() + '&email=' + $('#email').val(),
success: function(msg){
$('#response').remove();
$('#theform').append('<p id="response">' + msg + '</p>');
$('#loading').fadeOut(500, function() {
$(this).remove();
});
},
error: function(msg){
$('#theform').append('<p id="response">' + msg + '</p>');
}
});
Errors from MySQL are not thrown as exceptions and hence you cannot catch them.
Instead, if you query results null, you can print out the messages with db->_error_message() and db->_error_number() (http://codeigniter.com/forums/viewthread/79950/#413830). As such, you could rewrite your code as follows:
Also note that
errorinside$.ajaxis only called if there is an error performing the request. Even though your database query fails, it still doesn’t make the Ajax query fail. Hence, you will never the Ajax error.I see two options here:
1) Make the HTTP request fail somehow (e.g. return HTTP 404 error).
2) Process your MySQL errors inside
successmethod, instead oferror: