1

Stuck into a weird problem. My ajax call is showing response as following:

enter image description here

My ajax response is not going to success function.

Asp.Net Core code:

[HttpPost]
[AutoValidateAntiforgeryToken]
public async Task<JsonResult> Create(CityCreateUpdateVm vm)
{
    if(ModelState.IsValid)
    {
        Thread.Sleep(5000);
        var response = await _cityService.Create(vm);

        return Json(response);
    }

    return Json(new { });
}

_cityService service is returning following object:

public class AjaxResponseVm
{
    public List<string> Errors { get; set; }

    public bool IsOk
    {
        get
        {
            return Errors.Count > 0 ? false : true;
        }
    }

    public AjaxResponseVm()
    {
        Errors = new List<string>();
    }

    public void AddError(string error)
    {
        if (Errors != null && error != string.Empty)
        {
            Errors.Add(error);
        }
    }
}

Here is my form:

<form asp-controller="city" asp-action="create" id="cityCreateFrom" method="post" onsubmit="return CreateResource('cityCreateFrom', 'City created successfully.')">
    <partial name="_CityInfo.cshtml" />
</form>

Parial view just have 2 text boxes.

Here is my jQuery code:

function CreateResource(formid, successfulmessage) {

var form = '#' + formid;

if ($(form).valid()) {

    Swal.fire(
        {
            type: "success",
            text: "Working...",
            allowOutsideClick: false
        });
    Swal.showLoading();

    $.ajax({

        type: form.attr('method'),

        url: form.attr('action'),

        data: form.serialize(),

        async: true,

        dataType: "json",

        contentType: "application/json; charset=utf-8",

        success: function (response) {

            Swal.close();

            if (response.isOk) {

                Swal.fire(
                    {
                        title: successfulmessage,
                        icon: "success",
                        type: "success",
                        confirmButtonClass: "btn bg-gradient-primary",
                        confirmButtonText: "Ok",
                        allowOutsideClick: false,
                    })
                    .then((result) => {

                        if (result.isConfirmed) {

                            window.location.href = 'index';
                        }
                    });
            }
            else {
               
                var errorList = '<ul>';

            }
        },

        error: function (response) {

            Swal.fire(
                {
                    title: "Something went wrong.",
                    icon: "error",
                    type: "error",
                    confirmButtonClass: "btn bg-gradient-danger",
                    confirmButtonText: "Ok",
                    allowOutsideClick: false,
                });
        },
    });
}

return false;
}

Response is correctly returning from Asp.Net Core. The problem is response is not going to the success function but it is showing JSON as shown in above picture.

Any help will be appreciated.

Regards D

Update 1

I don't know why it is submitting this request:

enter image description here

Not the content-type here. I don't know why it is "application/x-www-form-urlencoded" instead of json. I think this is the problem.

8
  • Can you post _cityService.Create pls? Commented Jun 13, 2021 at 9:38
  • @Serge: I have updated the question, added return response class from service. Commented Jun 13, 2021 at 9:42
  • How you submit your form ? I can't see any button submit. Commented Jun 13, 2021 at 10:16
  • @Serge: It has a submit button with following code: <button class="btn bg-gradient-primary" type="submit" style="width: 140px !important"> Create</button> Commented Jun 13, 2021 at 10:17
  • Why are you returning the js function in onSubmit instead of just calling it there? Commented Jun 13, 2021 at 10:43

1 Answer 1

1

This is the default form submit behavior, you should stop it if you want it submit with ajax.

<form asp-controller="city" asp-action="create" id="cityCreateFrom" method="post" onsubmit="return CreateResource(event, 'cityCreateFrom', 'City created successfully.')">
    <partial name="_CityInfo.cshtml" />
</form>

function CreateResource(event, formid, successfulmessage) {
    event.preventDefault()
    //...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Did exactly this and everything worked fine. Thank you. Cheers ^^

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.