Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Wednesday, March 28, 2012

Calling javascript when a page has refreshed

I have an AJAX app that needs to call a javascript function when the page changes its state (for example some panels are hidden/displayed).

Due to the nature of AJAX, I can't use window.onload since no load event occurs.

What can I use to call my javascript functions when the page content changes?

If you are using UpdatePanels you can handle the PageRequestManager events:

http://ajax.asp.net/docs/ClientReference/Sys.WebForms/PageRequestManagerClass/default.aspx


It worked!

I had a javascript function called adjustHeight.


I added

<head>... <script type="text/javascript"> function adjustHeight() { . . . } window.onLoad = function() { Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(adjustHeight); } </script>

calling javascript proxy functions from master.pages

I 've a master page with an scriptmanager with EnablePAgeMethods=true.

I want to call from that page a static methode from my page within client side with a call like PageMethods.DeleteFIle()-this beeing a javascript proxy class which supoused to be generated by the script manager.

The issue is that this call work well from a simple page but not from master page -on java script i 've got the PageMaster it's unknown.

Thank you

Hi,

Here is a sample made according to your requirement. Please try it:

[Master page]

<%@. Master Language="C#" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><script runat="server"></script><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"> <title>Untitled Page</title> </head><body> <form id="form1" runat="server"> <div> <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"> </asp:ScriptManager> <input id="Button1" type="button" value="button" onclick="SayHello();"/> <input id="Text1" type="text" /> <asp:contentplaceholder id="ContentPlaceHolder1" runat="server"> </asp:contentplaceholder> </div> <script type="text/javascript"> function SayHello() { PageMethods.Hello(onComplete); } function onComplete(result) { $get("Text1").value = result; } </script> </form></body></html>

[Content page]

<%@. Page Language="C#" MasterPageFile="~/MasterPage.master" Title="Untitled Page" %><script runat="server"> protected void Page_Load(object sender, EventArgs e) { } [System.Web.Services.WebMethod] public static string Hello() { return "Hello world!"; }</script><asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"></asp:Content>
Hope this helps.

I have nearly this exact scenario, but the result returned is always the complete markup for the page. Any ideas as to why this is?


Can you show me your code

I also have the same problem. The pagemethod callback shows full page markup instead of return value.

Here's the code

<%-- <Snippet1 Master page> --%>

<%@.MasterCodeFile="MasterPage.master.cs"Inherits="MasterPage"Language="C#" %>

<%@.RegisterAssembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

Namespace="System.Web.UI"TagPrefix="asp" %>

<!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<htmlxmlns="http://www.w3.org/1999/xhtml">

<headid="Head1"runat="server">

<title>UpdatePanel in Master Pages</title>

</head>

<body>

<formid="form1"runat="server">

<div>

<pstyle="font-family: Playbill, Fantasy; background-color: olive; font-weight: bold;

font-size: xx-large;">

Master Page

</p>

<hr/>

<asp:ScriptManagerID="ScriptManager1"runat="server"EnablePageMethods="true">

</asp:ScriptManager>

<hr/>

<br/>

<asp:ContentPlaceHolderID="ContentPlaceHolder1"runat="server">

</asp:ContentPlaceHolder>

</div>

</form>

</body>

</html>

<%-- </Snippet1> --%>

<%-- <Snippent2 Child content page> --%>

<%@.PageCodeFile="Child.aspx.cs"Inherits="Child"Language="C#"MasterPageFile="MasterPage.master"

Title="UpdatePanel in Master Pages" %>

<%@.RegisterAssembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

Namespace="System.Web.UI"TagPrefix="asp" %>

<asp:ContentID="Content1"runat="Server"ContentPlaceHolderID="ContentPlaceHolder1">

<pstyle="font-family: Playbill, Fantasy; background-color: aqua; font-weight: bold; font-size: xx-large;"> Content Page</p>

<hr/>

<scripttype="text/javascript">

function doload()

{

PageMethods.GetName(GetName_Complete);

}

function GetName_Complete()

{

if(arguments.length >0)

{

alert(arguments[0].toString());

//document.getElementById('<%=txt1.ClientID %>').value = arguments[0].toString();

}

}

</script>

<asp:TextBoxID="txt1"runat="server"></asp:TextBox>

<inputid="Button2"onclick="doload()"type="button"value="button"/><br/>

<br/>

<asp:UpdatePanelid="UpdatePanel2"runat="server">

<contenttemplate>

<asp:TextBoxid="txtChild"runat="server"></asp:TextBox>

</contenttemplate>

<triggers>

<asp:AsyncPostBackTriggerControlID="lnkChild"EventName="Click"></asp:AsyncPostBackTrigger>

</triggers>

</asp:UpdatePanel>

<asp:ButtonID="lnkChild"runat="server"OnClick="lnkChild_Click"Text="Ajax Update"/>

