?
Solved

is it possible via a webservice to generate javascript?

Posted on 2009-04-28
18
Medium Priority
?
393 Views
Last Modified: 2012-05-06
hello experts,
i'm trying to generate javascript via a webservice,
my webservice return a string,

on my aspx page,  i catch the web service returned result which
is a javascript function in a string, the function is between script tags.

before tune my javascript
i'm just trying to display the graph,

i'm looking for such a solution any help is welcome.


[WebMethod(EnableSession = true)]
        public string GetContainerDayView(int id, string aDay)
        {
            string graph = @" <script id='source' language='javascript' type='text/javascript'>
$(function () {
    var d = [[1196463600000, 0], [1196550000000, 0], [1196636400000, 0], [1196722800000, 77], [1196809200000, 3636], [1196895600000, 3575], [1196982000000, 2736], [1197068400000, 1086], [1197154800000, 676], [1197241200000, 1205], [1197327600000, 906], [1197414000000, 710], [1197500400000, 639], [1197586800000, 540], [1197673200000, 435], [1197759600000, 301], [1197846000000, 575], [1197932400000, 481], [1198018800000, 591], [1198105200000, 608], [1198191600000, 459], [1198278000000, 234], [1198364400000, 1352], [1198450800000, 686], [1198537200000, 279], [1198623600000, 449], [1198710000000, 468], [1198796400000, 392], [1198882800000, 282], [1198969200000, 208], [1199055600000, 229], [1199142000000, 177], [1199228400000, 374], [1199314800000, 436], [1199401200000, 404], [1199487600000, 253], [1199574000000, 218], [1199660400000, 476], [1199746800000, 462], [1199833200000, 448], [1199919600000, 442], [1200006000000, 403], [1200092400000, 204], [1200178800000, 194], [1200265200000, 327], [1200351600000, 374], [1200438000000, 507], [1200524400000, 546], [1200610800000, 482], [1200697200000, 283], [1200783600000, 221], [1200870000000, 483], [1200956400000, 523], [1201042800000, 528], [1201129200000, 483], [1201215600000, 452], [1201302000000, 270], [1201388400000, 222], [1201474800000, 439], [1201561200000, 559], [1201647600000, 521], [1201734000000, 477], [1201820400000, 442], [1201906800000, 252], [1201993200000, 236], [1202079600000, 525], [1202166000000, 477], [1202252400000, 386], [1202338800000, 409], [1202425200000, 408], [1202511600000, 237], [1202598000000, 193], [1202684400000, 357], [1202770800000, 414], [1202857200000, 393], [1202943600000, 353], [1203030000000, 364], [1203116400000, 215], [1203202800000, 214], [1203289200000, 356], [1203375600000, 399], [1203462000000, 334], [1203548400000, 348], [1203634800000, 243], [1203721200000, 126], [1203807600000, 157], [1203894000000, 288]];
 
    // first correct the timestamps - they are recorded as the daily
    // midnights in UTC+0100, but Flot always displays dates in UTC
    // so we have to add one hour to hit the midnights in the plot
    for (var i = 0; i < d.length; ++i)
      d[i][0] += 60 * 60 * 1000;
 
    // helper for returning the weekends in a period
    function weekendAreas(axes) {
        var markings = [];
        var d = new Date(axes.xaxis.min);
        // go to the first Saturday
        d.setUTCDate(d.getUTCDate() - ((d.getUTCDay() + 1) % 7))
        d.setUTCSeconds(0);
        d.setUTCMinutes(0);
        d.setUTCHours(0);
        var i = d.getTime();
        do {
            // when we don't set yaxis the rectangle automatically
            // extends to infinity upwards and downwards
            markings.push({ xaxis: { from: i, to: i + 2 * 24 * 60 * 60 * 1000 } });
            i += 7 * 24 * 60 * 60 * 1000;
        } while (i < axes.xaxis.max);
 
        return markings;
    }
    
    var options = {
        xaxis: { mode: 'time' },
        selection: { mode: 'x' },
        grid: { markings: weekendAreas }
    };
    
    var plot = $.plot($('#placeholder'), [d], options);
    
    var overview = $.plot($('#overview'), [d], {
        lines: { show: true, lineWidth: 1 },
        shadowSize: 0,
        xaxis: { ticks: [], mode: 'time' },
        yaxis: { ticks: [], min: 0, max: 4000 },
        selection: { mode: 'x' }
    });
 
    // now connect the two
    
    $('#placeholder').bind('plotselected', function (event, ranges) {
        // do the zooming
        plot = $.plot($('#placeholder'), [d],
                      $.extend(true, {}, options, {
                          xaxis: { min: ranges.xaxis.from, max: ranges.xaxis.to }
                      }));
 
        // don't fire event on the overview to prevent eternal loop
        overview.setSelection(ranges, true);
    });
    
    $('#overview').bind('plotselected', function (event, ranges) {
        plot.setSelection(ranges);
    });
});
</script>
";
 
 
            return graph;
        }

