Link to home
Start Free TrialLog in
Avatar of AbebeDemeke
AbebeDemeke

asked on

a code behind method that can be called from a javascript and return list of strings

I have an aspx page that has a javascript and I wanted to use a code behind method that can accept parametrs and returns list of strings based on some operation to be performed. Here I am more interested to ensure the wiring between the javacript and the code behind method. Moreover I want to use the value returned from the web method in the java script for additional operations . Hence I have to store the value somewhere like in a hidden variable or some other variable. I have tried a webmethod but I am facing the problem of not getting the value returned from the web method outside of the onsuccess call back function . You can see the following code.

SO my question is do I have any other better option. or it that impossible to use the value retured by a web method ouside of the onsuccess call back fucntion? I need a help please





function webMethodCaller( ids){
         PageMethods.FormatName(ids,  onFormatNameSuccess,  onFormatNameFail,     onFormatNameTimeout);        
       
// i want to do something else based on result after this
//if I try to get the value in a hidden filed in here it is empty
}

 function onFormatNameSuccess(response)
{
      
                  
      var res="";
      
      for(var i=0,il=response.length; i<il;i++){
      res+=response[i];
      }
      
// i am trying to store the value in a hidden field for later use
      document.getElementById("HiddenField1").value = res;
//if i try to see the vaue of the hidden fiedl in here it is there but not ouside this fucntion
}

function onFormatNameFail (exception, ctx, methodName) 
{ 
       alert("Method:"+ methodName +"\n"+ 
            exception.get_exceptionType() +"\n"+
            exception._message); 
}
function onFormatNameTimeout () 
{ 
      alert("Timeout"); 
}








///////////////////////////////////////////////

   <form id="form1" runat="server">
        <asp:HiddenField ID="hdnReturnValue" runat="server" Value="xx" />
        <asp:HiddenField ID="HiddenField1" runat="server" />
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <input type="hidden" id="hiddnvalue" runat="server" value="" />
        <asp:ScriptManager ID="yourScriptManager" runat="server" EnablePageMethods="true">
        </asp:ScriptManager>
    </form>


the web method is the folloiwng
///////////////////////////////////////

 [WebMethod, ScriptMethod]
        static public List<String> FormatName(string featureIds)
        {
           

            string[] rawdata = featureIds.Split(new char[] { ',' });

            List<String> strings = new List<String>();
            for (int i = 0; i < rawdata.Length; i++)
            {
                strings.Add(rawdata[i]);
            }
            // strings.Add(FirstName);
            // strings.Add(LastName);*/

            //Session["result"] = strings;
            //   hdnReturnValue.value = strings;
          //  HiddenField1.Value = featureIds;
           // hiddnvalue.Value = featureIds;
            return strings;
            // LastName + ", " + FirstName;
        }

Open in new window

Avatar of Luis Pérez
Luis Pérez
Flag of Spain image

That's very easy using Ajax.

For example, jQuery Ajax:
http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/

Hope that helps.
You can also take a look at ClientCallBack
@AbebeDemeke,

type PageMethods in Google and confirm you generaly don't see anything after PageMethods call.

PageMethods do an asynchrone ajax call mean :
1- do the call an continue the execution of the code

and not :
2- do the call, wait for result and execution and continue.

if the first case you can't use result of the pagemethod call immediately because the call just start in parallel
in the second case you are able to use the result because you wait for the end of the call.

@RolandDeschain give you an other link to do a SYNCHRONE ajax call.

Avatar of AbebeDemeke
AbebeDemeke

ASKER

leakim971: thanks

and it seems that the problem is as you pointed out but do u know how can i do a synchronized ajax call. a simple example would help me a lot
leakim971:one question for you can i pass a parameter to the on success call back function so that I can finish everything there?
>a simple example would help me a lot
@RolandDeschain give you an other link to do a SYNCHRONE ajax call.
You just need to add :

