Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax.BeginForm, Calls Action, Returns JSON, How do I access JSON object in my OnSuccess JS Function?

Ajax.BeginForm calls an action and then returns JSON. How do I access JSON object in my OnComplete js function?

so my Ajax.BeginForm looks like this...

using (Ajax.BeginForm("Coupon", new AjaxOptions { OnSuccess = "CouponSubmitted" }))

and my OnSuccess function looks like this...

function CouponSubmitted() {
    var data = response.get_response().get_object();
    alert(data.success);
}

I also tried...

function CouponSubmitted(data) {
    alert(data.success); 
}

My controller "Coupon" returns this...

return Json(new { success = false, nameError = nameError, emailError = emailError });

Any ideas on how to access the Json that gets returned?

like image 723
Jason Avatar asked Oct 26 '10 04:10

Jason


3 Answers

function OnSuccess(e) { //function CouponSubmitted(data) in the question
   var json = e.get_response().get_object();
   alert(json.success);
}

This is what the AJAX.BeginForm OnSuccess callback expects you to do to get your JSON back.

Hope I saved someone else some time on this ridiculously under documented "feature?".

like image 94
Jason Avatar answered Oct 21 '22 19:10

Jason


I bumped into this question looking for the answer to do the same thing in ASP.NET MVC 4, and none of the above worked, so for anyone looking for the answer, the data is already encoded from json when you recive it in your js function

 public ActionResult Something()
 {
    return Json(new { result = 0, message = "Testing" });
 } 

...

 new AjaxOptions { HttpMethod = "POST", OnSuccess= "something" }

...

function something(data) {
    switch(data.result)
    {
    case 1:
       alert(data.result)
    break;
    case 0:
        alert(data.result)
    break;
    case -1:
        alert(data.result)
    break;
    default:
        alert(data.message);
    }
}

This doesn't work with OnComplete I assuame it doesn't have paramtars to recive data.

like image 43
formatc Avatar answered Oct 21 '22 19:10

formatc


in asp.net mvc 4

function CouponSubmitted(data) {
    alert(data.success); 
}

will return parsed 'json'

like image 35
Mudasar Rauf Avatar answered Oct 21 '22 18:10

Mudasar Rauf