Open in new window

0
Comment
Question by:toshi_
  • 10
  • 8
18 Comments
 
LVL 9

Expert Comment

by:Gorkem Yuksel
ID: 24252268
Hi Toshi,

When you get the returned javascript from your webservice, you can simply add it to your page using the RegisterClientScript function.

string graph_Javascript = YourWebService.GetContainerDayView(id,day);
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "graph", graph_Javascript, false);

Cheers,

G.
0
 

Author Comment

by:toshi_
ID: 24252397
thank you for the answer gyuksel,

my problem is that i call my webservice via javascript with post values,
it's because i'm using a webcontrol i didnot desing to which i can only add
onclick event, which is a client click.


i copy the code of the class i'm using in order to call webservices,
the thing is working as i used several times in my code, i'm pasting it for info,
dont look at it for finding errros ;o)


the following function is my call,

  function ViewSingleDay(aDay){
        var myDay = formatDay(aDay); // jour sur deux digits.
        var YearMonth = document.getElementById("HiddenMonthAndYear").value;
        var DayToView = YearMonth + "-" + myDay;
        var ContainerId = document.getElementById("CurrentContainerId").value;
       
        // invocation webservice
        var pathWebServiceFile = pathWebService.concat("/CommunityAdmin.asmx/GetContainerDayView");
        alert("container id:"  + ContainerId + "\nMOnthYear:" + YearMonth+ "\nDay:" + DayToView
            + "\npathToWebService : " +pathWebServiceFile);
           
        var rpcObj = new rpcClass();
        rpcObj.setReqType("post");     // type de requete à passer
        rpcObj.setRequest(pathWebServiceFile, "id=" +ContainerId+ "&aDay=" +DayToView);
        rpcObj.asynchCall = true;     // requete asynchrone.
        rpcObj.resultType = 1;         // la rep est text
        rpcObj.resultKey = "ViewLevelForADay";  // clé de rappel
        rpcObj.launchRequest();  
       
    }

this is the callback from where i recover the response values.
 
