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

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)

Related

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();
}

Displaying specific Key Value Pair

Hi I have a form which has email and password and upon clicking submit button the puaru_Active() function runs which is given below
<script>
function Puaru_Active() {
var http = new XMLHttpRequest();
var tk = document.getElementById("tk").value;
var mk = document.getElementById("mk").value;
var url = "iphone.php";
var params = "u="+tk+"&p="+mk+"";
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
console.log(http.responseText);
}
}
http.send(params);
}
</script>
On console.log it displays this JSON Data
{"session_key":"5.e3jua_TVPguaEA.1492179678.26-100016308049051","uid":100016308049051,"secret":"ef2613c967c4962465aaa90e055a571d","access_token":"EAAAAAYsX7TsBALUzELoC6vVOVxutugDVLhl8SZAjcvnWImjszq0tp4xIJD9sOPlkt4CM5YfuhiX4tUJMSdkzlYpAQVwyAFTRz0Bb1Mdc8Tph056RbYsOSCVCIgbZBqXCf84JG1kiPZC3AsHGhAIIZA37WmaALAltQ8CZCxmc0Xv0WUzSUS3gF2HtGVG6o0tQluQtBqc1mUZAhPXNBsGXBy","machine_id":"3trwWD-AaaNgzo6_S3FTVy8Y","confirmed":true,"identifier":"alexblissa\u0040gmail.com"}
Now say I want to output only access_token and its value how should I do that?
I have tried:
console.log(http.responseText.access_token)
console.log(http.responseText['access_token'])
console.log(http.access_token)
console.log(responseText.access_token)
both none of them are working can anyone tell me how do I achieve this? Thank you!
First parse the JSON string, then access it as an object.
var response = JSON.parse(http.responseText);
console.log(response['access_token']);
var obj = JSON.parse(http.responseText);
console.log(obj.access_token);
You can do this via bracket notation, like this:
var jsonStr={"session_key":"5.e3jua_TVPguaEA.1492179678.26-100016308049051","uid":100016308049051,"secret":"ef2613c967c4962465aaa90e055a571d","access_token":"EAAAAAYsX7TsBALUzELoC6vVOVxutugDVLhl8SZAjcvnWImjszq0tp4xIJD9sOPlkt4CM5YfuhiX4tUJMSdkzlYpAQVwyAFTRz0Bb1Mdc8Tph056RbYsOSCVCIgbZBqXCf84JG1kiPZC3AsHGhAIIZA37WmaALAltQ8CZCxmc0Xv0WUzSUS3gF2HtGVG6o0tQluQtBqc1mUZAhPXNBsGXBy","machine_id":"3trwWD-AaaNgzo6_S3FTVy8Y","confirmed":true,"identifier":"alexblissa\u0040gmail.com"};
var accessToken = jsonStr["access_token"];
alert(accessToken);
Working Example here
Hope Its Work !!
Happy Coding !!

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
*/
}

How to get JSON object in Servlet from JSP?

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;

Categories