Solved

How can I insert user form variables into javascript?

Posted on 2009-03-30
11
775 Views
Last Modified: 2012-08-13
I have some clever javacript that gets RSS feeds, [see the snippet, and thanks experts Robinu and Sunithnair for the help building this code.]

Now, I want to run it with the user entering the feed addresses instead of the addresses being hard coded as they are at present.

In this example I have 2 feeds but I could have many more.

Currently, the user enters their feed urls into a form as in these examples. This works.


<input type="text" name="textarea_l1" size="30" value="Put code for an RSS feed here" onblur="if(this.value == '') { this.value='Put code for an RSS feed here'}" onfocus="if (this.value == 'Put code for an RSS feed here') {this.value=''}" />
<input type="text" name="textarea_l2" size="30" value="Put code for an RSS feed here" onblur="if(this.value == '') { this.value='Put code for an RSS feed here'}" onfocus="if (this.value == 'Put code for an RSS feed here') {this.value=''}" />

I put those user inputs into variables by the following method. This works too.

bodycode_l1 = document.inputForm.textarea_l1.value;
bodycode_l2 = document.inputForm.textarea_l2.value;

Now, I need to get those into my getFeeds(), which is currently hard-coded like this.

getFeed("http://tvnz.co.nz/content/1323589/rss_20_skin.xml","a_source")  
getFeed("http://feeds.reuters.com/reuters/worldNews","b_source")

I need to make it so the javascript doesn't crash if the user doesn't enter anything into a particular form variable.
The logic would be something like "if variable bodycode_l1 includes the string 'http:' use it in getfeed().
Otherwise, do nothing."

Thanks.
<html>

<head>

<title>News</title>

<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf-8">

<meta name="generator" content="BBEdit 7.1.4">
 

<style type="text/css">
 

p

{

	font-family: Times New Roman, Times, serif;

	font-size: 12px;

	line-height: 115%;

	margin: 10px;

}
 

div

{	

	font-family: Times New Roman, Times, serif;

	font-size: 12px;

	line-height: 115%;

	margin: 0px;

}
 

h1

{	

	font-family: Times New Roman, Times, serif;

	font-size: 20px;

	font-weight: bold;

	margin: 10px;

}

</style>
 

<script type="text/javascript">         

var puthere = new Array();

var count1 = 0;

var count2 = 0;

function getFeed(feed,div_id) {

  puthere[count1]=div_id;

  count1++;

  var newScript = document.createElement('script');

  newScript.type = 'text/javascript';

  newScript.src = 'http://pipes.yahoo.com/pipes/9oyONQzA2xGOkM4FqGIyXQ/run?&_render=json&_callback=piper&feed='+feed;

  document.getElementsByTagName("head")[0].appendChild(newScript);

}

function piper(feed) {

  var tmp='';

  for (var i=0; i<feed.value.items.length; i++) {

    tmp+='<a href="'+feed.value.items[i].link+'">';

    tmp+=feed.value.items[i].title+'</a><br>';

    if (feed.value.items[i].description) {

      tmp+=feed.value.items[i].description;

    }

    tmp+='<hr>';

  }

  document.getElementById(puthere[count2]).innerHTML=tmp;

  count2++;

} 

function getFeeds()

{

getFeed("http://tvnz.co.nz/content/1323589/rss_20_skin.xml","a_source")   

getFeed("http://feeds.reuters.com/reuters/worldNews","b_source")

}

</script>
 

</head>

<body onload="getFeeds()">
 

<h1>My News</h1>

<p>TVNZ</p>  

<div id='a_source'>

</div>

<p>Reuters</p>  

<div id='b_source'>

</div>
 

</body>

</html>

Open in new window

0
Comment
Question by:NEILPH
  • 7
  • 4
11 Comments
 
LVL 29

Expert Comment

by:David H.H.Lee
ID: 24025722
Hi NEILPH,
>>..The logic would be something like "if variable bodycode_l1 includes the string 'http:' use it in getfeed().
You can append this checking under getfeed() function.

eg:
function getFeed(feed,div_id) {
 if(feed.toString().indexOf('http')!=-1){ //this line of checking
  puthere[count1]=div_id;
  count1++;
  var newScript = document.createElement('script');
  newScript.type = 'text/javascript';
  newScript.src = 'http://pipes.yahoo.com/pipes/9oyONQzA2xGOkM4FqGIyXQ/run?&_render=json&_callback=piper&feed='+feed;
  document.getElementsByTagName("head")[0].appendChild(newScript);
 }
}

0
 

Author Comment

by:NEILPH
ID: 24025831
Thanks x_com. I'll give that a go tomorrow.
0
 

Author Comment

by:NEILPH
ID: 24035691
x_com. Your error trapping works perfectly. Nice job.

Part of my question was also how to get the user input into the getFeed() function. If you prefer I can post that as a new question and give you 500 points for your solution to date. Let me know.

