Tyler Durden
Tyler Durden

Reputation: 2171

Passing data with jquery ajax

I always get the 'error' alert, and I can't figure out what's wrong. I'm just trying to get back the string ("testexpression") that I send. It has to be something with the data part, because without a parameter it works.

Here's the jquery part:

<script>

$("#meaning").blur(function () {

    $.ajax({ 
        type: "POST",
        url: '/GetMeaning/',
        data: {"expression" : "testexpression"},
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: successFunc,
        error: errorFunc
    });

    function successFunc(data, status) {
        $("#dictionaryDropDown").html(data);
    }

    function errorFunc() {
        alert('error');
    }
})
</script>

And this is the controller:

    public class GetMeaningController : Controller
{
    //
    // GET: /GetMeaning/

    [HttpGet]
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(string expression)
    {

        return Json(expression, JsonRequestBehavior.AllowGet);

    }

}

(update: the type is post, I was just trying it out with get as well, and I left it in)

Upvotes: 12

Views: 71303

Answers (2)

beautifulcoder
beautifulcoder

Reputation: 11320

On the back end side I recommend

return Json(
    new { this.expression = expression },
    JsonRequestBehavior.AllowGet);

Assuming you want to send back an actual JSON and not just some random string.

Upvotes: 0

Dennis Flagg
Dennis Flagg

Reputation: 664

You need to send data as a string/json. You are sending a javascript object. Also, The URL might need to be a absolute url and not a relative url

$("#meaning").blur(function () {

    $.ajax({ 
        type: "POST",
        url: '/GetMeaning/',
        data: JSON.stringify({expression: "testexpression"}),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: successFunc,
        error: errorFunc
    });

    function successFunc(data, status) {
        $("#dictionaryDropDown").html(data);
    }

    function errorFunc() {
        alert('error');
    }
})

Upvotes: 16

Related Questions