$.ajax({
  async: false,
  type: "POST",

else again : http://kpumuk.info/asp-net/synchronous-page-method-call-in-asp-net-ajax-library/

A fast example
Where PageName.aspx is your page having the webmethod
if(window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("POST","PageName.aspx/FormatName",false);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("parameter1=Value1&parameter2=Value2");
xmlhttp.send();
document.getElementById("<%= HiddenField1.ClientID %>").innerHTML = xmlhttp.responseText;

Open in new window

i am not sure where do i put those fragment of codes?

function webMethodCaller( ids){
     if(window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
     xmlhttp.open("POST","PageName.aspx/FormatName",false);
     xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
     xmlhttp.send("parameter1=Value1&parameter2=Value2");
     xmlhttp.send();

// i want to do something else based on result after this
//if I try to get the value in a hidden filed in here it is empty
document.getElementById("<%= HiddenField1.ClientID %>").innerHTML = xmlhttp.responseText;
}

Open in new window

thaks but then do I need to change my web method and if then how?
have a look to the good article propose by @RolandDeschain
leakim971: please would you mind to make your answer complete? I appriciate your help so much

I have
function webMethodCaller( ids){
     if(window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
     xmlhttp.open("POST","PageName.aspx/FormatName",false);
     xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
     xmlhttp.send("parameter1=Value1&parameter2=Value2");
     xmlhttp.send();

// i want to do something else based on result after this
//if I try to get the value in a hidden filed in here it is empty
document.getElementById("<%= HiddenField1.ClientID %>").innerHTML = xmlhttp.responseText;
}

which means I dont have to call the page method like?

PageMethods.FormatName(ids,onFormatNameSuccess,onFormatNameFail,onFormatNameTimeout);

Moreover where do i put the code fragment

$.ajax({
  async: false,
  type: "POST",




>which means I dont have to call the page method like?
>PageMethods.FormatName(ids,onFormatNameSuccess,onFormatNameFail,onFormatNameTimeout);
Yes

>Moreover where do i put the code fragment
>$.ajax({
> async: false,
> type: "POST"
no need too, it's a jquery version

PageMethods : .net Ajax call
$.ajax : jQuery

pure javascript :
function webMethodCaller( ids){
     if(window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
     xmlhttp.open("POST","PageName.aspx/FormatName",false);
     xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
     xmlhttp.send("parameter1=Value1&parameter2=Value2");
     xmlhttp.send();
     document.getElementById("<%= HiddenField1.ClientID %>").innerHTML = xmlhttp.responseText;
}

Open in new window

correction you must remove line 6 : xmlhttp.send();

(only one send of course)

and its safe to use encodeURI
function webMethodCaller( ids){
     if(window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
     xmlhttp.open("POST","PageName.aspx/FormatName",false);
     xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
     xmlhttp.send(encodeURI("featureIds=" + ids));
     document.getElementById("<%= HiddenField1.ClientID %>").innerHTML = xmlhttp.responseText;
}

Open in new window

OK how do i pass my parmeters in this case ids?

is it like  xmlhttp.send("parameter1=ids");

morover since the page method is in the code behind of the page containing the java script will the folloiwng work

xmlhttp.open("POST","FormatName",false); ?

finally do i need to keep my previous web method as it is like :


 [WebMethod, ScriptMethod]
        static public List<String> FormatName(string featureIds)
        {
           
            string[] rawdata = featureIds.Split(new char[] { ',' });

            List<String> strings = new List<String>();
            for (int i = 0; i < rawdata.Length; i++)
            {
                strings.Add(rawdata[i]);
            }
   

       
            return strings;
         
           

        }
>OK how do i pass my parmeters in this case ids?
check line 5 : xmlhttp.send(encodeURI("featureIds=" + ids));

>finally do i need to keep my previous web method as it is like :
create a webservice with :


[WebMethod]
public List<String> FormatName(string featureIds)
{
            string[] rawdata = featureIds.Split(new char[] { ',' });

            List<String> strings = new List<String>();
            for (int i = 0; i < rawdata.Length; i++)
            {
                strings.Add(rawdata[i]);
            }
            return strings;
}

Open in new window

the xmlhttp.responseText is a long html code.

how can I extract the string list returned by the web method?

if at  all possible?
>xmlhttp.responseText is a long html code

do you see you data inside ? Perhaps is a error page.
If you saw your data, yes we can!

just post it here, in code snipet, to let we see it
and say witch part/string you want to get
well what i need is the string returned by the webmethod. I dont need the other and I dont really know where it is located in the code. However after taking out the part of the html that contains my conde follwoing is the rest returned as xmlhttp.responoseText

<input type=\"hidden\" name=\"__EVENTTARGET\" id=\"__EVENTTARGET\" value=\"\" />
<input type=\"hidden\" name=\"__EVENTARGUMENT\" id=\"__EVENTARGUMENT\" value=\"\" />
<input type=\"hidden\" name=\"__VIEWSTATE\" id=\"__VIEWSTATE\" value=\"/wEPDwUKLTI0NDQ5NDAwOWRk+xP7p8daFyNLYiR19DwIZihK0J0=\" />
</div>

<script type=\"text/javascript\">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
    theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}
//]]>
</script>


<script src=\"/WebResource.axd?d=W8uJCuYzqaZgFZVW92HeEg2&amp;t=633697903278952835\" type=\"text/javascript\"></script>


<script src=\"/ScriptResource.axd?d=CexzdgQeXWxJFoiTDPLHRhHW8BopNhuJXu1PpwHKi4GD0aZYyIkqVAh5sir4Lut4YGcJ2FX1KmHJPLgL5u5YbgAXJy901ffWht5-gi5fFDk1&amp;t=ffffffffdb87df90\" type=\"text/javascript\"></script>
<script src=\"/ScriptResource.axd?d=CexzdgQeXWxJFoiTDPLHRhHW8BopNhuJXu1PpwHKi4GD0aZYyIkqVAh5sir4Lut4AKg24qXhrbuX8JaVACwgKD7J27LMh309rZT-49R29zQ1&amp;t=ffffffffdb87df90\" type=\"text/javascript\"></script>
<script type=\"text/javascript\">
//<![CDATA[
var PageMethods = function() {
PageMethods.initializeBase(this);
this._timeout = 0;
this._userContext = null;
this._succeeded = null;
this._failed = null;
}
PageMethods.prototype = {
_get_path:function() {
 var p = this.get_path();
 if (p) return p;
 else return PageMethods._staticInstance.get_path();},
FormatName:function(featureIds,succeededCallback, failedCallback, userContext) {
return this._invoke(this._get_path(), 'FormatName',false,{featureIds:featureIds},succeededCallback,failedCallback,userContext); }}
PageMethods.registerClass('PageMethods',Sys.Net.WebServiceProxy);
PageMethods._staticInstance = new PageMethods();
PageMethods.set_path = function(value) { PageMethods._staticInstance.set_path(value); }
PageMethods.get_path = function() { return PageMethods._staticInstance.get_path(); }
PageMethods.set_timeout = function(value) { PageMethods._staticInstance.set_timeout(value); }
PageMethods.get_timeout = function() { return PageMethods._staticInstance.get_timeout(); }
PageMethods.set_defaultUserContext = function(value) { PageMethods._staticInstance.set_defaultUserContext(value); }
PageMethods.get_defaultUserContext = function() { return PageMethods._staticInstance.get_defaultUserContext(); }
PageMethods.set_defaultSucceededCallback = function(value) { PageMethods._staticInstance.set_defaultSucceededCallback(value); }
PageMethods.get_defaultSucceededCallback = function() { return PageMethods._staticInstance.get_defaultSucceededCallback(); }
PageMethods.set_defaultFailedCallback = function(value) { PageMethods._staticInstance.set_defaultFailedCallback(value); }
PageMethods.get_defaultFailedCallback = function() { return PageMethods._staticInstance.get_defaultFailedCallback(); }
PageMethods.set_path(\"/signal_demo.aspx\");
PageMethods.FormatName= function(featureIds,onSuccess,onFailed,userContext) {PageMethods._staticInstance.FormatName(featureIds,onSuccess,onFailed,userContext); }
//]]>
</script>

<div>

      <input type=\"hidden\" name=\"__EVENTVALIDATION\" id=\"__EVENTVALIDATION\" value=\"/wEWBQK6lI3zAQLcteSgAQKQo8KrDQLs0bLrBgKlzeSLB5WD/E4S3+cgUPrYOjiWJ0/INDlN\" />
</div>
        <input type=\"hidden\" name=\"hdnReturnValue\" id=\"hdnReturnValue\" value=\"xx\" />
        <input type=\"hidden\" name=\"HiddenField1\" id=\"HiddenField1\" />
        <input name=\"TextBox1\" type=\"text\" id=\"TextBox1\" />
        <input name=\"hiddnvalue\" type=\"hidden\" id=\"hiddnvalue\" />
        <script type=\"text/javascript\">
//<![CDATA[
Sys.WebForms.PageRequestManager._initialize('yourScriptManager', document.getElementById('form1'));
Sys.WebForms.PageRequestManager.getInstance()._updateControls([], [], [], 90);
//]]>
</script>

   

<script type=\"text/javascript\">
//<![CDATA[
Sys.Application.initialize();
//]]>
</script>
</form>
</body>
</html>
lol you don't post it in code snipet...

could you post the webservice you're using ?
and the main page.

it's not a correct inetegration of the code, you should get back a light XML with the result
the web service is the web method . isn't it ? if so it is the following

[WebMethod]
public List<String> FormatName(string featureIds)
{
            string[] rawdata = featureIds.Split(new char[] { ',' });

            List<String> strings = new List<String>();
            for (int i = 0; i < rawdata.Length; i++)
            {
                strings.Add(rawdata[i]);
            }
            return strings;
}

now when u say the main page if u mean the code where i called the web service it is like


    if(window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
       
      xmlhttp.open("POST","signal_demo.aspx/FormatName",false);
     
      xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
      xmlhttp.send(encodeURI("featureIds=" + ids));
     
      document.getElementById("<%= HiddenField1.ClientID %>").innerHTML = xmlhttp.responseText;


or does it look like back to square one
? lol

please help me
Did you really create a webservice page named : signal_demo.aspx

Or you're using the same previous page doing the call ?
that is a good question. the signal_demo is the name of the page that contains the webmethod in its code behind
create a dedicated webservice
man I think you are taking me towards the solution after creating the dedicated webservice and doing

 if(window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
       
      xmlhttp.open("POST","Dedicated.asmx/FormatName",false);
     
      xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
      xmlhttp.send(encodeURI("featureIds=" + ids));
     
      document.getElementById("<%= HiddenField1.ClientID %>").innerHTML = xmlhttp.responseText;



However the last line is returning an error message and I saw the xmlhttp.responseText and I found a much shorter xml document than the one above. lol

            xmlhttp.responseText      "<?xml version=\"1.0\" encoding=\"utf-8\"?>
<string xmlns=\"http://tempuri.org/\">104,103,98,26,105</string>"      String

how can i extract the string containing the numbers  from the xml document?
yes you got a valid answer !

Please post it in code snipet, as you can see its not well formated in comment

to insert in code snipet, click on the Code link

___below me_____
xmlhttp.responseText      "<?xml version=\"1.0\" encoding=\"utf-8\"?>
<string xmlns=\"http://tempuri.org/\">104,103,98,26,105</string>"      String
how can i extract the string value then?
xmlhttp.responseText      "<?xml version=\"1.0\" encoding=\"utf-8\"?>
<string xmlns=\"http://tempuri.org/\">104,103,98,26,105</string>"      String

Open in new window

:o(

try again, you post it again in comment
check bhind comment textarea, on the bottom left, you have links : File, Code, Image
Click on Code, paste you xml in the new textarea and click on the attach button

or confirm this is all you have :


<?xml version=\"1.0\" encoding=\"utf-8\"?>
<string xmlns=\"http://tempuri.org/\">104,103,98,26,105</string>

Open in new window

that is all i have as an xmlhttp.responseText and I know that the value returned is a string containgin 104,103,98,26,105. but how can i extract it from the xml ?
ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
leakim971:

I think with your great help two days of hell is comming to a conclusion . I really apreciate your help . I really do. I hope we will meet in the future and I like to learn more from you. Thank you
You're very welcome! Thanks for the points!

Hey! Look what you did lol :
tshirt.jpg
leakim971:Everything is working fine except that when i try to pass multiple parametrs to the webmethod an error will be gnerated. I used the following approach to send multiple params.

 xmlhttp.send(encodeURI("featureIds="+ids&"sender="+senders));

senders is a simple string and I have also modified the web method to accept two string parms.

not : xmlhttp.send(encodeURI("featureIds="+ids&"sender="+senders));
but : xmlhttp.send(encodeURI("featureIds="+ids+"&sender="+senders));
perfect. it works. thankyou