Javascript Ajax jQuery Html PHP Example Quiz New MORE

jQuery AJAX try catch example


Create a common.js file and add the below Code.

function fetchData(dataURL,method,data={}) {

return jQuery.ajax({
type:method,
data: data,
dataType: 'json',
url: dataURL
});
}
function catch_function(jqXHR, exception){
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {

msg = jqXHR.responseText; 
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
}else {
msg = jqXHR.responseText;
}
return msg;
}
Try and catch script example
<script>
$(document).on('click','#submitForm',function(e) {
var project_id=$("#ProjectID").val();
var FileNo=$("#FileNo").val();
var FileName=$("#FileName").val();
var service_id = [];

$("input[name='ServiceID']:checked").each(function(){
service_id.push(this.value);
});
var dataUrl = "<?php echo base_url()?>files/savefileno";
var method="POST";
var data={
"ProjectID":project_id,
"FileNo": FileNo,
"FileName": FileName,
"service_id":service_id
}
var ajaxData = fetchData(dataUrl,method,data)
jQuery.when(ajaxData).then(function(result){
window.location = `<?php echo base_url()?>files`;

}).catch(function(jqXHR, exception){

msg = catch_function(jqXHR, exception)
console.log("msg ",msg)
mymsg="";
alert(msg.toString());
});
});
</script>