1

I know this topic has been talked about quite often, but I can't find answer that specifically targets what I'm after. Many point to accessing one return object. I need to access both

I can't seem to figure out how to access the parameters of a Json object when returned to an Ajax call. I've consoled out and can see the response is there. The two items within the data section are correct. I just don't know how to correctly access them.

The response is coming from a controller. with this returned.

 else
    {           
        string sl = subLineData[0];
        string d = "fail";
        var result = Json(new { param1 = d, param2 = sl });
        return Json(result, JsonRequestBehavior.AllowGet);

    }

This is the Ajax call.

   $.ajax({
    url: '/Trucking/SubLineValuesInsert',
    type: 'POST',
    contentType: 'application/json',
    data: data,
   success: function (response) {
       console.log(response); 

       if (data.param1 === "fail") {
           alert(data.param2 + " already exists");
       }
       // console.log(response);
    },
    error: function () {
        //alert('Error');
        console.log('Error');
    }
});     

The data.param1 was me trying to access the data this way. I get undefined of course with this.

Here is an image the console.log(response) showing it does return, I just need to access it so I can use some conditional logic after. It's the param1 and param2 I am after. Your help is always appreciated.

enter image description here

2 Answers 2

1

data contains the object you send in the request. To access the Data property of the object you return in the response you need to use response.Data:

success: function (response) {
  if (response.Data.param1 === "fail") {
    alert(response.Data.param2 + " already exists");
  }
},
Sign up to request clarification or add additional context in comments.

1 Comment

Mcrossan. Thanks .. You posted yours right as I posted mine. I worked out a solution, but now I have two! Just tried your response and works great. Thanks.
0

Found my answer here Send to and get value from a MVC3 controller by AJAX. Specifically the return Json and how I access it in Ajax call.

Here is the Json return

       else
         {
            string sl = subLineData[0];
            return Json(new {Success = false, Result = sl }, JsonRequestBehavior.AllowGet);
         }

Here's the Ajax call now:

  $.ajax({
    url: '/Trucking/SubLineValuesInsert',
    type: 'POST',
    contentType: 'application/json',
    data: data,
   success: function (result) {
       if (!result.Success) {
           alert(result.Result + " already exists");
       }
    },
    error: function () {
        //alert('Error');
        console.log('Error');
    }
});    

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.