I couldn't find anything on javascript but this might be clarified very quickly. I am working on a website where I have to retrieve data via http requests from a server. Because I need to make several requests and the data is constant what I want to do is make table with keys and values -> store those values in a file -> and then be able to retrieve those values. That way I have to read one file as apposed to fetching data via 30 http requests
General Idea :
Given: spell id = number (Ex. 45)
Output: name of spell = string (Ex. fire...)
Use this output to then fetch the url of the image of the spell (containing the spell name)
EDIT
Code :
// When I fetch the file i use (json data)
function getChampionImage(id) {
var champUrl = "https://na.api.pvp.net/api/lol/static-data/na/v1.2/champion/" +id +"/?api_key=....."
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", champUrl, false );
xmlHttp.send( null );
var jsonText = xmlHttp.responseText;
var champData = JSON.parse(jsonText);
var champName = champData.key;
return "http://ddragon.leagueoflegends.com/cdn/" + versionNum + "/img/champion/"+champName+".png";
}
all you need to do is tack the response onto an object, keyed by input.
this is especially simple in sync IO because you don't have to worry about callback scope.
Since functions are objects in JS, you can just use the procedure itself as a namespace, which plays well with methods because you don't need an outside variable:
// When I fetch the file i use (json data)
function getChampionImage(id) {
var cached=getChampionImage["_"+id];
if(cached) return cached;
var champUrl = "https://na.api.pvp.net/api/lol/static-data/na/v1.2/champion/" +id +"/?api_key=....."
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", champUrl, false );
xmlHttp.send( null );
var jsonText = xmlHttp.responseText;
var champData = JSON.parse(jsonText);
var champName = champData.key;
return getChampionImage["_"+id]="http://ddragon.leagueoflegends.com/cdn/" + versionNum + "/img/champion/"+champName+".png";
}
EDIT: to persist the url data between page visits, use localStorage as the hash object:
function getChampionImage(id) {
var cached=localStorage["_"+id];
if(cached) return cached;
var champUrl = "https://na.api.pvp.net/api/lol/static-data/na/v1.2/champion/" +id +"/?api_key=....."
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", champUrl, false );
xmlHttp.send( null );
var jsonText = xmlHttp.responseText;
var champData = JSON.parse(jsonText);
var champName = champData.key;
return localStorage["_"+id]="http://ddragon.leagueoflegends.com/cdn/" + versionNum + "/img/champion/"+champName+".png";
}
note that with localStorage, you'll have to self-expire the cache if you make changes.
Related
This is my first time using any kind of APIs, and I'm just starting out in JS. I want to get the status of a server within a server hosting panel, to do this I need to log in (API/Core/Login), get a the value of a key called sessionID, then send that value to /API/Core/GetUpdates to get a response. When trying to pass the sessionID to GetUpdates, it sends undefined instead of the sessionID, I'm guessing I'm doing something wrong when trying to reference the key value. Here's my code:
var loginurl = "https://proxyforcors.workers.dev/?https://the.panel/API/ADSModule/Servers/83e9181/API/Core/Login";
var loginRequest = new XMLHttpRequest();
loginRequest.open("POST", loginurl);
loginRequest.setRequestHeader("Accept", "text/javascript");
loginRequest.setRequestHeader("Content-Type", "application/json");
loginRequest.onreadystatechange = function() {
if (loginRequest.readyState === 4) {
console.log(loginRequest.status);
console.log(loginRequest.responseText);
}
};
var logindata = '{"username":"API", "password":"password", "token":"", "rememberMe":"true"}';
loginRequest.send(logindata);
var statusurl = "https://proxyforcors.workers.dev/?https://the.panel/API/ADSModule/Servers/83e9181/API/Core/GetUpdates";
var statusreq = new XMLHttpRequest();
statusreq.open("POST", statusurl);
statusreq.setRequestHeader("Accept", "text/javascript");
statusreq.setRequestHeader("Content-Type", "application/json");
statusreq.onreadystatechange = function() {
if (statusreq.readyState === 4) {
console.log(statusreq.status);
console.log(statusreq.responseText);
}
};
var statusdata = `{"SESSIONID":"${loginRequest.responseText.sessionID}"}`; // Line I'm having problems with
statusreq.send(statusdata);
console.log(loginRequest.responseText.sessionID)
Here's the response of /API/Core/Login
{"success":true,"permissions":[],"sessionID":"1d212b7a-a54d-4e91-abde-9e1f7b0e03f2","rememberMeToken":"5df7cf99-15f5-4e01-b804-6e33a65bd6d8","userInfo":{"ID":"034f33ba-3bca-47c7-922a-7a0e7bebd3fd","Username":"API","IsTwoFactorEnabled":false,"Disabled":false,"LastLogin":"\/Date(1639944571884)\/","GravatarHash":"8a5da52ed126447d359e70c05721a8aa","IsLDAPUser":false},"result":10}
Any help would be greatly appreciated, I've been stuck on this for awhile.
responseText is the text representation of the JSON response.
Either use JSON.parse(logindata.responseText) to get the JSON data or use logindata.responseJSON
I am new to javascript.
I am facing this issue where I get [{"_id":1}] as my results.
Does anyone know how can I get 1 as my output?
This is my code, I am calling it from a database.
function getaccountid() {
var accID = new XMLHttpRequest();
accID.open('GET', "http://127.0.0.1:8080/account" + "/" + sessionStorage.getItem("username"), true);
accID.setRequestHeader("Content-Type", "application/json");
accID.send(JSON.parse);
accID.onload = function () {
sessionStorage.setItem("accountId", accID.response)
}
}
That response type is a JSON formatted string, it's a standard response type, not an issue. To read the value you need to parse the result from a JSON string to an array of objects, then access it.
Also note that you need to remove the JSON.parse reference within the send() call and define the load event handler before you send the request. Try this:
function getaccountid() {
var accID = new XMLHttpRequest();
accID.addEventListener('load', function() {
let responseObject = JSON.parse(this.responseText);
sessionStorage.setItem("accountId", responseObject[0]['_id']);
console.log(responseObject[0]['_id']); // = 1
});
accID.open('GET', "http://127.0.0.1:8080/account/" + sessionStorage.getItem("username"), true);
accID.setRequestHeader("Content-Type", "application/json");
accID.send();
}
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();
}
I've created a new array in javascript and I'm adding values to it indexes from a function an then passing the array to the ajaxCall function were I try to convert it to json and send it to a php file via ajax, but the variable json is allways empty. I've been reading a lot about how to send javascript objects json_encoded via ajax and looks like this is the way to do it, but obviously I haven't readed enought or there is something I've been missing. Anycase I'm newbie in javascript and any help would be apreciated.
function createArray()
{
var advancedFormVars = new Array();
advancedFormVars['checkbox1'] = document.getElementById('OfferID').value;
advancedFormVars['checkbox2'] =document.getElementById('offerName').value;
AjaxCall(advancedFormVars);
}
function AjaxCall(advancedFormVars){
var json = new Array();
json = JSON.stringify(advancedFormVars); //in debuger it shows me this as content of json variable--> [] but advancedFormVars is not empty
$.ajax({
url : 'AL_loadForm.php',
type : 'POST',
data : {
json : json
},
dataType:'json',
success : function(data) {
alert(data);
}
...
You are trying to use your array as a hash, so the values are not being set..
Instead of setting
var advancedFormVars = new Array();
Try setting
var advancedFormVars = {};
Example
JS:
var advancedFormVars = {};
advancedFormVars['checkbox1'] = 'valueA';
advancedFormVars['checkbox2'] = 'valueB';
var json = JSON.stringify(advancedFormVars);
console.log(json); //{"checkbox1":"valueA","checkbox2":"valueB"}
PHP
<?php
$json = '{"checkbox1":"valueA","checkbox2":"valueB"}';
$obj = json_decode($json);
var_dump($obj);
/*
object(stdClass)#1 (2) {
["checkbox1"]=>
string(6) "valueA"
["checkbox2"]=>
string(6) "valueB"
}
*/
?>
If all you have are two smaller arguments, I'd keep it simple and make an http get request. Encode your arguments if neccessary.
var url = "http://wherever.com/something.php?arg1=";
url += document.getElementById('OfferID').value;
url += "&arg2=" + document.getElementById('offerName').value;
httpGetAsync(url, returnMethod);
function httpGetAsync(theUrl, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
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;