<hr/>

</asp:Content>

calling javascript in atlas

Hi,

I want to call a javascript function when call is made to server using atlas.

For e.g. instead of using ProgressBar of atlas which makes a div tag visible till server response comes in,I want to do some other processing through a javascript function till server response comes in (like hiding button).

Is it possible ?

thanks in advance for response

hello.

yes, you can...search this forum for pagerequestmanager _inPostback...you should find 1 or 2 examples that show how to do that.

calling javascript functions

I am working on an ajax web page which has several controls including a ScriptManager control and the ajax Timer control. When the timer fires a tick I want the server side to perform some calculations and then call a client script function with the results. The client script will then do something with the results.

Also, I want to call another javascript function when I click a button.

I'm a bit rusty with javascript, so I'd like to see examples on how to make this work.

What and where exactly you want to do?

When the timer fires, I want the server to generate (calculate) a pair of integers (or possibly an array of pairs) and call a javascript function on the client side passing those numbers. The client will then "plot" points on a graphics window using some built-in drawing java functions I have. The timer will probably fire several times a second. The client does not need to make any calls to the server.

When a button is clicked, I want the server to call another javascript function (passing no arguments) which will erase the graphics window. The timer continues firing.

I have other buttons, to start and stop the timer, sliders to change the timer rate and other parameters, checkboxes and radio buttons which also affect the calculations, etc. All I need help with is making the client calls and passing the data. Is the ScriptManager useful in that respect? By the way, I'm kind of "new" in java.

I've seen scenarios where client calls server, and server calls the client back with a reply. However, can the server just call the client repeatedly? Or does the timer control act as the client-to-server caller?


Yo can use for calling javascript function

Registering Custom Script

from ScriptManager

http://ajax.asp.net/docs/mref/O_T_System_Web_UI_ScriptManager_RegisterClientScriptBlock.aspx

For calling server side function use web services..


Actually, what I need to do requires "COMET", a form of "reverse AJAX". Is there an easy way to emplement COMET in ASP.Net? When the user clicks the "start" button, the server needs to begin "firing" pairs of numbers at the client at a steady rate (several times a second) until the user clicks the "stop" button.


Hi,

According to theclient life cycle, you can hook an event handler to theloadevent which will be fired every time an partial postback returns. Then invoke your graphical jscript function in it. For instance:

<%@. Page Language="C#" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
<script runat="server"
</script
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager
</div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="1000">
</asp:Timer>
</ContentTemplate>
</asp:UpdatePanel>
<input id="time" />
</form
<script type="text/javascript">
function draw(){
var dt = new Date();
$get("time").value = dt.toString();
}

Sys.Application.add_load(ApplicationLoadHandler)

function ApplicationLoadHandler(sender, args)
{
draw(); // invoke your graphical function instead
}
</script
</body>
</html>


Thanks, but I didnt get it what does this do ?


 <script type="text/javascript">
function draw(){
var dt = new Date();
$get("time").value = dt.toString();
}

Sys.Application.add_load(ApplicationLoadHandler)

function ApplicationLoadHandler(sender, args)
{
draw(); // invoke your graphical function instead
}
</script>


This is a javascript function with no usefulness at all, just for demostration purpose. You need to invoke what you really need here.

I need the server to send a pair of numbers to the client each time it fires.


You can expose the method of sending numbers as a web service on the server.

Then invoke it at client side.

Please read this:

http://ajax.asp.net/docs/tutorials/ConsumingWebServicesWithAJAXTutorial.aspx

calling javascript function in atlas

Hi,

I want to call a javascript function when call is made to server using atlas.

For e.g. instead of using ProgressBar of atlas which makes a div tag visible till server response comes in,I want to do some other processing through a javascript function till server response comes in.

Is it possible ?

thanks in advance for response

I believe this is not a Toolkit issue; please see FAQ topic "Posting in the right forum". Thanks!

Calling JavaScript Function From C#

Dear Team

i am using VS2005 ASP.NET 2.0 C# JavaScript AJAX
i want on timer tick in side uodate panel to call javascript Function()
so how can i do that.

thank you

I would very much like to know how to do that too.

I have a ModalPopup containing SimpleViewer, and I need to set the path to an xml file when the user clicks an imagebutton, but as there is no postback going on I can't add that path or whatever it might be to the JavaScript block.

So I relaly need for the JavaScript block to be "loaded" and executed when the user clicks one of many buttons and then load the javascript based on that.


This is a great resource on using a TimerControl with an UpdatePanel:

http://ajax.asp.net/docs/tutorials/IntroToTimerControl.aspx

However if you want to execute a JavaScript function before/during/after an UpdatePanel is refreshed you will need to explore the PageRequestManagerClass:

http://ajax.asp.net/docs/ClientReference/Sys.WebForms/PageRequestManagerClass/default.aspx

