1

I'm passing some string messages as Json object in view.

public ActionResult SomeAction(someObject object)
{            
    .....
    .....
    
    if (check1)
    {
        return Json(new { error = Resource.someMessage1},JsonRequestBehavior.AllowGet);
    }
    if(check2)
    {
        return Json(new { error = Resource.someMessage2}, JsonRequestBehavior.AllowGet);
    }
 
    //some stuffs

    return Json(new {success = "success"}, JsonRequestBehavior.AllowGet);
}

I want to retrieve the messages passed from controller and alert from My view

in view I have some javascript

function done(data) {
    alert("hello");
    var message = JSON.parse(data);
    alert(message);
    if (message["error"] != undefined) {
        alert(message["error"]);
    } else {
     //do some stuff

    }
};

what I was expecting is if passed message from controller is type error then I would get alert with the message.

The line alert("hello"); but there is no alert after that. I get error in console

enter image description here

Am I doing something wrong?

6
  • 1
    console the value present in the "data" and share it here, want to know what is passed to this done() function. Commented Mar 26, 2014 at 8:34
  • @Biplov..can you post your view code? Commented Mar 26, 2014 at 8:38
  • You mean the response sent? If yes, then this is what I see as response in browser {"error":"somemessage"}. If no, I probably didn't understand what u meant, sorry. Quite new to this front end thing Commented Mar 26, 2014 at 8:39
  • @Biplov..there is no need to parse the data Commented Mar 26, 2014 at 8:39
  • @AvinashKothamasu but when I alert data I get [object object] as alert Commented Mar 26, 2014 at 8:40

4 Answers 4

2

If you execute the following line of code

var a = { success : "success" };
var b = JSON.parse(a);

you will get the error you have mentioned about "SyntaxError: Unexpected token o..."

Don't know why are you trying to convert your already JSON object using JSON.parse(), instead you could use this

a.success

to read the "success" value .

Sign up to request clarification or add additional context in comments.

Comments

1

the variable type is detected as json object.

var x = {"error":"somemessage"};
alert(x.error)

The variable is detected as String here.

var x = JSON.parse('{"error":"somemessage"}'); alert(x.error)

If you notice, the difference is #1 starts with {(curly braces) whereas #2 starts with '(apostrophe)

Comments

0

Try not parsing the answer (so remove "JSON.parse(data)" line) and read everything directly from "data" variable.

Comments

0

You have to use data.sucess to get your result . There is no need to parse again.

Comments

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.