-2

so this is my code :

 function CreateDiv(D) {

   D.body = function () {

            var d =
                 $.ajax({
                     type: "GET",
                     url: "Default.aspx",
                     data: 'ExtrFlag=GetChat&userID=1&FriendID=' + this.id,
                     success: function (data) {
                         var StrResponse;
                         StrResponse = data.split('@@@');
                         return StrResponse[0];
                     },
                     error: function (xhr) {
                         return xhr.responseText;
                     }
                 });
            alert(d);

            return "<div class='chatBody' id='chatBody" + this.id + "' >" + d + "</div>";
     };

 }
 function NewChat(id,username,picture) {

        var div = new CreateDiv({ width: 250, height: 285, id: id, username: username, picture: picture });
        div.create();
    }

the problem is when the ajax call is executed the result is d=[object object] but in my case it should be a string because the ajax server side function always returns a string.

John Dvorak
  • 26,799
  • 13
  • 69
  • 83
Sora
  • 2,465
  • 18
  • 73
  • 146

2 Answers2

0

d is not the return value of the ajax request but the actual ajax request handler itself. the value that is returned from the server is data in your case.

Since ajax is by definition asynchronous you cant use it the way you are using it in a function. You should handle all the required proccessing in the success handler or you can return a handle on the ajax request itself and use $.when() and $.promise() to handle the processing elsewhere

DGS
  • 6,015
  • 1
  • 21
  • 37
0

You can't return a value from an asynchronous method, all the code that deals with the response of the ajax request should be added to the success/failure handlers of the ajax request.

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531