How to get JSON object in Servlet from JSP? - javascript

In JSP page I have written:
var sel = document.getElementById("Wimax");
var ip = sel.options[sel.selectedIndex].value;
var param;
var url = 'ConfigurationServlet?ActionID=Configuration_Physical_Get';
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
httpRequest.open("POST", url, true);
httpRequest.onreadystatechange = handler(){
if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
param = 'ip='+ip;
param += 'mmv='+mmv;
param += "tab="+tab;
}};
httpRequest.send(param);
I want this param variable in my ConfigurationServlet. Can anyone tell me how to get this json object in servlet?
Update: I changed my statements and now it is showing status code as 200.
var index = document.getElementById("Wimax").selectedIndex;
var ip = document.getElementById("Wimax").options[index].text;
httpReq = GetXmlHttpObject();
alert(httpReq);
var param = "ip=" + ip;
param += "&mmv=" + mmv;
param += "&tab=" + tab;
alert("param "+param);
var url="http://localhost:8080/WiMaxNM/ConfigurationServlet?ActionID=Configuration_Physical_Get";
url = url+"?"+param;
httpReq.open("GET",url,true);
alert("httpReq "+httpReq);
httpReq.onreadystatechange = handler;
httpReq.send(null);
But new problem has occured. Control is not at all going to the servlet action ID as specified in url. Please tell me what is wrong here.

The code in the handler will only be invoked AFTER the request is been sent. You need to populate param before this. You would also need to concatentate separate parameters by &.
Thus, e.g.
// ...
httpRequest.onreadystatechange = handler() {
// Write code here which should be executed when the request state has changed.
if (httpRequest.readyState == 4) {
// Write code here which should be executed when the request is completed.
if (httpRequest.status == 200) {
// Write code here which should be executed when the request is succesful.
}
}
};
param = 'ip=' + ip;
param += '&mmv=' + mmv;
param += "&tab=" + tab;
httpRequest.send(param);
Then you can access them in the servlet the usual HttpServletRequest#getParameter() way.
That said, the Ajax code you posted there will only work in Microsoft Internet Explorer, not in all the four other major webbrowsers the world is aware of. In other words, your Javascript code won't work for about half of the people in the world.
I suggest to have a look at jQuery to lessen all the verbose work and bridge the crossbrowser compatibility pains. All your code could be easily replaced by
var params = {
ip: $("Wimax").val();
mmv: mmv,
tab: tab
};
$.post('ConfigurationServlet?ActionID=Configuration_Physical_Get', params);
And still work in all webbrowsers!
Update: as per your update, the final URL is plain wrong. The ? denotes a start of the query string. You already have one in your URL. You should use & to chain parameters in the query string. I.e.
url = url + "&" + param;

Related

why does xmlHttpRequest.Open only work when I input a string?

I'm trying to call a Restful service on my localhost. I am doing it this way because It's an asynchronous call. The appropriate Url plus the Uri-template to call my service is this:
"http://localhost:65016/Service1.svc/SN?lower=200&upper=300"
on the line where I try to open ( xhttp.open ), my client page only receives the proper data whenever I literally insert the url like this:
xhttp.open("GET", "http://localhost:65016/Service1.svc/SN?lower=200&upper=300" , true);
but I need the 200 and 300 numbers to be user input so I tried these two things:
I first tried grabbing the user input and simply concatenating it to the base URL in between the URi template like this:
<script>
function ServiceCall()
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function ()
{
if (xhttp.readyState == 4 && xhttp.status == 200) {
var ans = document.getElementById("secretNum");
ans.innerHTML = xhttp.responseText;
}
}
var base_uri = "http://localhost:65016/Service1.svc/";
// grab the lower number
var ln = document.getElementById("LN").firstChild;
var LN = ln.nodeValue;
// grab upper number
var un = document.getElementById("UN").firstChild;
var UN = un.nodeValue;
//complete
var URL = base_uri + "SN?lower=" + LN + "&upper=" + UN;
xhttp.open("GET", URL, true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send();
}
</script>
Doesn't work. So i tried looking at the documentation for the xmlHttpRequest.open, and I saw that the parameter had to be a URL. so I tried using the URL(string) function and using the output as a parameter and that didn't work either.
Any help please?
Thank you. I it helped to look at the network request. I was simply using the wrong syntax to obtain the value inside of the html input tag.
var ln = document.getElementById("LN").value;
returns the real value inside of html input tag given by the user input.
I'm answering my own question because this is a homework assignment.
(Not that I was cheating. Answering this is far from solving the homework)

