Ajax Example

Simple Version

function delete_item(id, callback){
    var params = {
        acc_no:acc_no
    }
 
    $.ajax({
        type: 'get',
        url: base_url + 'admin/member/ajax/delete',
        data: params,
        dataType: 'json',
        success: function(res){
            //console.log(res);
            if(typeof res.status == 'undefined'){
                alert(res);
                return;
            }else if(res.status == 'fail'){
                alert(res.message);
                return;
            }
                 
            var data = res.data;
            alert('新增成功');
             
            var data = res.data;
            if(typeof callback == 'function'){
                callback.call(null, data);
            }
        },
        error: function(res){
            console.log(res);
            alert('系統錯誤');
        }
    });
}
  • Response handler
  • HTTP Status code detection
  • Error Handlers
function delete_item(id, callback){
	var params = {
		acc_no:acc_no
	}

	$.ajax({
		type: 'post',
		url: base_url + 'admin/member/ajax/delete',
		data: params,
		dataType: 'json',
		success: function(res){
			//console.log(res);
			if(typeof res.status == 'undefined'){
				alert(res);
				return;
			}else if(res.status == 'fail'){
				alert(res.message);
				return;
			}
				
			var data = res.data;
			alert('新增成功');
			
			var data = res.data;
			if(typeof callback == 'function'){
				callback.call(null, data);
			}
		},
		error: function(res){
			//console.log(res);
			if(res.status == 419){//Detect CSRF token expire
				alert('網頁已過期,請重新整理');
				return;
			}

			//console.log(res);
            if(typeof res.responseJSON == 'undefined'){
                if(typeof res.responseText != 'undefined'){
                    alert(res.responseText);
                }else{
                    alert(res);
                }
            }else{
                var response = res.responseJSON;
                show_request_error($('#iform'), response.errors);
                alert('請檢查必填的欄位');
            }
		}
	});
}

function show_request_error($form, errors){
    var str = '';
    //console.log(errors);
 
    for(var key in errors){
        var err = errors[key];
        //str += err[0] + '\n';
        var $el = $form.find('[name="' + key + '"]');
        if($el.length != 0){
        	//console.log($el.next('.error').length);
        	if($el.next('.error').length == 0){
        		var $error = $('<div class="error invalid-feedback" style="display:block;">' + err[0] + '</div>');
        		$el.parent().append($error);
        	}else{
        		var $error = $el.next('.error');
        		$error.show();
        	}
        }
    }
}
$.ajax({
  statusCode: {
    404: function() {
      alert( "page not found" );
    }
  }
});

Reference: