Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 915
Tyler Durden Avatar asked Oct 17 '13 23:10

Tyler Durden


1 Answers

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');
    }
})
like image 67
Dennis Flagg Avatar answered Oct 03 '22 22:10

Dennis Flagg