0

I've tries setting breakpoints at the Controller method. But it does not stop there. The alerts "clicked" and the next one work perfectly fine. But the controller method is not called. Any help is appreciated. Here's my ajax call and my controller method.

var Url = "@Url.Action("~/Home/Get_Location")";

$("#gotoloc").click(function() {
  alert("clicked");
  alert(lat +" "+ lon);
  $.ajax({
    type: "POST",
    url: Url,
    data: { 
      latitude: lat, 
      longitude: lon    
    },
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(response) {
      alert("Hello:" + response)
    },
    failure: function(response) {
      alert(response.responseText);
    },
    error: function(response) {
      alert(response.responseText);
    }
  });
  alert("ignored");
});
public JsonResult Get_Location(double latitude,double longitude)
{
  string loc = latitude + "/" + longitude;
  return Json(loc, JsonRequestBehavior.AllowGet);
}
3
  • Do any of the other alert() calls fire? I'd expect the error one to at least. Check the console for errors Commented Jul 19, 2017 at 15:38
  • open your console and check for any errors. Also check your network tab Commented Jul 19, 2017 at 15:39
  • It says it cannot find the function. I have changed the Url content as Shyju suggested, But now, its throwing an alert saying 'Invalid Json Primitive latitude'. Commented Jul 19, 2017 at 15:44

1 Answer 1

1

You are using the Url.Action method incorrectly.

Try this

var Url = "@Url.Action("Get_Location","Home")";

The above overload takes the action method name as first parameter and controller names as second parameter

Also, i see you are passing incorrect contentType request header. contentType headers tells the server what is the type of data the client is sending. Your current code says you are sending json data. But you have 2 parameters in your action method and the json serializer will fail to properly map the posted data to it, hence you will be getting a 500 response from the server.

This should work, assuming there are no other js errors in your page

var url = "@Url.Action("Get_Location","Home")";

$.ajax({
    type: "POST",
    url: url,
    data: { latitude: 44, longitude: 55 },
    success: function (response) {
        console.log("Hello:" + response);
    },
    failure: function (response) {
        console.log(response.responseText);
    },
    error: function (response) {
        console.log(response.responseText);
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Well spotted, although I suspect this isn't the only issue if no other alert() calls are firing

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.