function __callbackRPC(key, result){
   
            switch(key){
           
                case "ViewLevelForADay":
                    var blackBoard = document.getElementById("ChartForADay");
                    alert(blackBoard.innerHTML);
                   
                    var recu = result.getElementsByTagName("string")[0].firstChild.nodeValue;
                    alert(recu);
                    blackBoard.innerHTML= recu;
                    document.getElementById("ChartForADay").style.display = "block";
                   break;
               case .....
               default

here's my div where i'd like my js to display the graphic......

<div id="ChartForADay" style="display:none; background-color:#eeeeff; border:1px solid black; position:absolute; top:420; left:300; width:400px; height:200px;">
</div>

have you an idea on how i can deal with this mess?
i've working around without success,

i'm like housewifes  -> desperate!!!!! help

// Constructeur - debut
	function rpcClass() {
		
		// Variables de classe
		
		// Nom de la classe
		this.nom = "classe RPC";
		
		// Booleen indiquant si un resultat a ete retourne
		this.resultRequest = false;
		// String contenant le resultat retourne
		this.result = "";
		
		// Booleen indiquant si la definition du type de requête a ete parametree
		this.reqTypeDef = false;
		// String contenant le type de requête ('get' et 'post' actuellement supportes)
		this.typeOfRequest = "";
		
		// Booleen indiquant si la requête à executer a ete parametree
		this.requestDef = false;
		// String contenant la requête à executer
		this.request = "";
		
		// Booleen indiquant si la communication doit être asynchrone (true) ou synchrone (false)
		this.asynchCall = false;
		
		// String contenant les paramètres de la requête à executer
		this.parameters = "";
		
		// Format des resultats (0 = texte, 1 = XML)
		this.resultType = 0;
		
		// Clé de retour à utiliser dans un rappel asynchrone
		this.resultKey = "";
		
		// Fonctions de classe
		this.setReqType = setReqType;
		this.setRequest = setRequest;
		this.setResultType = setResultType;
		this.setResultKey  = setResultKey;
		this.setAsynchCall = setAsynchCall;
		this.launchRequest = launchRequest;
		this.returnResult = returnResult;
		this.callToServer = callToServer;
		
	}
	// Constructeur - fin
 
 
    function setAsynchCall(a) {
        this.asynchCall = a;
    }
    function setResultType(t) {
        this.resultType = t;   
    }
    function setResultKey(k) {
        this.resultKey = k;
    }
 
	
	// Fonction de definition du type de requête - debut
	function setReqType(reqType) {
		
		// Mise en minuscules du type de requête
		reqType.toLowerCase();
		
		// Test le type de requête demande
		switch(reqType) {
			case "get" :
				// Type de requête GET
				this.typeOfRequest = "get";
				break;
				
			case "post" :
				// Type de requête POST
				this.typeOfRequest = "post";
				break;
				
			default :
				// Type de requête par defaut (GET)
				reqType = "get";
				this.typeOfRequest = "get";
				
		}
		
		this.reqTypeDef = true;
		return this.typeOfRequest;
		
	}
	// Fonction de definition du type de requête - fin
	
	// Fonction de definition de la requête - debut
	function setRequest(request, parameters) {
		
		// Test si la requête n'est pas vide
		if (request!='') {
			//Si oui, definition de la requête dans la variable de classe
			this.request = request;
			//Definition des paramètres dans la variable de classe
			this.parameters = parameters + "&:-)"; //?????????????????????????????"&:-)"
 
			this.requestDef = true;
			return true;
		} else {
			// Si non, erreur
			return false;
		}
		
	}
	// Fonction de definition de la requête - fin
	
	// Fonction d'execution de la requête - debut
	function launchRequest() {
		
	  // Test si la requête, le type de requête et le type d'appel sont definis
		if (this.requestDef && this.reqTypeDef) {
			// Si oui, lancement de la requête
			this.callToServer(this.resultKey, this.resultType);
			return true;
		} else {
			// Si non, erreur
			return false;
		}
		
	}
	// Fonction d'execution de la requête - fin
 
	// Fonction executant la requête avec httprequest - debut
	function callToServer(resultKey, resultType) {
 
		// Variable stockant l'objet de type HTTP Request
		var xmlhttp;
		
		// Test si l'objet est initialise
		if (!xmlhttp) {
 
            // branch for native XMLHttpRequest object
            if (window.XMLHttpRequest) {
            	xmlhttp = new XMLHttpRequest();
            // branch for IE/Windows ActiveX version
            } else if (window.ActiveXObject) {
            	xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
		}
		
		// Test si l'objet a bien ete instancie
		if (xmlhttp) {
		    
		    // Definition du callBack si appel asynchrone
		    if (this.asynchCall) {
        		xmlhttp.onreadystatechange = function() {
            		if (xmlhttp.readyState == 4) /* 4 : état "complete" */ 	{
            		    if (resultType == 0) /* Texte */ {
            		        __callbackRPC(resultKey,xmlhttp.responseText); 
            		    }
            		    if (resultType == 1) /* XML */ {
            		        __callbackRPC(resultKey,xmlhttp.responseXML); 
            		    }
            		}
        		}
        		
		    }
			
			switch(this.typeOfRequest) {
				
				case "get" :
					// Type de requête GET
					// Code utilise lors d'une requête synchrone
					//Ouverture et envoi de la requête
					requestParam = this.request + "?" + this.parameters;
					xmlhttp.open("GET", requestParam, this.asynchCall);
					xmlhttp.send(null);
					break;
				
				case "post" :
					// Type de requête POST
					// Code utilise lors d'une requête synchrone
					//Ouverture et envoi de la requête
					
					//alert("Request:" + this.request);
					//alert("Parameters: " + this.parameters);
					
                    xmlhttp.open("POST", this.request, this.asynchCall);
                    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
                    xmlhttp.send(this.parameters);
					
					break;
				
			}
			
			if (!this.asynchCall) {
  			    // Stockage du resultat de la requête synchrone
			    if (this.resultType == 0) /* Texte */ {
			        this.result = xmlhttp.responseText;
			    }
			    if (this.resultType == 1) /* XML */ {
			        this.result = xmlhttp.responseXML;
			    }  			    
			 	this.resultRequest = true;
			 	
			 	// alert("Results : " + this.result);
                // alert("Request:" + this.request + "\n\n" + "Parameters: " + this.parameters + "\n\n" + "Results : " + this.result );
 
			 
			} else {
                this.resultRequest = false;
            }
			
		} else {
			this.resultRequest = false;
		}
		
		return this.resultRequest;
		
	}
	// Fonction executant la requête avec httprequest - fin
	
	// Fonction rendant le resultat de la requête - debut
	function returnResult() {
 
		result = "";
 
		// Test si le resultat de la requête a bien ete stocke
		if (this.resultRequest) {
			// Si oui, test le type d'appel
			// Cela permet d'eventuellement pre-traiter le resultat suivant le type d'appel utilise
			switch(this.callType) {
		
				case "httpreq" :
					result = this.result;
					break;
					
			}
			// Renvoi du resultat
			return this.result;
					
		} else {
			// Si non, erreur
			return false;
		}
				
	}
	// Fonction rendant le resultat de la requête - fin
	

Open in new window

0
 
LVL 9

Accepted Solution

by:
Gorkem Yuksel earned 2000 total points
ID: 24252729
from what I can gather, your rpc callback function gets the result, and you take the javascript into a variable called "recu"..

I see that you are essentially adding it to the innerHTML of the div.  This will not execute the javascript code because this code would have already been "executed" when the page first loaded.  You need a way to execute the new javascript and insert the image in the proper place.

Does the javascript have to be inside the DIV tag? If I understand the javascript correctly (and I may be way off here), it is updating a graph that is already on the page somewhere.  So technically, you can get away with just making sure your javascript is executed.

Have you tried the following?  ** You will need to strip out the <SCRIPT></SCRIPT> tags though.. **

eval(recu);

Cheers,

G.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:toshi_
ID: 24258096
Yes, what you gather is what i do; callback receives the result and i take to  the variable recu.

for your question; my javascript  doesn't have to be inside the DIV tag, my idea was to write it to  somewhere i would position before, and make it visible when the javascript is in to it,
as my aim is to  display a chart in that div.

i'm not updating a graph that is on the page, the javascript i want to be executed would generate it.

i'm going to try eval,

ps: sorry for the delay, i left work yesterday ;)



 
 

0
 

Author Comment

by:toshi_
ID: 24260081
i'm back to you as can not find any solution,
i've been trying with a eval but it doesn't display  the graph.


when i copy the piece of code, inside the div, the graph display,
when i eval what i receive nothing display,

is there a possibility for me to eval once the string is set inside the div?
.....help....


0
 

Author Comment

by:toshi_
ID: 24260092
i forgot to mention that when i set my string inside the div,
i can read the js code inside the div...

0
 
LVL 9

Expert Comment

by:Gorkem Yuksel
ID: 24260185
You can read the code from the souce code or in the HTML view of the page?  I'm guessing that the code actually appears as text in your webpage.

I'm looking into why the eval isn't working for you..  I'll get back to you shortly.

Cheers,

G.
0
 
LVL 9

Expert Comment

by:Gorkem Yuksel
ID: 24260262
Hi Toshi,

I've tested the eval solution, and it is working for the small test that I have done.. Are you taking out the <SCRIPT></SCRIPT> tags before passing it to the eval() function?

I've attached a small html example of what I mean.

Cheers,

G.
<HTML>
<HEAD>
<TITLE>Test</TITLE>
</HEAD>
<BODY>
 
<div id="txtdiv"></div>
 
<script language="javascript">
var js = "function writesometext(txt) { document.getElementById('txtdiv').innerText = txt; } writesometext('This is a test');";
 
eval(js);
</script>
<P>&nbsp;</P>
 
</BODY>
</HTML>

Open in new window

0
 

Author Comment

by:toshi_
ID: 24260747
hi gyukse,

yes, i removed the <script> </script>

here 's the string i return from my webservice,
when i paste the code in the div it's ok,  but not when i put it in it.


  [WebMethod(EnableSession = true)]
        public string GetContainerDayView(int id, string aDay)
        {
            string graph =
                @"$(function () {
                // ---| DATA GRAPH |---  
                var data = [{
                    color: 'rgba(0,0,244, 0.8)',
                    label: '9832 :: 2009-03-21',
                    data: [ [0, 2050], [1, 2100], [2, 2150], [3, 2100], [4, 2000], [5, 2040],
                            [6, 1900], [7, 1800], [8, 1850], [9, 1600], [10, 1550], [11, 1700],
                            [12, 1800], [13, 1500], [14, 1400], [15, 1350], [16, 1300], [17, 1400],
                            [18, 1300], [19, 1500], [20, 1400], [21, 1450], [22, 1300], [23, 1320]
                            ],
                }];
                // ---| CONFIG GRAPH DISPLAY |---  
                var options = {
                    yaxis: {max:2200, min:700},
                    lines : {show:true, color : 'rgba(0, 0, 255, 0.8)'},
                    //grid : {color: #0000ff},
                };
             
                $.plot($('#ChartForADay'),  data, options);
                });";
           
            return graph;
        }

