0

I have an ajax post method to ad new records to a database, the process itself works ok and my server side code traps errors (duplicate input, etc). When an eror happens, the ajax method doesnt 'see' it, the 'success' function is always called. This is my ajax post method

$.ajax({
                            url: '@Url.Action("Add", "Organisation")',
                            data: $form.serialize(),
                            async: true,
                            type: 'POST',
                            error: function (returnval) {
                                $form.parents('.bootbox').modal('hide');
                                bootbox.alert('There was an error saving this organisation : ' + returnval['responseText']);
                            },
                            success: function (returnval) {
                                // Hide the dialog
                                $form.parents('.bootbox').modal('hide');
                                bootbox.alert('New Organisation successfully added');
                            }
                        })

and the actionmethod on my controller

[HttpPost]
    [ValidateAntiForgeryToken]
    public JsonResult Add(OrganisationEditCreateViewModel data)
    {
        InsertOrganisationRequest request = new InsertOrganisationRequest();
        IEnumerable<ModelError> allErrors = ModelState.Values.SelectMany(v => v.Errors);
        if (ModelState.IsValid)
        {
            var model = mapper.Map<OrganisationEditCreateViewModel, OrganisationDto>(data);
            request.organisation = model;
            var response = this._organisationService.InsertOrganisation(request);
            if (response.isSuccess)
            {
                return Json(new { success = true, responseText = "New organisation added successfully" }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(new { success = false, responseText = "Error adding new organisation : " + response.Message }, JsonRequestBehavior.AllowGet);
            }
        }
        return Json(new { success = false, responseText = "Error adding new organisation : Invalid input" }, JsonRequestBehavior.AllowGet);
    }

so when I insert a duplicate record, the serverside code traps this and this branch of code is returned back to my ajax call

return Json(new { success = false, responseText = "Error adding new organisation : " + response.Message }, JsonRequestBehavior.AllowGet);

but the ajax call always calls this bit of code

success: function (returnval) {
                                // Hide the dialog
                                $form.parents('.bootbox').modal('hide');
                                bootbox.alert('New Organisation successfully added');
                            }

the error part never gets called, what am I doing wrong ?

  • 1
    Nowhere in your method are you throwing an exception, so it will not hit the `error` function. You need to check the value of `returnval.success` –  Apr 05 '17 at 10:09

2 Answers2

0

Update your success method!

 success: function (returnval) 
        {
           if(returnval.success=true)
           {
             // Hide the dialog
             $form.parents('.bootbox').modal('hide');
            bootbox.alert('New Organisation successfully added');
           }
           if(returnval.success=false)
           {
             $form.parents('.bootbox').modal('hide');
             bootbox.alert('There was an error saving this organisation : ' + returnval['responseText']);
           }
        }

hope helps!

Zaheer Ul Hassan
  • 771
  • 9
  • 24
  • had to change returnval.success=false to returnval.success==false but that did the trick, thank you so much, ive been trying to figure this out for a while. I cant quite see the point of the error: function part though if it doesnt actually work :-( – user2347338 Apr 05 '17 at 10:49
  • error function will get hit if there comes error in ajax call, but ajax call is working good and returning in success. now you need to add check point in success method. – Zaheer Ul Hassan Apr 05 '17 at 10:57
0

You are not doing anything wrong.Actually your code is also working fine,the reason is Success function always getting executing because your AJAX call successfully happening.

If AJAX call failed then only error function will get execute.

Example suppose if you gave Ajax attribute contentType wrong

ex:- contentType:'xyzfds';

in some scenario or may be because of any another ajax method attribute wrong value.So no need to worry about it.

If you want to display your error message then follow below approach it may help you.Thank You

                     success: function (returnval) {
                           if(returnval!=null){
                           if(returnval.success){
                           // Hide the dialog
                            $form.parents('.bootbox').modal('hide');
                            bootbox.alert('New Organisation successfully added');
                         }
                         if(returnval.success==false){ 
                           $form.parents('.bootbox').modal('hide');
                            bootbox.alert('There was an error saving this organisation : ' + returnval['responseText']);
                    }                             
                   }
                  }