UwakPeter
UwakPeter

Reputation: 341

How to return json object on post request with message to ajax function

I want to be able to return json object with a custom error/success message using the same line of code on post request: i have these two lines of code:

return Json(data);
return Json(new { f = "error" });

I want to be able display it in one line like this:

return Json(data, Json(new { f = "error" }));

I know i can't have multiple return statements in my code. but i want to return the data with message.

My ServerSide Code:

if (getId > 0)
{
    var getList = appointmentRepository.GetAppointmentList(userId);
    var data = Newtonsoft.Json.JsonConvert.SerializeObject(getList);                       
    return Json(data);
    return Json(new { s = "success" });
}
else
{
    var getList = appointmentRepository.GetAppointmentList(userId);
    var data = Newtonsoft.Json.JsonConvert.SerializeObject(getList);
    return Json(data);
    return Json(new { f = "error" });
}

My Ajax Fucntion:

<script type = "text/javascript">
   $(document).ready(function () {
      $('#tblAppointment').DataTable({
         dom: 'Bfrtip',
         buttons: [
            'copyHtml5',
            'excelHtml5',
            'csvHtml5',
            'pdfHtml5'
         ]
      });

      var table = $("#tblAppointment").DataTable();
      $("#saveButton").click(function () {

         console.log("appDate:" + $('.datetimepicker').val());
         $.ajax({
            url: '/Appointment/InsertPatientAppointment/',
            type: "POST",
            data: JSON.stringify({
               appointmentDate: $(".datetimepicker").val(),
               patientRegNo: $("#patientRegNo").val(),
               reasons: $("#reasons").val()
            }),

            cache: false,
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (_data) {
               if (_data.f !== undefined) {
                  swal({
                     title: "Failed!",
                     text: _data.f, //"Ooops! something went wrong, 
                     record not saved,
                     try again later ",
                     type: "info"
                  });
                  table.clear().draw();
                  //table.destroy();
                  // $("#viewReportBtn").prop("disabled", false);
                  return false;
               } else {
                  swal({
                     title: "Success!",
                     text: _data.s, //"Appointment added successfully!",
                     type: "success"
                  });

               }
               $(".datetimepicker").val('');
               $("#patientRegNo").val('');
               $("#reasons").val('');

               var arr = $.map(JSON.parse(_data), function (el) {
                  return
                  el
               });

               if (arr.length === 0) {
                  swal({
                     title: "No Record Found!",
                     text: _data.f, //"Your search returns an empty 
                     result set !",
                     type: "info"
                  });
                  table.clear().draw();
                  return false;
               }
               table.clear();
               table.destroy();
               $('#tblAppointment').dataTable({
                  data: arr,
                  columns: [{
                        "data": "MatricRegNo"
                     },
                     {
                        "data": "PatientName"
                     },
                     {
                        "data": "EntryDate"
                     },
                     {
                        "data": "AppointmentDate"
                     },
                     {
                        "data": "Reasons"
                     },
                     {
                        "data": function (data, type, row, meta) {
                           return '<span class="fa fa-edit" data- 
                           toggle = "modal"
                           data - target = "#modal-Edit" > < /span>';
                        }
                     }
                  ],
                  dom: 'Bfrtip',
                  buttons: [
                     'copy', 'csv', 'excel',
                     {
                        extend: 'pdfHtml5',
                        orientation: 'Portriat',
                        pageSize: 'A4'
                     }
                  ]
               });
               table = $("#tblAppointment").DataTable();
            }
         });
      });
   });
</script>

Upvotes: 1

Views: 2523

Answers (3)

croxy
croxy

Reputation: 4170

You can integrate the data object in your anonymous object which you are already returning:

return Json(new {data = data, f = "error"});

If you do it like this, you can access the data object in your ajax call like this:

success: function (_data) {
    var returnedData = _data.data;
}

Which means you have to adjust your map method call where you are preparing the data array for the table. Instead of:

var arr = $.map(JSON.parse(_data), function (el) { return el });

call it with the data object _data.data:

var arr = $.map(JSON.parse(_data.data), function (el) { return el });

This should do the trick.

Upvotes: 0

Enrique Gonz&#225;lez
Enrique Gonz&#225;lez

Reputation: 180

You can use this:

var data = Newtonsoft.Json.JsonConvert.SerializeObject(getList);

var returnData = new object[2];
  returnData[0] = data;
  returnData[1] = new { f = "error" };
  return Json(returnData);

Upvotes: 1

Greg
Greg

Reputation: 11480

I would potentially approach in the following manner, extend the JsonResult to include a status code. This way you can dictate the level of success to the Ajax request.

public class JsonResultWithStatusCode : JsonResult
{
     private readonly HttpStatusCode statusCode;

     public JsonResultWithStatusCode(object data, HttpStatusCode statusCode)
     {
          Data = data;
          this.statusCode = statusCode;
     }

     public override void ExecuteResult(ControllerContext context)
     {
         context.RequestContext.HttpContext.Response.StatusCode = (int)statusCode;
         base.ExecuteResult(context);
     }
}

Then inside your controller:

if(...) 
{
     var model = JsonConvert.SerializeObject(...);
     return new JsonResultWithStatusCode(model, HttpStatusCode.Ok)
}

else 
{
     var model = new { error = "..." };
     return new JsonResultWithStatusCode(model, HttpStatusCode.InternalServerError);
}

Then inside your Ajax you would be able to read the status code and then read the body.

.success: function(response) {
     console.log(response.status); // Status Code (200 or 500 based on above)
     console.log(response.data); // Our model based on above, one writing error the other actual model data.
}

All you would have to do would be read based on the server output.

Upvotes: 0

Related Questions