Is this the correct syntax to send a GET request URL?

TO INSERT values to my table I tried this GET xmlhttprequest object.
Is my syntax correct in the URL? It's not working.
document.getElementById('allsubmit').addEventListener('click',sendPost);
var com = document.getElementById('inputcompany').value;
var cat = document.getElementById('selectCategory').value;
var subcat = document.getElementById('selectsubCategory').value;
var descrip = document.getElementById('textdescription').value;
var exp = document.getElementById('datepicker').value;
function sendPost() {
var xhr = new XMLHttpRequest();
xhr.open('GET',"addingthevacancy.php?company='"+com+"'?category='"+cat+"'?subcategory='"+subcat+"'?description='"+descrip+"'?expdate='"+exp,true);
xhr.onprogress = function() {
//
}
xhr.onload = function() {
console.log("Processed..."+xhr.readystate);
console.log(this.responseText);
}
xhr.send();
}
I don't know what's wrong here.
Several issues:
Parameters must be separated with &, not ?.
URL parameters don't need quotes around them.
Parameters should be encoded using encodeURIComponent().
You need to get the values of the input inside the sendPost() function; your code is setting the variables when the page first loads, not when the user submits.
If the button is a submit button, you need to call e.preventDefault() to override the default submission.
Using GET for requests that make changes on the server is generally not recommended, POST should normally be used for these types of requests. Browsers cache GET requests, so if you really need to do this, you should add a cache-buster parameter (an extra, unused parameter containing a random string or timestamp that changes each time, just to prevent the URL from matching a cached URL).
document.getElementById('allsubmit').addEventListener('click', sendPost);
function sendPost(e) {
e.preventDefault();
var com = encodeURIComponent(document.getElementById('inputcompany').value);
var cat = encodeURIComponent(document.getElementById('selectCategory').value);
var subcat = encodeURIComponent(document.getElementById('selectsubCategory').value);
var descrip = encodeURIComponent(document.getElementById('textdescription').value);
var exp = encodeURIComponent(document.getElementById('datepicker').value);
var xhr = new XMLHttpRequest();
xhr.open('GET', "addingthevacancy.php?company=" + com + "&category='" + cat + "&subcategory=" + subcat + "&description=" + descrip + "&expdate=" + exp, true);
xhr.onprogress = function() {
//
}
xhr.onload = function() {
console.log("Processed..." + xhr.readystate);
console.log(this.responseText);
}
xhr.send();
}

How to set multiple HTTP headers in JavaScript get () method