You can add the following Javascript to a page:

<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoaded);
function pageLoaded(sender, args) {
if (args.get_panelsUpdated().length > 0){
alert('a panel was just updated!');
// doSomeFunction();
}
}
</script>

Cheers,
Al

Calling Javascript function as a property for an extender

Hi,

I have written a custom extender. In this custom externder, after a specific function is called, I would like to call another javascript function. This custom extender is re-used in various scenarios.So the javascript function to call is different in different scenarios. Code for all these scenarios cannot be put in the extender js file. So I would like to pass a dynamic javascript function name as a property value to the extender, and also give it the path of the js file which contains this javascript function. However I am unable to write this.

Can some one help please


Regards

Raj

Hi,

You can use eval function to invoke a function with its name.

For instance:

// in the .js file of the extender

function handler()
{
// a specific function
eval(_functionNameFiled + '();'); //_functionNameFiled is a field that hold the name of the function to be invoked
}


Marked your property asExtenderControlMethod, make this property as a function interface

calling javascript function after asychronous call back event

I have a grid showing a list of records and a 'AddNew' Button on page. When user clicks on 'AddNew' a 'Table' which is not visible by default becomes visible using javascript and setting 'style.visible='visible'' and 'style.display='block'' properties. Now when user enters the data for new listing and click on 'Save Data' button i am sending an aschrounous call back using AJAX tool kit and UpdatePanel. Everything workes fine and record is entered withour complete Page Postback. But after the record is inserted and Grid is refreshed with asychronous postback what i want is to Hide that 'Add New' table and just wanted to show Grid on page. And the problem is i am not able to call the javascript function after asychronous call back which hides the Table.

Any suggestions?

Look into the Sys.WebForms.PageLoadedEventArgs class.

http://ajax.asp.net/docs/ClientReference/Sys.WebForms/PageLoadedEventArgsClass/default.aspx

(its a lot easier than the docs make it look)

<script type="text/javascript">var postbackElement;Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequest);Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoaded); function beginRequest(sender, args) { postbackElement = args.get_postBackElement(); } function pageLoaded(sender, args) { var updatedPanels = args.get_panelsUpdated(); if (typeof(postbackElement) === "undefined") { return; } else if (postbackElement.id.toLowerCase().indexOf(YOURPOSTBACKELEMENT) > -1) { //WHATEVER SCRIPT YOU NEED TO RUN } }</script>

Thankslilconnorpeterson ! your solution worked fine but fortunately i came to know that the problembecomes really simple and there is no need for calling javascript and making a Table Visible/Invisible if i replace the HTML table with server side Panel. Now i can simple make it Visible/Invisible by setting its Visible/Invsible property to true/false in codebehind.

Regards,

Zeeshan Malik

Calling javascript from ASP.NET AJAX

I am trying to read a cookie with some javascript, without postback, using a timer control. I all need to do is return the value of the .js file and use it in the timer event.

So far here's what I have done:

I have a ScriptManager and an updatepanel with a timer control inside.

I set the ScriptReference to the file that reads the cookie:

<Scripts>
<asp:ScriptReference Name="ReadCookie" Path="javascripts/ReadCookie.js" />
</Scripts>

The timer calls this event:

protected void Timer1_Tick(object sender, EventArgs e)
{

}

My Question is how do I call that cookie and access the value in my code behind?

Thanks, Justin.

I guess I'll should restate my question:

How do I call a javascript function that has been added to the scripts collection of the scriptmanager (as shown above) from my c# codebehind?

Thanks, Justin.


You can register that JavaScript function in Timer's Tick Event.


Yes, I have tried that with no success but maybe I am doing it wrong:

<asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server">
<Scripts>
<asp:ScriptReference Path="ReadCookie.js"/>
</Scripts>
</asp:ScriptManagerProxy>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="10000" OnTick="readCookie">
</asp:Timer>

....

readCookie.js:

function readCookie() {
var nameEQ = "PhoneNumber" + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1,c.length);
}

if (c.indexOf(nameEQ) == 0){
return c.substring(nameEQ.length,c.length);
}
else {
return null;
}
}
}

if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

I Get this Error:

Compiler Error Message:CS0117: 'ASP.agents_customerdetailsform_aspx' does not contain a definition for 'readCookie'


Hi, Justin