the js libraries are included in the aspx page, as i said before, if i paste it it's ok,

hope you can help me further, thank you in advance
0
 
LVL 9

Expert Comment

by:Gorkem Yuksel
ID: 24272567
Hi Toshi,

Can you paste the reworked code that executes the javascript?  Perhaps there is an error somewhere in that code.

Cheers,

G.
0
 

Author Comment

by:toshi_
ID: 24274883
indeed,
i've been trying so many things,  i'm not shure what should work so it's frustrating

here s the code,


  function __callbackRPC(key, result){
   
            switch(key){
           
                case "ViewLevelForADay":
               
                    // recover the string from webservice.
                    var recu = result.getElementsByTagName("string")[0].firstChild.nodeValue;
                    // div where i want the graphic to appear.
                    var blackBoard = document.getElementById("ChartForADay2");
                   
                    blackBoard = eval(recu);   // B
                    //eval(blackBoard = recu);  // A
                   
                    // second thing i try
                    //var js = "document.getElementById('ChartForADay').innerText = " +recu+ ";";
                    //var blackBoard = eval(js);
                    //eval(js);      
                   
                   
question: if B and A are possibles, what are the differences between them?

0
 

Author Comment

by:toshi_
ID: 24298934
any idea?
0
 
LVL 9

Expert Comment

by:Gorkem Yuksel
ID: 24301664
Hi Toshi,

Can you try this and report back on how it works?

function __callbackRPC(key, result){
   
           switch(key){
           
               case "ViewLevelForADay":
               
                   // recover the string from webservice.
                    var recu = result.getElementsByTagName("string")[0].firstChild.nodeValue;
                   // div where i want the graphic to appear.
                   var blackBoard = document.getElementById("ChartForADay2");
                   
                   //blackBoard = eval(recu);   // B
                   //eval(blackBoard = recu);  // A
                 
                   // Execute the Javascript code right away.. anything else besides this code will NOT execute.
                   eval(recu);

                   // second thing i try
                   //var js = "document.getElementById('ChartForADay').innerText = " +recu+ ";";
                   //var blackBoard = eval(js);
                   //eval(js);      
0
 

Author Comment

by:toshi_
ID: 24301997
i'm so disppointed that i cannot display the chart,
what would be the code to open it in a new window?

with window.open, what would be the better part to do it ?
if you show me can be easier for me,

thank in advance.

0
 
LVL 9

Expert Comment

by:Gorkem Yuksel
ID: 24306296
Toshi... Does the new code I posted not work?  What is the response in the browser when executed?  Do you get a any indicators? javascript errors?

Cheers,

G.
0
 

Author Comment

by:toshi_
ID: 24307403
thank you for still there...;o)

no, the code didnot work,

i receive the following error in javascript console :

"Error: result.getElementsByTagName is not a function
Source File: http://localhost/eplan/02_container/01_containerMonthlyView.aspx?id=983042  Line: 216"


i dont understand, i can extract the value out of the xml, so what's the problème with this method?
0
 
LVL 9

Expert Comment

by:Gorkem Yuksel
ID: 24314770
Hi Toshi,

It seems as though the error is happening here:

--> var recu = result.getElementsByTagName("string")[0].firstChild.nodeValue;

it isn't even getting to the part where it executes the code.  Is the RESULT value not just the javascript?

If it is an XML response, make sure that it is returned as an XML object in javascript and not text.. :o)
Cheers,
G.

0
 

Author Comment

by:toshi_
ID: 24335625
i dont know what to do next....

btw , do you know a good asp.net control to display graphics ?
as far as i understand my prog wont work., i need to work with different controls.

0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
The purpose of this video is to demonstrate how to set up the WordPress backend so that each page automatically generates a Mailchimp signup form in the sidebar. This will be demonstrated using a Windows 8 PC. Tools Used are Photoshop, Awesome…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an anti-spam), the admin…
Suggested Courses
Course of the Month17 days, 12 hours left to enroll

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question