0

I have this jQuery ajax:

        // ... omitted code ...

        var data = "{'TagName':'" + TagName + "'}";

        var resultSet = 0;

        jQuery.ajax(
        {
            type: "POST",
            url: '<%= ResolveUrl("~/Webservices/TagWebServices.asmx/GetTagByTagName") %>',
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (t)
            {
                resultSet = t.d;
            }
        });

        jQuery(this).after("<div style='color:#E3E3E3; margin-bottom:10px;'>" +
        resultSet.desc +
        "</div>" );

        // ... omitted code ...

The problem is that resultSet.desc always returns "undefined" BUT when I use Firebug and add a breaking point in the last line and then click (Continue) resultSet.desc works as expected.

2
  • 2
    Welcome to the wonderful world of async! You can't do that. Commented Dec 3, 2012 at 14:37
  • This is the first time I use jQuery ajax but that makes sense it was a stupid mistake from my part. thanks Commented Dec 3, 2012 at 15:06

2 Answers 2

1

Ajax is asynchronous by default. You could try to set ajax request synchronous setting: async:false, but this is a bad way.

The way to go is to code your logic in the success callback function keeping ref on 'this' object.

var data = "{'TagName':'" + TagName + "'}";

        var resultSet = 0,
            that = this;

        jQuery.ajax(
        {
            type: "POST",
            url: '<%= ResolveUrl("~/Webservices/TagWebServices.asmx/GetTagByTagName") %>',
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (t)
            {
                resultSet = t.d;
                 jQuery(that).after("<div style='color:#E3E3E3; margin-bottom:10px;'>" +
                    resultSet.desc +
                    "</div>" );
            }
        });
Sign up to request clarification or add additional context in comments.

Comments

1

An ajax call is Asynchronous (by definition...). So you have to put the affectation in the success handler:

$.ajax({ ...
    success : function(t) {
        resultSet = t.d;
        jQuery(this).after("<div style='color:#E3E3E3; margin-bottom:10px;'>" +
            resultSet.desc +
        "</div>" );
    }
)};

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.