0

I have a javascript function which returns a value that I am trying to display in a table in my partial view.

In my main view I have something like this:

<script type="text/javascript">
    function myFunc(i) 
    {
        var url = '/myurl/?id=' + i;

        $.getJSON(url)
        .done(function (data) 
        {
            return data;
        }
    }
</script>

In my partial view html I am trying to do this:

<td><script>document.write(myFunc())</script></td>

The function gets called but it seems to always return undefined am I doing something wrong here?

8
  • try <td><script>window.myFunc();</script></td> Commented Jul 7, 2015 at 18:12
  • with the semi-colon it doesn't get called at all, without the semi-colon I get the same result "undefined" Commented Jul 7, 2015 at 18:16
  • <script>var data = window.myFunc(); console.log(data); </script></td> Commented Jul 7, 2015 at 18:18
  • 1
    You should check window object in your partial view. Please check <script>console.log(window); </script> Please check whether you're getting your function here ? Commented Jul 7, 2015 at 18:21
  • 1
    After watching your code I got to know it was happening because of async call of ajax. Commented Jul 7, 2015 at 18:47

2 Answers 2

1

This is because you are not passing parameter in function and function aspect parameter.. which is null at this stage.

  • your call ...

    document.write(myFunc())

  • and your Function

    function myFunc(i)

  • so your URl become

    var url = '/myurl/?id=' + Null; // some thing like this

so URL is not correct and hence not getting correct data

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

Comments

0

Silly me, once I realized this was an asynchronous issue the solution was obvious and I should have done this in the first place...

<script type="text/javascript">
    function myFunc(i) 
    {
        var url = '/myurl/?id=' + i;

        $.getJSON(url)
        .done(function (data) 
        {
            document.getElementById("myDiv").innerHTML = data;
        }
    }
</script>

This did the trick.

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.