Tiago
Tiago

Reputation: 365

AJAX call don't call MVC method and returns success

I'm trying to make AJAX request to a MVC method located in DefaultController.cs

var booking = { price: price, distance: distance }
$.ajax({
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify({ booking: booking }), //Turns into: "{\"booking\":{\"price\":\"56.1376\",\"distance\":\"35086\"}}"
    url: "/Default/submitBooking",
    cache: false,
    success: function (data) { alert("success " + data.d) },
    error: function (XMLHttpRequest, textStatus, errorThrown) { if (errorThrown != 'abort') debugger; }
})

It returns success undefined, and no breakpoint in the submitBooking() method is hit.

public ActionResult submitBooking(Booking booking)
{
   return Json(new { success = true, message = "Booking success" }, JsonRequestBehavior.AllowGet);
}

The Booking class:

public class Booking
{
    decimal price; decimal distance;
    public decimal Price
    {
        get { return price; }
        set { price = value; }
    }
    public decimal Distance
    {
        get { return distance; }
        set { distance = value; }
    }
}

Upvotes: 0

Views: 225

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337550

The issue is because your Action is returning JSON with success and message properties. Your JS code is then attempting to read a property from the response named d, which does not exist, hence the undefined value you see.

To fix this you just need to amend your JS code to read the right properties from the response:

var booking = { price: price, distance: distance }
$.ajax({
  contentType: "application/json; charset=utf-8",
  data: { booking: booking }, // no need to JSON.stringify here, jQuery does it for you
  url: "/Default/submitBooking",
  cache: false,
  success: function (data) {  
    console.log(data.success);
    console.log(data.message);
  },
  error: function (XMLHttpRequest, textStatus, errorThrown) { 
    if (errorThrown != 'abort') 
      debugger; 
  }
})

Upvotes: 1

Related Questions