How to send a parameter from java script function to a servlet - javascript

I want to send some parameters to a servlet with the help of javascript.....
In my jsp page there is a parameter "a[j]" which is generated dynamically and on a click the javascript function invoke and this a[j] parameter which is "ur" in java script function should be send to a servlet named Rank.....
Tell me which function should i use to forward the parameter...
IN Jsp:
<%out.println(a[j+1]);%>
Javascript:(rank)
<script type="text/javascript">
function rank(ur)
{ ??????????("Rank?set="+ur);
}
</script>
In Servlet(Rank):
String s = (String)request.getParameter("set");

You could do
window.location="Rank?set="+ur;
or
document.body.innerHTML+='<form id="myform" action="Rank" method="get"><input name="set" value="'+ur+'" /></form>';
document.getElementById('myform').submit();
Edit:
Ah, I think that what you need is AJAX, a group of interrelated web development techniques used on the client-side to create asynchronous web applications. With Ajax, web applications can send data to, and retrieve data from, a server asynchronously (in the background) without interfering with the display and behavior of the existing page.
Then the code is:
var xmlhttp;
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
//only if you want the response
document.getElementById("log").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","Rank?set=" + ur,true);
xmlhttp.send();
}

Related

Trigger webservice

I have a webservice that I can trigger to do various stuff by typing in the URL in a browser with some defined parameters:
Example:
http://hsserver/HomeSeer_REST_API.aspx?function=setdevicebyname&param1=bedroomlight&param2=on
I am building a web front end in plain HTML but cannot find a way to do this trigger without opening a new page in the broswer.
It would be preferable if it was a function like:
UPDATE: Got it to work with this code, but cant get the parameters to work (func,param1,param2) when I call it with
<button type="button" onclick="processnew('setdevicebyname','bedroom desktop light','off')">processnew</button>
function processnew(func,param1,param2)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","HomeSeer_REST_API.aspx?function=setdevicebyname&param1=bedroom%20desktop%20light&param2=off",true);
xmlhttp.send();
I have no clue where to look for this - hoping for some help
XHR baby.
http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
or jquery's abstraction [ajax generic, or post/get for shortcuts]
http://api.jquery.com/jquery.ajax/
well... that would be a simple HTTP GET request.
if you use jQuery, check this out: http://api.jquery.com/jquery.get/
if you want to stick to plain javascript (I wouldn't recommend that though due to some incompatibilities across browsers): http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
Try jQuery
$.ajax({
url: 'http://hsserver/HomeSeer_REST_API.aspx?function=setdevicebyname&param1=bedroomlight&param2=on',
method: 'GET' // HTTP request method
}).done(function(data) {
console.log('Response from server: ' + data);
});

Tracking visitor with javascript

I have one master domain : www.domain-A.com
I have some domains that call a javascript file on this principal domain.
For example, www.domain-B.com use the file www.domain-A.com/file.js
In this file.js script, I'm trying to put cookie (that's ok) and send some data to www.domain-A.com like the query string, the referrer and the user agent.
I've use that code in my 'file.js' (found on W3School website) :
//Envoi des données
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var json = xmlhttp.responseText;
}
}
xmlhttp.open("POST","http://www.domaine-A.com/script.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(urlParams + "&" + infParams + "&" + u);
It's working very well on FF and Chrome. But, not on IE because I have this error :
This page is accessing information not under its control
So, I've look a little how analytics send data to Google and i seem's use a GIF or something like that but i don't know how to do it in the good way.
My goal is send data from domain-x.com to domain-a.com with javascript.
What version of GA are you using? If you are on analytics.js (Universal Analtyics) You can use ajax and the measurement protocol to call page views on the other site. The measurement protocol lets you make HTTP requests and send raw data right into to GA.
I have used it before to track interaction with interactive infographic that I had on another site.
For your case you can use the following paramaters
www.google-analytics.com/collect
v=1 // Version.
&tid=UA-XXXX-Y // Tracking ID / Web property / Property ID.
&cid=555 // Anonymous Client ID.
&t=pageview // Pageview hit type.
&dh=mydemo.com // Document hostname.
&dp=/home // Page.
&dt=homepage // Title.

Using CGI methods to pass a parameter from JavaScript to Perl script over a web server

Wise ones: I am still having extreme troubles with a web application I am building. I am using an APACHE 2 web server. When in localhost, clicking on test.html will pop up a test button which should run the javascript within my .html file.
test.html is as follows:
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
var str, fileNameVar;
fileNameVar = "hello";
if (xmlhttp.readyState==4 && xmlhttp.status==200){
str = xmlhttp.responseText;
alert(str);
}
}
xmlhttp.open('GET', 'try.pl?name=fileNameVar' + encodeURIComponent(fileNameVar),false);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>Example</h2></div>
<button type="button" onclick="loadXMLDoc()">test</button>
</body>
</html>
This web app has worked before when calling a perl script and printing its return value, but this time I am trying to pass a parameter from the javascript to my perl script [try.pl]. As you see I am trying to pass the variable fileNameVar which will hold a string or an integer.
Here is my perl script, try.pl:
#!C:/indigoampp/perl-5.12.1/bin/perl.exe
use CGI;
use strict;
use warnings;
my $cgi = CGI->new;
my $name = $cgi->param('name');
print "Content-type: text/plain\n\n";
print "$name";
So when the button is pushed in my web app, it should simply create an alert to the user which contains the word "hello".
Though, when I press the button, nothing happens. I don't know what I am doing wrong, as it seems to work for others. Essentially, my web app works but I want to add the functionality of passing a variable from the javascript to the perl script.
NOTE: I do not want to pass "hello" directly in my GET statement. I want it to pass whatever is stored in fileNameVar. Though, in this example, fileNameVar is set to "hello". Thanks for ANY help!
1) Put test.html in the htdocs directory of apache2.
2) Put try.pl in the cgi-bin directory of apache2.
3) Make try.pl executable(which is probably done automatically for you on Windows). On unix, you would write:
.../apache2/cgi-bin$ chmod a+x try.pl
4) Start apache.
5) Request the test.html page by entering the following in your browser:
http://localhost:8080/test.html
(substitute in whatever port apache is listening on)
6) In this line:
xmlhttp.open('GET', 'try.pl?name=fileNameVar' + encodeURIComponent(fileNameVar),false);
...you have a few problems. You defined fileNameVar inside a function, and you are trying to access fileNameVar from outside the function. Variables defined inside a function can only be seen inside that function(exception for things called 'closures', which are functions defined inside other functions).
Secondly, in your example, encodeURIComponent() would return "hello", so your url would look like:
'try.pl?name=fileNameVar' + 'hello'
or equivalently:
'try.pl?name=fileNameVarhello'
...which is probably not what you want. You want to write:
var fileNameVar = "hello";
....'try.pl?name=' + encodeURIComponent(fileNameVar)
Next, you need to put 'cgi-bin' in the path:
var fileNameVar = "hello";
......'cgi-bin/try.pl?name=' + encodeURIComponent(fileNameVar)
7) In the line:
print "$name";
the quotes don't do anything.
====
.../apache2/htdocs/test.html:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var str = xmlhttp.responseText;
alert(str);
}
}
var fileNameVar = "hello"; //LOOK AT ME*******
xmlhttp.open(
'GET',
'cgi-bin/try.pl?name=' + encodeURIComponent(fileNameVar),
false
);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>Example</h2></div>
<button type="button" onclick="loadXMLDoc()">test</button>
</body>
</html>
...apache2/cgi-bin/try.pl:
#!/usr/bin/env perl
use CGI;
use strict;
use warnings;
my $cgi = CGI->new;
my $name = $cgi->param('name');
print "Content-type: text/plain\n\n";
print $name;
url to enter in your browser:
http://localhost:8080/test.html
(substitute in whatever port you configured apache to listen on--it's specified in .../apache2/conf/httpd.conf)
Then click on the button.
"When in localhost, clicking on test.html" says to me you might be accessing the page with a file: url, which will keep XMLHttpRequest from working.
You also want to use a standard javascript library instead of native XMLHttpRequest calls. Most of the world uses jquery these days.

xmlhttp status 200 message when adding DOCTYPE to page

I have the following code placed into a function and when the function is called it loads my XML file and displays it in a message box:
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
} else
{
alert('Panel not communicating.Reason: '+xmlhttp.status);
}
}
xmlhttp.open("POST","myfile.xml",false);
xmlhttp.send();
The above code does everything like it's meant to.
However, as soon as I add the following code to the top the page:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
when I load my function it comes up with the following message:
Panel not communicating.Reason: 200
however it still loads my XML file like how I want it to.
After searching around it says that xmlhttp status 200 means "OK"
Does anyone know why it's displaying this message?
It probably means that xmlhttp.readyState is transitioning to a state other than 4 ("complete") -- this can occur if the whole page doesn't download instantly, which is likely. Your function should probably return immediately when xmlhttp.readyState != 4, rather than treating that as an error condition.
You should also strongly consider using a Javascript framework such as jQuery here, as it will save you a lot of unnecessary effort. For instance, all of the code you've got here can be reduced to:
$.post("myfile.xml", function(data) {
alert(data);
}).error(function() {
alert("Panel not communicating.");
});
I think the code you added is not supposed to appear in XML, it was for HTML, so the browser may fail to parse the file, which made the xmlhttp.readyState==2, I am not sure for this value, may you check it.

Path issue in ajax ,in a wordpress site

I have a wordpress site
for ex, www.test.com
There is a js file (forms.js)in the script folder of mytheme folder.
ie (theme/mytheme/script/forms.js)
There is a mail.php page in mytheme folder
ie (theme/mytheme/mail.php)
Following is the content of forms.js
function submitFormToEmail()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//document.getElementById("results").innerHTML=xmlhttp.responseText;
alert("Form received, thank you!");
}
}
xmlhttp.open("GET","/mail.php",true);
xmlhttp.send();
}
I will call "submitFormToEmail",if we click a image in the page *www.test.com/hello_test*
Where "hello_test" page lies in theme/mytheme/.
But the mail.php is not working.
Let me know ,how can we set the path of mail.php in the function "submitFormToEmail", so that it will work
Calling /mail.php will look for the mail.php file at http://www.test.com/mail.php. Just fix the path?
Either directly code the correct path into the javascript file or use php to dynamically get it using get_bloginfo. There are several ways to do this, but probably the best way is to create a hidden element on the page that contains the url and then fetch this when building your ajax request. Otherwise you'd have to set php to parse js files and include it in there. Doesn't seem like a good way to me though.
get_bloginfo('template_url');

Categories

Resources