I have been searching the total Internet from around a week and finally decided to post here. I want to send an HTTP get request to an API with two headers for authentication. These are custom headers and need to be sent at once.
I have tried the following code but it never gives me success. The API returns a JSON file which will have parameters like "title", "description". The URL and headers work fine, when I tried it using hurl.it.
This is the code. Please suggest some answer to solve this problem. And one more thing is, I want to do it using JavaScript only, no jQuery, AJAX, or AngularJS.
var xmlhttp = new XMLHttpRequest();
var url = "https://affiliate- api.flipkart.net/affiliate/offers/v1/dotd/json";
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 &&xmlhttp.status==200) {
var myArr = JSON.parse(xmlhttp.responseText);
function display(arr) {
var i;
var out = " ";
for(i = 0; i < arr.length;i++) {
out += "<p>title:" + arr.dotd[i].title + "<br>description:" + arr.dotd[i].description + "<br></p>";
}
document.getElementById("p1").innerHTML = out;
}
}
else {
alert(xmlhttp.status);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.setRequestHeader("Fk-Affiliate- Token","xxxxxxxxxxxxxxxxx");
xmlhttp.setRequestHeader("Fk-Affiliate-Id","xxxxxxxxx");
xmlhttp.send();

I am trying to implement an AJAX call. What am I doing wrong?

This is my HTML text:
<input type="text" class="resizedsearch" name="searchdb">
<button id="submit" onclick="ajaxCall()">Search!</button>
This is Javascript:
ajaxCall()
{
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost:8080/CSE%205335%20Project%20One/userInfo.php";
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send('searchdb');
function myFunction(response)
{
var obj = JSON.parse(response);
document.getElementById("democity").innerHTML =
obj.city;
document.getElementById("demodes").innerHTML =
obj.description;
document.getElementById("latlon").innerHTML =
obj.latitude + "," + obj.longitude;
}
}
And this is where I am trying to display the response that I am receiving from the PHP file:
<b><font size="24" face="Cambria"><p id="democity"></p></font></b>
<font size="6" face="Cambria"><p id="demodes"></p></font>
</br>
The output of the PHP file is stored in $outp and it is in the JSON format.
Any help appreciated. Thank you.
!!UPDATE!!
function ajaxCall()
{
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost:8080/CSE%205335%20Project%20One/userInfo.php";
xmlhttp.onreadystatechange=function()
{
xmlhttp.open("GET", url, true);
xmlhttp.send('searchdb');
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
myFunction(xmlhttp.responseText);
}
}
}
function myFunction(response)
{
var obj = JSON.parse(response);
document.getElementById("democity").innerHTML =
obj.city;
document.getElementById("demodes").innerHTML =
obj.description;
document.getElementById("latlon").innerHTML =
obj.latitude + "," + obj.longitude;
}
This is how the improvised code looks. Still not working.
Example by FactoryAidan is not going to work as it violates Same Origin Policy (unless you'll run the code in browser console on Google page). Try replacing http://www.google.com with your local address. I tested the code with a little modification and it works, or at least gives alert, so the function is called. Here's it is:
function ajaxCall(){
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost:8080"; /* but make sure the url is accessible and of same origin */
xmlhttp.onload=function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send('searchdb');
}
function myFunction(response){
alert('I made it here');
}
Your code update after my first answer looks like it was done in haste and I think makes the question a little harder. The .open() and .send() methods ended up inside your .onreadystatechange function definition but they need to be outside. Your first one didn't have those placement issues. The code I wrote below has your exact building blocks but with no placement issues so you should be able to follow along with how it matches your example code. I also tested it and it sucessfully sends and receives data back and successfully calls the myFunction() callback function.
Nonetheless, I took your code and rewrote it a bit. If you get an alert('') message when you run it, that means that your xml request worked perfectly. If you don't see an alert('') message. It means your xml request is returning a http 404 error, which means your request URL is bad. Try changing your request URL to something you know won't give you a 404 error, like 'http://www.google.com'. If it works and you get the alert message, then the only problem is that your localhost:8080 url is a bad url.
Also, in your myFunction callback function, javascript treats line-breaks as the end of a line of code. So you must write assignments that use an '=' sign on the same line with no line-breaks. Due to this javascrit principle, you also don't need a semicolon ';' at the end of a single line like you would in PHP script.
Finally, a big cause of errors can be the JSON.parse() call. The data received MUST be a valid json string. So if the URL you call returns anything other than pure json... your myFunction() callback function will break on the JSON.parse() command.
Lastly, if there is an error in your myFunction() callback function, your browser inspector will not report it in a useful way and will instead throw an error that points to your xmlhttp.onreadystatechange=function(){} as being the culprit because that is where the browser thinks the error resides (being the calling function), even though the real error is in your myFunction() callback function. Using my edit of your ajaxCall(){...} code and with a valid url, you can be positive that the ajax call works and any errors you have are in your myFunction() callback function.
Lastly again, You have to be careful in your callback function because there are so many things that could break it. For example, document.getElementById() will cause an error if no html element exists on your web-page with the id you provided. Also, if the JSON you received back from the ajax call is missing any properties you mentioned like (city or latitude) it is likely that the innerHTML will be set to 'undefined'. But some browsers may treat the missing json properties as an error instead of just saying they are 'undefined' when you try to call them.
function ajaxCall(){
var xmlhttp = new XMLHttpRequest();
var url = "http://www.google.com";
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send('searchdb');
}
function myFunction(response){
alert('I made it here')
/*
var obj = JSON.parse(response);
document.getElementById("democity").innerHTML = obj.city
document.getElementById("demodes").innerHTML = obj.description
document.getElementById("latlon").innerHTML = obj.latitude + "," + obj.longitude
*/
}

Tracking the redirection path of URLs in javascript

I am trying to find number of redirections of a requested url in a browser, and if possible want to track the redirected path of that URL through javascript.
For example, if i request 'A' in my browser.assume the redirection flow as A->B->C->D. Means,it gets redirected to 'D'. In this case i need to get three 301 redirect status codes and one 200 ok status code.
I tried the below method in my addon.js(and made an addon to firefox browser).
var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
var StatusValue = req.status;
It is giving 200 ok (I think it is of final url).
Is it possible to get all 301 redirects of a URL through Javascript.
Thanks,
nsIXMLHttpRequest interface has a member channel (accessible to extensions only) of type nsIChannel. You can assign your own callbacks to its notificationCallbacks property and implement nsIChannelEventSync interface to receive redirection events. Something along these lines:
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
var req = new XMLHttpRequest();
req.open('GET', document.location);
var oldNotifications = req.channel.notificationCallbacks;
var oldEventSink = null;
req.channel.notificationCallbacks =
{
QueryInterface: XPCOMUtils.generateQI([
Components.interfaces.nsIInterfaceRequestor,
Components.interfaces.nsIChannelEventSink]),
getInterface: function(iid)
{
// We are only interested in nsIChannelEventSink, return the old callbacks
// for any other interface requests.
if (iid.equals(Ci.nsIChannelEventSink))
{
try {
oldEventSink = oldNotifications.QueryInterface(iid);
} catch(e) {}
return this;
}
if (oldNotifications)
return oldNotifications.QueryInterface(iid);
else
throw Components.results.NS_ERROR_NO_INTERFACE;
},
asyncOnChannelRedirect: function(oldChannel, newChannel, flags, callback)
{
var type = null;
if (flags & Components.interfaces.nsIChannelEventSink.REDIRECT_TEMPORARY)
type = "temporary";
else if (flags & Components.interfaces.nsIChannelEventSink.REDIRECT_PERMANENT)
type = "permanent";
else if (flags & Components.interfaces.nsIChannelEventSink.REDIRECT_INTERNAL)
type = "internal";
Components.utils.reportError("Redirect from " + oldChannel.URI.spec + " " +
"to " + newChannel.URI.spec + " " +
(type ? "(" + type + ")" : ""));
if (oldEventSink)
oldEventSink.asyncOnChannelRedirect(oldChannel, newChannel, flags, callback);
else
callback.onRedirectVerifyCallback(Cr.NS_OK);
}
};
req.send(null);
This code makes sure to always call the old notification callbacks while logging any calls to nsIChannelEventSync.asyncOnChannelRedirect.
For reference: nsIInterfaceRequestor, XPCOMUtils.
thx, the code works, but not as expected: A->B->C->D (channel_1 -> channel_2 -> channel_3 -> channel_4).
In my case it will record a redirect chain of A->B->C->D like:
A->B (channel_1 -> channel_2), than B->C (channel_1 -> channel_2), C->D (channel_1 -> channel_2); where channel_1 & channel_2 are random hash numbers.
So I can not link the chain together. that would be the strategy to capture the chain of events (while the pages redirect using, meta-refresh, javascript, http...)?

Categories