2

In the post How to use Ajax.BeginForm MVC helper with JSON result? Joel references a solution as follows:

function onTestSuccess(data, status, xhr) { 

    console.log("data", data); 
    console.log("xhr", xhr); 
    console.log("status", status); 

    // Here's where you use the JSON object 
    //doSomethingUseful(data); 
} 

How do I reference elements in the JSON object "data" in my code? My console log shows the following: LOG: data{"success":true,"uri":"/Image/Confirm2?category=foo"}

I am trying to use the value of "uri" in my jquery code. I've tried:

console.log("uri", data.uri);

but get the folowing as a result:

LOG: datauriundefined

1 Answer 1

1
function onTestSuccess(data, status, xhr) { 
    var uri = data.uri;
    // uri = '/Image/Confirm2?category=foo' at this stage 
    // so you could do something useful with it
} 

Also for this to work you need to use the OnSuccess="onTestSuccess" setting in your AjaxOptions when setting up the Ajax.BeginForm instead of OnComplete="onTestSuccess".


It turns out that the problem is with your controller action in which you specified incorrect Content-Type of text/html.

So instead of:

String uri = Url.Action("Confirm2", "Image", new RouteValueDictionary(new { category = "foo" })); 
return Json(new { success = true, uri = uri }, "text/html");

you should use:

String uri = Url.Action("Confirm2", "Image", new RouteValueDictionary(new { category = "foo" })); 
return Json(new { success = true, uri = uri });
Sign up to request clarification or add additional context in comments.

8 Comments

Unfortunately I am still not having much success.
see code: var uri = data.uri; console.log(uri); displays LOG: undefined
@user1219694, you should use OnSuccess="onTestSuccess" instead of OnComplete="onTestSuccess" in your AjaxOptions.
Yes - that is what I am doing @using (Ajax.BeginForm("create", "Guide", new AjaxOptions { HttpMethod = "Post", OnSuccess = "JsonCreateGuide_OnComplete" }))
And your controller action return Json(new { uri = "/Image/Confirm2?category=foo" })? You may also try console.log($.parseJSON(data).uri);.
|

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.