To recap, I currently have users entering this kind of form input...

<input type="text" name="textarea_l1" size="30" value="Put code for an RSS feed here" onblur="if(this.value == '') { this.value='Put code for an RSS feed here'}" onfocus="if (this.value == 'Put code for an RSS feed here') {this.value=''}" />

I then put those user inputs into variables, e.g...

bodycode_l1 = document.inputForm.textarea_l1.value;

Now, I need to get those into my getFeeds(), which are currently hard-coded like this.

getFeed("http://tvnz.co.nz/content/1323589/rss_20_skin.xml","a_source")  

Your error trapping routine kicks in after that.

Thanks again.
0
 
LVL 29

Expert Comment

by:David H.H.Lee
ID: 24036154
Hi NEILPH,
I'm not sure which event that you're trying to perform getFeeds() function after user enter the value inside  "textarea_l1" control. But, here is one of the sample showing how it work under button's onclick event. You can amend it into your existing js code.
eg:
<input type=button id="btn" value=" Proceed " onclick="javascript: getFeeds();"/>

<script>
function getFeeds()
{
var strDefault='Put code for an RSS feed here';
var bodycode_l1 = document.inputForm.textarea_l1.value;
var bodycode_l2 = document.inputForm.textarea_l2.value;

if((bodycode_l1.toString()!='') || (bodycode_l2.toString()!=strDefault)){
  getFeed(bodycode_l1,"a_source");  
}

if((bodycode_l2.toString()!='') || (bodycode_l2.toString()!=strDefault)){
  getFeed(bodycode_l2,"b_source");  
}

}
</script>
0
 

Author Comment

by:NEILPH
ID: 24043493
Thanks again. I've got a full-on day today so I'll get back to you tomorrow.
0
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 

Author Comment

by:NEILPH
ID: 24056493
Thanks again x_com. Sorry to be slow responding. I suddenly got extra other work I had to do promptly.

I don't think my project would work calling getFeeds() from the button's OnClick event. And I think it's probably not necessary. The reason is that there are two pages. The user enters the RSS urls into the form on page one and then clicks the button that generates the second page, which contains the javascript functions including getFeeds(), that call the RSS feeds.

For this reason, looking at your suggested code I figured that all I needed to do was adapt my original lines
getFeed("http://tvnz.co.nz/content/1323589/rss_20_skin.xml","a_source")
getFeed("http://feeds.reuters.com/reuters/worldNews","b_source")

to
getFeed(bodycode_l1,"a_source")
getFeed(bodycode_l2,"b_source")

However, when the second page is generated the RSS isn't called. Instead, the browser gives this error message: 'body_i1' is undefined.

This surprises me because if on the first page I include the following...
'<p>' +
bodycode_l1 + '<br>' +
bodycode_l2 + '<br>' +
'</p>\n' +

...then on the second page I see a paragraph containing literally what I entered on the form for variables bodycode_l1 and bodycode_l2.

In other words, as far as the paragraph is concerned those variables are defined, so why does the javascript error message say they are undefined?
I think we're fairly close to making this work. Thanks so far.
0
 
LVL 29

Expert Comment

by:David H.H.Lee
ID: 24057326
Hi NEILPH,
Do you able to retrieve any value for "bodycode_l1" before being passed into getFeed() function as mentioned?
eg:
alert(bodycode_l1);//check value?
getFeed(bodycode_l1,"a_source")

Please provide some related code snippet for further investigations seemed it close to the solution gate.
0
 

Author Comment

by:NEILPH
ID: 24065597
x_com,
I incorporated your alert(bodycode_l1) as suggested and ran the first page again to generate the second page. Surprisingly, it didn't display the alert but I still got the error message: 'body_i1' is undefined.

I don't know what's happening. I expected the alert to show.

Let's keep in mind that this all works when I hard code getFeed("http://feeds.reuters.com/reuters/worldNews","a_source"). It's only using the variable that is the probblem: getFeed(bodycode_l1,"a_source"). Also, the variable bodycode_l1 successfully displays in a paragraph on the generated page.


The 4-steps code snippet gives more detail.

Thanks so far.


1. The user inputs into the form like this...
 

<input type="text" name="textarea_l1" size="30" value="Put code for an RSS feed here" onblur="if(this.value == '') { this.value='Put code for an RSS feed here'}" onfocus="if (this.value == 'Put code for an RSS feed here') {this.value=''}" />
 
 

2. The user clicks this button...
 

<input type="button" value="Generate page code" onClick="javascript:preview();">

function preview() {

    var htmlCode = generateCode();

    var newWindow = window.open('');

    newWindow.document.write(htmlCode)

}
 
 

3. This creates a new HTML page, containing code constructed on the first page, including the following...
 

'</style>\n' +

