-2

I'm trying to get returned data by json after jquery.post but...

    <script>
        function sendToJsonTitleConverter() {
            $.post("/engine/title-converter", {
                NewTitle: $("#NewTitle").val()
            });
        }
    </script>

MVC:

    public ActionResult JsonTitleConverter()
    {
        if (!string.IsNullOrWhiteSpace(Request.Form["NewTitle"]))
        {
            string title = myFunction.ClearTitle(Request.Form["NewTitle"]);
            var result = new LinkedList<object>();
            result.AddLast(new
            {
                Title = title
            });
            return Json(result, JsonRequestBehavior.AllowGet);
        }
        else
        {
            return null;
        }
    }

Returned Json:

[{"Title":"test 21312 asdasd asas"}]

How can I get Title in javascript?

Erçin Dedeoğlu
  • 4,950
  • 4
  • 49
  • 69

2 Answers2

1

You need a "callback", which are functions that are set to execute when an async operation is done. Sort of a "to-do", since you can't do sequential code for a non-sequential operation.

In this example, I prefer using the deferred style of adding a callback, so that the name of the function (in this case, done) is readable. You can additionally put fail and complete without being confused.

Additionally, you need to state that you are getting JSON data. jQuery sometimes fails in getting the type right, especially on their shorthand functions.

$.post("/engine/title-converter", {
    NewTitle: $("#NewTitle").val()
  },'json')
  .done(function(data){
    var title = data[0].Title
  });
Joseph
  • 117,725
  • 30
  • 181
  • 234
1

Like this:

function sendToJsonTitleConverter() {
    $.post("/engine/title-converter", {NewTitle: $("#NewTitle").val()}, function(data){
         var title = data[0].Title;
         alert(title);
    }, 'json');
}

Cheers

Edgar Villegas Alvarado
  • 18,204
  • 2
  • 42
  • 61