0

I'm beginner in asp.net mvc ,and want to fetch simple json from controller to ajax variable,for that purpose in view page write this ajax function:

<script>
    var OutPut;
    OutPut = "behzad";
    function CallService() {
        $.ajax({
            url: '@Url.Action("callService", "myPassword")',
            type: 'GET',
            dataType: 'json',
            cache: false,
            data: { 'id': 2 },
            success: function (color) {
                OutPut= color;

            },
            error: function () {
                alert('Error occured');
            }
        });
        alert("I think is ok!"+":"+OutPut);

    }
</script>


and this controller:

[HttpGet]
        public JsonResult callService(int id)
        {
            string JSON = "behzad";
            return Json(JSON,JsonRequestBehavior.AllowGet);

        }


that ajax function call with this html code in view page:

<button type="button" class="btn btn-success" onclick="CallService()">Success</button>


but this line in ajax function:

alert("I think is ok!"+":"+OutPut);


Output is undefined,what happen?is controller return null?or why i get undefined alert?thanks.

1
  • 2
    ajax is async and your alert(..) will be called before your ajax call returns a value. In the code you have shown, the output will be "behzad" (not undefined) because you have declared it globally. Commented May 8, 2016 at 5:58

1 Answer 1

2

Since the AJAX call is asynchronous, you should place the alert inside the success callback:

<script>
    function CallService() {
        $.ajax({
            url: '@Url.Action("callService", "myPassword")',
            type: 'GET',
            cache: false,
            data: { 'id': 2 },
            success: function (color) {
                alert("I think is ok!" + ":" + color);
            },
            error: function () {
                alert('Error occurred');
            }
        });
    }
</script>
Sign up to request clarification or add additional context in comments.

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.