I am trying to make an AJAX call when I click on a button. My program should send a request to the server to fetch some data and display it on the page. To keep things simple I first need to understand how I could make the AJAX call to work. I tried the following:

My controller in ASP.Net MVC5 C#:

[HttpPost]
public string MyMethod(int somePara)
{
    return "it worked";
}

My AJAX call:

$("button#test").on("click", function() {
  $.ajax({
    type: "POST",
    url: loc + "/MyMethod",
    data: somePara = "",
    success: function(data) {
      alert(data);
    },
    error: function() {
      alert("Error")
    }
  });
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<button class="btn btn-default btn-lg btn-block" id="test">
    <span class="glyphicon glyphicon-time"></span>
    Test
</button>

(Where loc field within the AJAX call would define my controller.)

When I run this code locally, my AJAX call will return the error part.

What should I change? Is there a way I could detect why this is happening?

1 Answers

1
Hien Nguyen On Best Solutions

The issues of your request

  • Not correct data format somePara = "111" => JSON.stringify({ somePara: "111" }),

  • Did not defined dataType

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

  • Action did not return JSON format.

Controller action

  [HttpPost]
    public JsonResult MyMethod(int somePara)
    {
        return Json("it worked", JsonRequestBehavior.AllowGet);
    }

AJAX

 $("button#test").on("click", function () {


       $.ajax({
                    type: "POST",
                    url:  "/Home/MyMethod", // i try home controller
                    data: JSON.stringify({ somePara: "111" }),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        alert(data);
                    },
                    error: function () {
                        alert("Error")
                    }
                });
            });

Update: the action should change to MyMethod(int? somePara) to prevent somePara : "" cant cast to int.