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?

1

2 Answers 2

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.

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

5 Comments

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
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?
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
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.
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: stackoverflow.com/questions/20597445/…
0

You must use success:function(response){ }

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.