0

I have a function, that call a controller method using ajax

function CallService(data) {
        $.ajax({
            url: '@Url.Action("MyMethod", "MyController")',
            type: 'GET',
            dataType: 'json',
            cache: false,
            data: { 'serializedMessage': data }                
        });

MyMethod() returns a complex object and I need to display some properties on the page.

<script>
    $(function(){          

            // create inputData

            function (inputData) {                
                var myItem = CallService(inputData);                
                $('#name').text(myItem.Name);
            };
        });        
</script>

As ajax returns nothing, I get an error message 'myItem is undefined' on the page. Can anyone explain how to return a variable and use it in JS functions, please?

ADyson
  • 57,178
  • 14
  • 51
  • 63
Egor
  • 153
  • 1
  • 2
  • 10

2 Answers2

3

I'm surprised you couldn't find an example of this anywhere already, but here goes:

There are a few different ways of defining callbacks which can run when the ajax call completes, as shown in the docs at http://api.jquery.com/jquery.ajax/. Here is one, based on the promises API:

function (inputData) {                
    $.ajax({
        url: '@Url.Action("MyMethod", "MyController")',
        type: 'GET',
        dataType: 'json',
        cache: false,
        data: { 'serializedMessage': inputData }
    }).done(function(result) {
        console.log(JSON.stringify(result)); //just for debugging, to see the structure of your returned object
        $('#name').text(result.Name);
    });
}

One thing you need to grasp is that ajax calls run asynchronously, so the structure you had before will not work - you can't return anything directly from your "CallService" wrapper, which kind of makes it redundant. You have to wait until the ajax call completes, and run any code which depends on the result within (or within a function called from) the "done" callback.

As per the docs I linked to you can also define other callbacks for tasks such as handling errors, if you so desire.

ADyson
  • 57,178
  • 14
  • 51
  • 63
  • Thank you for your answer. Yes, you are right, there are a lot of resources with different solutions. And yes, I saw the page, you've shared above. But unfortunately for me it looks like .done() is never achieved. Even if I set $('#name').text("test name"); it is the same – Egor Sep 26 '17 at 16:46
  • in that case perhaps you have some other error? Have you checked your browser's tools to see if the ajax call succeeds or not? Do you get a 200 OK status back, or something else? What is contained in the response? – ADyson Sep 26 '17 at 17:23
  • Ajax returns 200 and response contains the custom object. It looks correct. The only issue is to get the result and display it. Never mind. I'll try to reorganize my code. Thank you so much for your help – Egor Sep 26 '17 at 17:41
  • perhaps `name` is not a direct property of the result? If you show me what `result` looks like (from the console.log command) I could help you. You also need to make sure you have an element on your page with `id="name"` attribute, and which is visible, in order to display it. – ADyson Sep 26 '17 at 17:45
  • 1
    many thanks for your help. In my case the issue was a "dataType: 'json' " parameter. Ajax works well after removing it. The solution was found here: https://stackoverflow.com/questions/20597445/jquery-ajax-done-callback-not-firing – Egor Sep 27 '17 at 08:46
0

You must use success:function(response){ }

ferhado
  • 2,363
  • 2
  • 12
  • 35