'<scr' + 'ipt type="text/javascript' + '">\n' +  

'var puthere = new Array();\n' +

'var count1 = 0;\n' +

'var count2 = 0;\n' +

'function getFeed(feed,div_id) {\n' +

 "if(feed.toString().indexOf('http')!=-1){\n" +

   'puthere[count1]=div_id;\n' +

   'count1++;\n' +

   "var newScript = document.createElement('script');\n" +

   "newScript.type = 'text/javascript';\n" +

   "newScript.src = 'http://pipes.yahoo.com/pipes/9oyONQzA2xGOkM4FqGIyXQ/run?&_render=json&_callback=piper&feed='+feed;\n" +

   'document.getElementsByTagName("head")[0].appendChild(newScript);\n' +

 '}\n' +

'}\n' +

'function piper(feed) {\n' +

  "var tmp='';\n" +

  'for (var i=0; i<feed.value.items.length; i++) {\n' +

    "tmp+='" + '<a href="' + "'+feed.value.items[i].link+'" + '">' + "';\n" +

    "tmp+=feed.value.items[i].title+'</a><br>';\n" +

    'if (feed.value.items[i].description) {\n' +

      'tmp+=feed.value.items[i].description;\n' +

    '}\n' +

    "tmp+='<hr>';\n" +

  '}\n' +

  'document.getElementById(puthere[count2]).innerHTML=tmp;\n' +

  'count2++;\n' +

'}\n' +

'function getFeeds()\n' +

'{\n' +

'alert(bodycode_l1)\n' +

'getFeed(bodycode_l1,"a_source")\n' +

'getFeed(bodycode_l2,"b_source")\n' +

'}\n' +

'</scr' + 'ipt>\n' +   

'</head>\n' ;
 
 

//Text

bodycode_l1 = document.inputForm.textarea_l1.value;

bodycode_l2 = document.inputForm.textarea_l2.value;
 

output = pghead + 

'<body onload="getFeeds()">\n' + 

"<div id='a_source'>" + 

'</div>' +

"<div id='b_source'>" + 

'</div>' +
 

'<p>' +

bodycode_l1 + '<br>' + 

bodycode_l2 + '<br>' + 

'</p>\n' +
 

'</body>\n' +

'</html>\n';
 

document.inputForm.source.value = output;
 

return output;

}
 
 
 
 

4. The resulting second page includes the following...
 
 

function getFeeds()
 

{
 

alert(bodycode_l1)
 

getFeed(bodycode_l1,"a_source")
 

getFeed(bodycode_l2,"b_source")
 

}
 

</script>
 

</head>
 

<body onload="getFeeds()">

Open in new window

0
 

Author Comment

by:NEILPH
ID: 24065779
After posting the above I realised that alert(bodycode_l1) probably wouldn't run from where I had placed it because <body onload="getFeeds()"> might bypass it.

I temporarily tried <body onload=alert(bodycode_l1)> and <body onload="alert(bodycode_l1)"> but they didn't display the alert either, and I still got error message: 'body_i1' is undefined.

 
0
 

Accepted Solution

by:
NEILPH earned 0 total points
ID: 24073580
x_com,

I solved why the javascript in the generated page can't see the variable bodycode_l1 that the user entered in the form in the page that generates the new page.

It took me a bit of effort until I suddenly realised that the answer is simple. Passing javascript variables between pages is a separate, more complex problem; usually solved by adding them to the url or using PHP, etc.

So the first page can't easily pass variables to the generated page. The variables have to be turned into literals in the construction of the code that will be contained in the generated page.

Here's the correct code on the first page...

'getFeed("' + bodycode_l1 + '",' + '"a_source")\n' +

If the user entered http://www.google.com in the form variable, the generated page code appears as...

getFeed("http://www.google.com","a_source")

Thanks for your help.

I reckon we solved this between us, so would you agree if we split the points evenly between us?
0
 
LVL 29

Assisted Solution

by:David H.H.Lee
David H.H.Lee earned 350 total points
ID: 24074140
Hi NEILPH,
I'm glad you resolve the answer before i visit this thread. I'm only come in ee during my spare time in weekday. Ok, you can request to split the points for this question. Cheers.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

SASS allows you to treat your CSS code in a more OOP way. Let's have a look on how you can structure your code in order for it to be easily maintained and reused.
This is a PowerShell web interface I use to manage some task as a network administrator. Clicking an action button on the left frame will display a form in the middle frame to input some data in textboxes, process this data in PowerShell and display…
In this tutorial viewers will learn how to position overlapping items using z-index in CSS. They will also learn the restrictions on the z-index property.  Create a new HTML document with an internal stylesheet.: Create a div in CSS and name it Red.…
In this tutorial viewers will learn how to embed videos in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: "<!DOCTYPE html>": Use the <video> tag to insert a video. Define the src as the URL of your video; this is similar to …

746 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now