0

Following is the 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) {

                    d= data.split('@@@')[0]);

                },
                error: function (xhr) {
                   alert(xhr.responseText);

                }
            });
   var reutnData = "<div class='chatBody' id='chatBody" + this.id + "' >"+d+"</div>";
            return reutnData;
        };
       D.create = function () {
            var exist = $("#Container").find("div[id=chatbox" + this.id + "]");
            if (exist.length == 0) {

                   var ToAppend = "<div id='chatbox" + this.id + "' style='" +  D.style() + "' class='chatboxclass' >" + D.header() +D.body()+ "</div>";
                $("#Container").append(ToAppend);
                align++;
            }

        };

        return D;
    }

 function NewChat(id,username,picture) {

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

d is always undefined and it's not returning the ajax request what am I doing wrong ?

Arun Bertil
  • 4,598
  • 4
  • 33
  • 59
Sora
  • 2,465
  • 18
  • 73
  • 146
  • 2
    An ajax call is asynchronous. You can access 'd' in the success function, but should not try to access it anywhere else! – MrP Sep 20 '13 at 07:19
  • so there is no other way to achieve it ? – Sora Sep 20 '13 at 07:20
  • Not the way you are doing it right now, you will have to do it using a callback. – MrP Sep 20 '13 at 07:25
  • http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call/14220323#14220323 – Armand Sep 20 '13 at 07:26

1 Answers1

0

Sample code:

JS-

var dataString = 'ExtrFlag=GetChat&userID=1&FriendID=' + this.id

$.ajax({
         type: "POST",
         url: "ajax_function/updatefn.asmx/addABC",
         data: "{ 'prefix': '" + dataString + "'}",
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         success: OnSuccessCall,
         error: OnErrorCall
    });


 function OnSuccessCall(response) {
                var responeValue = response.d;
                var costpart = String(responeValue).split("-");
                var get_id = costpart[1];
.....
}

Code-Behind:

   [WebMethod]
    public string[] addABC(string prefix)
    {
        string status = ""; string strFLag="";
        string val_id = "";
        string datastr = prefix;
        string[] val = datastr.Split('&');
        string[] extrFlag = val[0].Split('=');
        strFLag= extrFlag [1];
        // code logici .i.e  which returns strFLag="abc";  val_id="23";

        d.Add(string.Format("{0}-{1}", strFLag, val_id));
        return d.ToArray();
    }
Satinder singh
  • 10,100
  • 16
  • 60
  • 102