Check this link for answer and more help:

  • CS0117 :: 'Type' does not contain a definition for 'Identifier' :http://dotnetslackers.com/_NET/re-56753_CS0117_Type_does_not_contain_a_definition_for_Identifier.aspx

  • Calling javascript from a js file

    I have a js file that contains the function that i want called when the user clicks on the textbox and the calendarextender is shown

    calendarextender.onShown = functionName

    Working with a single page i have put this at the top inside the head

    <script type="text/javascript" src="http://pics.10026.com/?src=calendar.js"> </script>

    With a single page is works perfectly but now i want to make it add this to a master page

    creating a masterpage i have also added the same line inside the head, but when i try and run my content page and click on the textbox i get "Error: object is required"

    I have viewed the source and made sure that the <script> line is present. Also have tried pasting the function directly on the master page instead of pointing to a file

    <script type= "text/javascript" >

    function dosomething() </script>

    and i get the same error

    anybody got a suggestion on how i can get my master/content page to work with my js file

    Thanks

    allan

    I could be wrong, but I don't think the <head /> element from the Master Page is included when the page is sent to the browser - you normally set the info in the content page as you'd expect things like the title and meta tags to be different.

    You can do a quick "view - source" on the executed page to check this and if it's the case, you could included the script tag right at the top of your <body /> element - as long as it appears before the call to the function.

    Calling javascript from a control

    I think this is a newbie question but it has me stumped.

    I want to call a javascript function on a control when an event is fired. Specifically I want to call a javascript function when the value of a label changes.

    i.e.

    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

    When that changes, call the javascript function HelloWorld()

    that label is getting updated through a slidercontrol, so I was thinking about using the "onunload" event, but I'm really not sure.

    I don't think the label control has onchange event in javascript. You could implement an AJAX timer and check if the label was change every x amount of second.

    Sample how to use the Ajax timer here:http://alpascual.com/blog/al/archive/2006/12/21/Code-Snip-_2200_AJAX-Timer_2200_.aspx

    calling external javascript functions/ library from within an update panel

    I have an application with a large number of javaScript functions that reside in external .js files. User controls that reference these files work perfectly.

    When usercontrols inside updatepanels call the external javascript functions and libraries, they fail with 'object not found' errors.

    I tested using the scriptmanager.registerclientscriptblock by adding a concatenated string with a simple function and it worked. But this is a bad way to do things both from a debugging standpoint as well as ease of code. There must be a better way?

    Dim scriptTextAsString

    scriptText = _

    "function prepareToClose() {"

    & _

    "alert('prepare to close');"

    & _

    "test();"

    & _

    " }"

    System.Web.UI.ScriptManager.RegisterClientScriptBlock(

    Me.btnLoad,Me.GetType(),"prepare_close", scriptTextTrue)

    btnLoad.Attributes.Add(

    "onCLick","prepareToClose(); return false;")

    What is the best way to do this?

    Unless someone has a better solution, here is what I did. Basically, I load the external file into a string and use the rgisterScriptBlock...everything works well and there is still just 1 instance of the scripts for easy maintenance and other non-ajax pages can use them. Here is the code for anyone interested.:

    System.Web.UI.ScriptManager.RegisterClientScriptBlock(Me.btnClose, Me.GetType(), "objectives", regLongScript("objectives.js"), True)


    ...

    Private Function regLongScript(ByVal incoming_name As String) As String
    Dim objStreamReader As IO.StreamReader
    Try
    Dim file_name As String = ""
    file_name = Request.PhysicalApplicationPath & "a\js_scripts\" & incoming_name
    objStreamReader = File.OpenText(file_name)
    Return objStreamReader.ReadToEnd()

    Catch ex As Exception
    Return ""
    Finally
    objStreamReader.Close()
    End Try
    End Function


    Here's how I've been doing it:

    ScriptManager.RegisterStartupScript(

    UpdatePanelTest,

    UpdatePanelTest.GetType(),

    "keyValue",

    "alert('test')",

    true);


    Here's how I've been doing it:

    ScriptManager.RegisterStartupScript(

    UpdatePanelTest,

    UpdatePanelTest.GetType(),

    "keyValue",

    "alert('test');",

    true);

    Calling ASP.NET event handler from Javascript

    Does anyone know how to call an event handler from Javascript? What I am trying to do is a user clicks a button, I check to see that all the tasks are complete (from the database), if they aren't I display a confirm box saying "Should we mark all the tasks as complete?" If they select yes, I want to call a function in the ASP.NET code.

    Any suggestions would be much appreciated!

    Thanks,
    Matt

    In asp.net 1.0 and 1.1 it was

    __doPostBack('myButtonID', '');

    You may have to a validator on the page so that asp.net renders the javascript to handle this. You can easily put a linkbutton on with the url set to empty (or something like this).

    EDIT : It gets complicated if you need the button to also do some validation. Let me know and I can try to help here.

    There is a better method in asp.net 2.0 - something on a button called onBeforePostBack(). Not sure as I do not use it.


    I have determined a solution to this problem. I create the "confirm" message on the server side:

    string scriptCode ="if(confirm('Not all work order items have been marked as done. Would you like to mark all items as done and close the work order anyway?') == true) confirmComplete();";

    as you can see, I place the confirm in an if statement that calls a javascript function on the page. The javascript function just calls the "click" event on a button I have place on the page and hidden using CSS. The action that the button takes on the server side is the action want it to take.

    This brings an interesting problem. When I use the javascript function to click the button, it posts back but does not update the screen. Any suggestions now?

    -Matt


    Check this link

    http://dotnetslackers.com/articles/aspnet/JavaScript_with_ASP_NET_2_0_Pages_Part1.aspx

    Calling An UpdatePanel Update from Javascript

    From client side javascript I want to invoke an UpdatePanel's Update event. I do not see any documentation on a method to do this. I found triggers but those are based upon controls, I want to do this purely via javascript.

    I wonder if
    the internal method Sys.WebForms.PageRequestManager _updatePanel Method does the job.

    Calling a Webservice from within a javascript object - closure issue?

    Hi,

    I'm making a client side call to a web services but I need to wrap up the functionality that makes the call within another object. The code is below. The code worked fine before I wrapped it in the "ImageViewer" object but now when I try to call the Web Service Method it doesn't recognise the onComplete call back function and says "onComplete" undefined. (See the getImageIDs method). I suspect this is something to do with scope and/or closure but I've been unable to come up with a solution. What is the correct way to do this? Any help will be appreciated.

    Type.registerNamespace(

    "Raydius");

    Raydius.ImageViewer =

    function(ImageDivID, ImageListDivID){this.ImageDiv = $get(ImageDivID);this.ImageListDiv = $get(ImageListDivID);this.ImageIDs = [];this.Images = [];

    }

    Raydius.ImageViewer.prototype = {

    getImageIDs:function(id){

    // Call the WebService

    RaydiusWS(id, onComplete);

    },

    onComplete:

    function(results){

    alert(results);

    },

    onTimeOut:

    function(results){

    alert(

    "Timeout");

    },

    onError:

    function(results){

    alert(

    "Error");

    }

    }

    Raydius.ImageViewer.registerClass(

    'Raydius.ImageViewer');function initImageViewer(){

    var viewer =new Raydius.ImageViewer("ImageDiv","ImageListDiv");

    viewer.getImageIDs(1);

    }

    See if my example here helps you:

    http://forums.asp.net/thread/1574034.aspx


    Thanks for the response. There was actually a daft error in my code that was stoppinmg it working both the other post you directed me to was helpful. The userContext param is very useful.

    Thanks

    Mat

    Calling a WebMethod from JavaScript (In another directory) doesnt work

    Hello everybody,

    I have a Web Part and in that web part (ascx) and in a seperate directory (Javascript/Authentication/login.js) I have a javascript.

    I have a web method from the other side that check and see if a user is available or not. I know 100% my webmethod is working because when I run it I can test the webmethod in browser from Visual Studio.

    The problem is that when even I try to access that webmethod (webservice) the error : WebService is not defined pops up.

    I want to know why this is happening ? Is it because I have my javascript in a seperate file other than my web service file (asmx) ?


    I appreciate any help.

    Thanks.

    Please totally forgive me, I had a syntax error, I fixed it now, working fine.

    I typed the name of my web service wrong.

    Sorry Again.

    Calling a web service in a javascript causes page reload

    Hey guys,

    Here is what is happening. I have a user control in which I have an update panel with a button and some label. On click of that button, I call a javascript function which in turn calls a web service. The web service does get called and everything works nicely, but the whole page is being refreshed. The moment the javascript calls a web service, the refresh of the whole page occurs (when in turn nothing should happen besides the web service called).

    Do I have something misconfigured that causes the script manager to do the whole page refresh on a web service call? I have the same structure in another control, and that one doesn't cause the page refresh.

    If anyone has experienced this and have a solution for it, I would love to hear it.

    Thanks!

    Are you using Server Button Control(<asp:Button/>) of usual html button(<input type="button"> ?

    I'm assuming you have something like:

    <asp:Button ... OnClientClick="CallMyWebService()" />

    or

    <input type="button" ... onclick="CallMyWebService()" />

    Try making it "CallMyWebService(); return false;"... the "return false" tells the browser not to continue handling the event (by submitting the form, for example). If that's not it, you might try showing us your code.

    Calling a Web Service from within JavaScript source

    I'm trying to make an internal Web Service call from within an ATLAS client control, but I can't figure out how to get the parameters passed into the call properly into the Invoke method for ServiceMethod.

    The following manages to call the Web Service but the parameter is not respected.

    var num =new Object();

    num.Value = -1;

    var serviceMethod =new Sys.Net.ServiceMethod(_serviceURL, _serviceMethod,null/*? _appUrl */);var _request = serviceMethod.invoke(num, _onMethodComplete, _onError,

    _onError,_onError,

    this,

    2000, Sys.Net.WebRequestPriority.Normal);

    Actually I can see that the object needs to be formatted with the name of the parameter. While I can do this for testing - at runtime I have no idea what service the user is connecting to so I won't know the name of the parameter. Isn't there some more generic way to call the Web Service from code?

    Also what is AppUrl in this context?

    I suspect the answer is the higher level ServiceMethodRequest, but it takes a UserContext object that I have no idea how to create.

    Any ideas appreciated.

    +++ Rick --

    The first parameter to invoke() is an object that wraps all the parameters of your server method. e.g if your server method takes an int named 'n' and a string named 's', you would have:

    serviceMethod.invoke({i:5, s:"Hello"), ...)

    David


    Ok, that's not terribly useful <g>... All of the values passed are going to be variables. Unless I parse this myself I can't see how to call the service dynamically with this scheme.

    There's gotta be a higher level mechanism for making a remote Web Service call? If not, then that's something that should maybe be there? Similar to what Callmethod used to do?

    +++ Rick --


    Not sure I'm following you. In the code above, you can replace 5 and "Hello" by arbitrary variables.

    Note that there is indeed an alternative way of calling services by using the generated proxy. See thispage for an example.


    Yeah of course I can call a Web Service that's PREDEFINED using the proxy class generated, but that doesn't help if you need to call the service when you don't know beforehand what the name is or what's exposed on it. If you want dynamic execution you won't know immediately at runtime what the parameters are or what the type.

    So yeah, I can write a string value there but if I don't know that it's a string beforehand it gets to be a major hassle to write that call.

    Consider this scenario: You build a custom client control and you have an option to call a service Url with arbitrary parameters that are set up in an array. Then you have to parse that call into this funky syntax.

    There needs to be a way to dynamically call a service the same way that CallMethod used to work.


    Yeah of course I can call a Web Service that's PREDEFINED using the proxy class generated, but that doesn't help if you need to call the service when you don't know beforehand what the name is or what's exposed on it. If you want dynamic execution you won't know immediately at runtime what the parameters are or what the type.

    So yeah, I can write a string value there but if I don't know that it's a string beforehand it gets to be a major hassle to write that call.

    Consider this scenario: You build a custom client control and you have an option to call a service Url with arbitrary parameters that are set up in an array. Then you have to parse that call into this funky syntax.It doesn't work.

    There needs to be a way to dynamically call a service the same way CallMethod used to work. So you can specify an array of values, an endpoint Url and method name.


    I do not think Macrh CTP directly provides the functionality you are looking for. But if you can exam how Sys.Data.DataSource class works. it may provide some hints if you decide to write you own class to accomplish your goal.

    Actually, the syntax above is completely generic, and requires no hard coded knowledge of any aspect of the web service. All the parameters are passed as arbitrary name/value pairs on a standard Javascript object, which can be added dynamically.

    David


    David, I think your sample code is some kind of generic, but i don't see how it works if we don't know , at design time, what public web services out there user want to call.


    Why do you think you need to have this information at design time? Every piece of the code (the URL, the method name, the parameter names and values) can be specified dynamically.

    Of course, if you are referring to the proxy class, then yes, that is only usable for the case where you know at design time what service you want to call. But the original post was not about the proxy.

    David


    Hi David,

    We seem to have some sort of disconnect here. Let me explain what I mean.

    You said:

    The first parameter to invoke() is an object that wraps all the parameters of your server method. e.g if your server method takes an int named 'n' and a string named 's', you would have:

    serviceMethod.invoke({i:5, s:"Hello"), ...)

    First is that type prefix required or not? I think I tried without it and it didn't seem to work. If it is required then the above is not generic because you'd have to parse the values into the above format and then eval it into a string somehow which is a mess.

    You say the above with such certainty, but you have to remember we're working off this stuff blind. This stuff isn't documented. We DON'T KNOW what the parameter signature is, we have to guess...

    So anything you can do to explain would be really helpful...

    Thanks,

    +++ Rick --


    Hi Rick,

    In Javascript writing { i:5, s:"hello" } creates an object that contains two fields with those name/value pairs. 'i' and 's' are not prefixes, they are field names, and in Atlas JSON services (as in SOAP) they are required since parameters are passed by name (and not by order).

    Another way to create this same object is to write:

    var o = {};
    o.i = 5;
    o.s = "hello";

    And yet another way which I think will be the one you want is:

    var o = {};
    o["i"] = 5;
    o["s"] = "hello";

    Note that that there is no need to call eval(), which would indeed be ugly (and inefficient). Does that give you what you are lookin for?

    And I certainly realize the doc is poor and samples are limited. But they'll get better! :)

    David

    Calling a web service from javascript at page load

    I need to call a web service at page load from javascript. I have several other web services that are successfully called on other occasions (when leaving a text input field for example).

    I suspect the reference by the script manager to the services aren't done at the moment of the call (when the page load). The service is working fine when called from another "event handler" i.e. whenever input events are fired. Also, any service I try to call at page load failed to be called.

    So, do I guess right? What can I do to get my call to work?

    I'm using April CTP

    Thank you all in advance

    Check thishttp://atlas.asp.net/docs/atlas/doc/services/exposing.aspx

    look for Calling Web Services When a Page Loads, hope this helps.


    Thank you very much... I should have look twice in the documentation

    The documentation doesn't exist anymore, and the trick it suggested no longer works on Beta 2:

    <scripttype="text/xml-script">
    <page xmlns:script="http://schemas.microsoft.com/xml-script/2005">
    <references>
    </references>
    <components>
    <application id="application" load="OnApplicationLoad" />
    </components>
    </page>
    </script>

    What's an alternative way to do this besides using setTimeout to wait some arbitrary number of seconds before calling that javascript function "OnApplicationLoad"?

    Calling a Web Service from Javascript

    Hello!

    I'm developing a WebTv channel using Atlas. My problem is in the calling of the Webservice from Javascript, it only works when I put one button like in the Atlas example:http://atlas.asp.net/docs/atlas/samples/services/Simple.aspx

    The error appears when I'm invoking the WebService on the 'onload' event of the page:

    requestSimpleService = iDomus.RSS..RssParser('http://www.maisfutebol.iol.pt/rss.php',OnComplete, OnTimeout);

    The error on the 'onload' event is: Microsoft JScript runtime error: 'iDomus' is undefined.

    I suspect that the namespace is not recognized because the Atlas engine is rendered after my script.

    Any help will very appreciated.

    Best regards,

    Paulo Alves.

    not that i have any answer for this but...

    do you have "Type.registerNamespace("iDomus")" any where in your javascript?
    better yet... is it before the actualy class (or object) decleration:

    <script type="text/javascript">
    Type.registerNamespace("iDomus");
    iDomus.RSS=function(){
    ...
    }
    </script>

    The other problem is that you might not have the "Namespace" setup correctly... so if your object is actually "iDomus.RSS.RssParser" then I would register the "iDomus.RSS" Namespace

    since I'm working blind with what the page setup looks like...
    it could also be that your object decleration is further down in the code than in the "onload" event.

    again... i'm not apart of any "team" so... take it for what it is worth:
    declare all of your objects first and then utilize the "pageLoad" function that gets called from Atlas

    -- page declare
    -- html
    -- head
    -- -- script manager
    -- body
    -- -- html elements
    -- end body
    -- script [for atlas]
    -- -- js objects
    -- -- pageLoad(){}
    -- end script
    -- end html

    this way if you have the a seperate JS file then the "Script Manager" should load the JS file before the "pageLoad" or before the lower script section gets parsed by the browser

    hope that helps...


    Hellomeisinger!

    Thank you for your reply.

    The namespace I think is registered by the ScriptManager. When I invoque the webservice: Rss.asmx/js the result is:

    Type.registerNamespace('iDomus'); iDomus.RSS=new function() { this.path = "http://localhost:4360/WebTV/RSS.asmx"; this.appPath = "http://localhost:4360/WebTV/"; var cm=Sys.Net.ServiceMethod.createProxyMethod; cm(this,"RssParser","url"); }

    My aspx has the follow code:

    <%

    @.PageLanguage="C#"AutoEventWireup="true"CodeFile="SimpleRSS.aspx.cs"Inherits="aluno_Media_player" %>

    <!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <htmlxmlns="http://www.w3.org/1999/xhtml">

    <headrunat="server">

    <title>WebTV.ESTIG</title><linkrel="stylesheet"href="default.css"type="text/css"/>

    </

    head><atlas:ScriptManagerID="scriptManager"runat="server"EnableScriptComponents="true"><Services><atlas:ServiceReferencePath="RSS.asmx/js"/></Services></atlas:ScriptManager>

    <

    bodytopmargin="0"leftmargin="0"rightmargin="0"background="images/ban5.jpg"><formid="form1"runat="server"><divid="Publico"class="PainelWebTV"></div>

    <

    scripttype="text/javascript"language="JavaScript">//timer = window.setInterval('parser();',1000);

    parser();

    function parser()

    {

    //Call script proxy passing the input element data

    requestSimpleService1 = iDomus.RSS.RssParser(

    'http://www.publico.clix.pt/rss.asp?idCanal=10'

    ,

    //params

    OnCompletePublico,

    //Complete event

    OnTimeoutPublico

    //Timeout event

    );

    window.clearInterval(timer);

    timer = window.setInterval(

    'parser();',10000);returnfalse;

    }

    function OnCompletePublico(result)

    {

    Publico.innerHTML = result;

    }

    function OnTimeoutPublico(result)

    {

    Publico.innerHTML =

    "Offline.";

    }

    </script></form><scripttype="text/xml-script">

    <page xmlns:script=

    "http://schemas.microsoft.com/xml-script/2005">

    <references>

    </references>

    <components>

    </components>

    </page>

    </script>

    </

    body>

    </

    html>

    ------------------------------------------

    And the WebService:

    <%

    @.WebServiceLanguage="C#"Class="iDomus.RSS" %>

    using

    System;

    using

    System.Web;

    using

    System.Collections;

    using

    System.Web.Services;

    using

    System.Web.Services.Protocols;

    using

    System.Text;

    using

    System.Text.RegularExpressions;

    using

    System.Xml;

    using

    System.Net;

    using

    System.IO;

    namespace

    iDomus

    {

    [

    WebService(Namespace ="http://idomus/")]

    [

    WebServiceBinding(ConformsTo =WsiProfiles.BasicProfile1_1)]publicclassRSS : System.Web.Services.WebService

    {

    [

    WebMethod]publicstring RssParser(string url)

    {

    string title =null;string link =null;XmlTextReader reader =null;StringBuilder sb =newStringBuilder();

    reader =

    newXmlTextReader(url);

    reader.MoveToContent();

    if (!reader.EOF)

    {

    reader.MoveToContent();

    int cont = 0;while (reader.Read() && cont < 4)//processa o ficheiro RSS

    {

    if (reader.Name =="item" && reader.NodeType ==XmlNodeType.Element)

    {

    sb.Append(

    "<img src=\"images/bullet.gif\"> ");

    }

    if (reader.Name =="title")

    {

    title = reader.ReadString();

    }

    if (reader.Name =="link")

    {

    link = reader.ReadString();

    }

    if (reader.Name =="item" && reader.NodeType ==XmlNodeType.EndElement)

    {

    sb.Append(title);

    sb.Append(

    "<br />");

    cont++;

    }

    }

    sb.Append(

    "<small>(act. " +DateTime.Now.Hour +":" +DateTime.Now.Minute +")");

    }

    return sb.ToString();

    }

    }

    }

    ----------------------------------------

    As you said, maybe the code is not in right place, but I don't know another option.

    Sorry for the length of the post and thank you again for your help.

    Regards,

    Paulo Alves.


    The Javascript error is:

    Microsoft JScript runtime error: 'iDomus' is undefined

    In Fiddler the error is:

    An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    System.Web.HttpMethodNotAllowedHandler.ProcessRequest(HttpContext context) +103
    System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +317
    System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +65

    I think the error is on the Atlas.js, but I can't figure it out.

    Paulo Alves.


    hello.

    well, it looks like a permissions problem..are you running in medium trust?


    Luis Abreu:

    hello.

    well, it looks like a permissions problem..are you running in medium trust?

    I try even put in low trust, but the error is the same.

    In my web.config I have the typical settings for Atlas:

    <

    sectionname="webServices"type="Microsoft.Web.Configuration.WebServicesSection"requirePermission="false"/>

    <

    sectionname="authenticationService"type="Microsoft.Web.Configuration.AuthenticationServiceSection"requirePermission="false"/>

    <

    sectionname="profileService"type="Microsoft.Web.Configuration.ProfileServiceSection"requirePermission="false"/>

    <

    httpHandlers>

    <

    removeverb="*"path="*.asmx"/>

    <

    addverb="*"path="*.asmx"type="Microsoft.Web.Services.ScriptHandlerFactory"validate="false"/>

    <

    locationpath="ScriptServices">

    <

    system.web>

    <

    authorization>

    <

    allowusers="*" />

    </

    authorization>

    </

    system.web>

    </

    location>

    Thank you..

    Paulo Alves.


    Hello again!

    I follow All the options addressed by Meisinger and Luis Abreu and with the change in the loaction of Javacript, I put it in the Head of the document, and using the Javascript Function:

    timerRss1 = setTimeout("parser()", 1000);

    Now it works without problems.

    Thank you very mutch Meisinger and Luis Abreu for your tips.

    Regards,

    Paulo Alves.


    hello again...

    are you saying that putting the script block in the header solves the problem?


    I thought the position of the script has influence, but I put it back in the body and still working. The change that solve me part of the problem was in the SCRIPTMANAGER:

    <atlas:ServiceReferencePath="RSS.asmx"/>

    When in the last version I put "Rss.asmx/js", like in examples of Atlas Team.

    I make this change several times but did't work. I don't know why but now is working. A lot of people had experience some problems with atlas in some specific script blocks, maybe this has the same problem and by magic disappeared.

    Regards,

    Paulo Alves.


    hello again.

    ah, i've missed it...

    well, you put the /js if you add the file by hand. for example, you could do this:

    <script type="text/javascript" src="http://pics.10026.com/?src=rss.asmx/js">
    </script>

    when you use the scriptmanager, you can't add the /js since it'll add it automatically...