xmlHTTPrequest status code 400 - javascript

i want to get a response from my webserver. So i send a GET command to my api path "auftraege", but at xhht.send is an error "status code 400". The server has a controller to listen at "auftraege" and responses only "hello".
var xmlDoc = null;
function loadXML() {
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject('Microsoft.XMLDOM');
}
xhttp.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 400) {
updateXML(this);
}
};
xhttp.open("GET", "auftraege", true);
xhttp.send('grant_type=client_credentials');
}
function updateXML(xml) {
xmlDoc = xml.responseText;
document.getElementById("auftraege").innerHTML = xmlDoc;
setTimeout(updateTime, 5000);
}
window.addEventListener("load", loadXML);
That is the controller:
[RestController(InstanceCreationType.Singleton)]
public class AuftraegeController {
[UriFormat("/auftraege")]
public IGetResponse GetWithSimpleParameters() {
return new GetResponse( GetResponse.ResponseStatus.OK, "Hello");
}
That is the webserver
private HttpServer _httpServer;
public async Task InitializeWebServer()
{
var restRouteHandler = new RestRouteHandler();
restRouteHandler.RegisterController<AuftraegeController>();
var configuration = new HttpServerConfiguration()
.ListenOnPort(80)
//.RegisterRoute("api", restRouteHandler)
.RegisterRoute("/auftraege", restRouteHandler)
.RegisterRoute(new StaticFileRouteHandler(#"Web"))
.EnableCors();
var httpServer = new HttpServer(configuration);
_httpServer = httpServer;
await httpServer.StartServerAsync();

Related

Javascript GET request after POST request

I have a page that uses a function for getting some data, with a GET xhttp request, from a database (get_worktime_list()).
On the same page, I can add some data to the database with a form using a POST xhttp request and after a success (saved in the response) I will get the content included the new line from the database with the same function get_worktime_list().
The problem is that when getworktime is called after the POST request, get_worktime_list() makes another POST request instead of a GET. why???
function http_request(post_data, end_point, type)
{
console.log("HTTP");
var res = 0;
//var data = "data=0&username="+stored_token.username+"&token="+stored_token.token;
var data = "data=0&"+post_data;
console.log(data);
// Check if is valid token/username from database
const url = "http://192.168.1.188:5000/services/"+end_point;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
res = JSON.parse(xhttp.responseText);
}
};
if (type == "GET")
{
console.log(url+"?"+post_data);
xhttp.open("GET", url+"?"+post_data, false);
}
else
{
console.log("Data: "+data);
xhttp.open("POST", url, false);
}
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhttp.send(data);
xhttp.abort();
return res;
}
This add data to DB
function addworktime(username,token)
{
console.log("Aggiungo ore");
var date = document.getElementById("data").value;
var type = document.getElementById("turno").value;
var pay = document.getElementById("paga").value;
var emp = document.getElementById("dipendente").value;
var ore = document.getElementById("num_ore").value;
var data = "username="+username+"&token="+token+"&day="+date+"&turn_type="+type+"&pay="+pay+"&emp="+emp+"&ore="+ore;
var res = http_request(data,"admin/dipendenti/addtime.php","");
//console.log(res);
if (res.insert_ok == 1)
{
display_time_table(0,0,null);
} else {
console.log(res);
}
}
This function makes a GET request when a page load and a POST request when called by addworktime()
function display_time_table(from,to,cf)
{
let time_list_table = document.getElementById("list-container");
var time_list = get_worktime_list(saved_data.username,saved_data.token,from,to,cf);
let time_table = generate_time_list_table(time_list);
time_list_table.innerHTML = time_table;
}
function get_worktime_list(username,token,date_from,date_to,cf)
{
var data = "username="+username+"&token="+token;
if (cf != "" || cf != null)
{
data = data+ "&dipendente="+cf;
}
if (date_from != 0)
{
data = data +"&date_from="+date_from;
}
if (date_to != 0)
{
data = data + "&date_end="+date_to;
}
var time_list = http_request(data,"admin/dipendenti/getworktime.php", "GET");
return time_list;
}
The server can only accept GET requests for that API and obviously, I get a parse error parsing the JSON response.
Thanks for help

How to add Node.js result in my HTML project?

this is my project: http://cryptotipsitalia.sytes.net/.
I want add Ethereum value down to "Valore BTC" with Node.js: https://www.npmjs.com/package/crypto-price.
How can I add it?
That's my code:
function getValueBTC() { <!-- chiamata API --> /
var xmlhttp = new XMLHttpRequest();
var url = "https://api.coindesk.com/v1/bpi/currentprice.json";
var output;
console.log(url);
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
output = this.responseText;
var obj = JSON.parse(output);
var rightValue = (obj.bpi.EUR.rate).substring(0,obj.bpi.EUR.rate.length-2); /* eliminazione ultime due cifre */
document.getElementById("cellaValoreBTC").innerHTML= obj.bpi.EUR.symbol + " " + rightValue;
}
};
xmlhttp.open("GET", url, true);
xmlhttp.setRequestHeader("Content-type", "text/plain");
xmlhttp.send();
}
let price = require('crypto-price');
price.getCryptoPrice('EUR', 'ETH').then(obj => {
console.log(obj.price); // It will print ETH rate per BTC
document.getElementById("cellaValoreETH").innerHTML = obj.price;
}).catch(err => {
console.log(err);
});
table><tr><td width="75%">VALORE BTC:</td></tr><tr id="cellaValoreBTC" width="75%"></tr><tr><td width="75%">VALORE ETH:</td></tr><tr id="cellaValoreETH" width="75%"></table>
Why "document.getElementById("cellaValoreBTC").innerHTML = obj.price;" doesnt' work?
How can I add obj.price in my HTML code?
Thanks

Get JSON from Web Service Using JavaScript

I get this error when I click the button in HTML to use my JavaScript.
myapp.azurewebsites.net/:1 Uncaught SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
JS:
function ajaxFunction() {
console.log("ajaxFunction()");
var ajaxRequest;
try {
ajaxRequest = new XMLHttpRequest();
} catch(e) {
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
alert("Broken");
return false;
}
}
}
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
var form = document.getElementById("myform");
var titleParagraph = document.getElementById("home_title");
titleParagraph.innerHTML = ajaxRequest.responseText;
form.style.display = "none";
}
}
var value1 = document.getElementById("field1").value;
var value2 = document.getElementById("field2").value;
var url = "https://webapp.azurewebsites.net/users/" + value1 + "/" + value2;
console.log(url);
// Call sign in web service
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
var jsonResponse = JSON.parse(ajaxRequest.responseText);
console.log("RESPONSE:");
console.log(jsonResponse);
}
This JSON is what I get when I go to https://webapp.azurewebsites.net/users/value1/value2
[{"ID":1,"UserName":"username","FirstName":"first","LastName":"last","email":"example#example.com"}]
ajaxRequest.open("GET", url, false);
Third parameter says if the request is asynchronous or not. So by looking at your code it should be synchronous.

Trouble with having global JavaScript variables updated

I am trying to get a XML document sorted and decided to go for the "sort via XSLT" approach.
However, I am having trouble updating my two global variables that should contain the content of the XML and XSLT files and I can't really figure out why.
Up until now I never had this kind of problem and global variables used to work... I also didn't declare them inside the functions, but used the global name instead and also tried using window.variable, but to no avail.
Does anyone have an idea why the code doesn't update the global variable?
best regards,
daZza
<script type="text/javascript">
var xml = "";
var xsl = "";
function callSort()
{
loadSortXML();
loadSortXSLT();
sortXML();
}
function loadSortXML()
{
var xmlHttp = null;
var xmlData;
var xmlFile = "data/LessonsLearned.xml";
if (typeof XMLHttpRequest != 'undefined')
{
xmlHttp = new XMLHttpRequest();
}
if (!xmlHttp)
{
try
{
xmlHttp = new ActiveXObject("Msxm12.XMLHTTP");
}
catch(e)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP")
}
catch(e)
{
xmlHttp = null;
}
}
}
if (xmlHttp)
{
var url = xmlFile;
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4)
{
xml = xmlHttp.responseXML;
}
}
xmlHttp.send();
}
}
function loadSortXSLT()
{
var xmlHttp = null;
var xmlData;
var xmlFile = "data/xslt.xml";
if (typeof XMLHttpRequest != 'undefined')
{
xmlHttp = new XMLHttpRequest();
}
if (!xmlHttp)
{
try
{
xmlHttp = new ActiveXObject("Msxm12.XMLHTTP");
}
catch(e)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP")
}
catch(e)
{
xmlHttp = null;
}
}
}
if (xmlHttp)
{
var url = xmlFile;
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4)
{
xsl = xmlHttp.responseXML;
}
}
xmlHttp.send();
}
}
function sortXML()
{
console.log("XML " + xml);
console.log("XSL "+ xsl);
var parser = new DOMParser();
var domToBeTransformed = parser.parseFromString(xml, "text/xml");
var xslt = parser.parseFromString(xsl, "text/xml");
var processor = new XSLTProcessor();
processor.importStylesheet(xslt);
var newDocument = processor.transformToDocument(domToBeTransformed);
var serializer = new XMLSerializer();
var newDocumentXml = serializer.serializeToString(newDocument);
alert(newDocumentXml);
}
</script>

Javascript Functions Confusing AJAX Responses from CGI Request/Response

I have 3 Javascript functions called from the body onload in the HTML page.
Each Javascript function is contained in it's own Javascript file. Each Javascript file corresponds to another CGI script on the server.
The bodyonload.js looks like:
function bodyOnload() {
getElementsA();
getElementsB();
getElementsC();
}
Each getElements function simply calls a CGI script to get the contents for 3 different selectboxes.
The problem is that as all 3 functions are called asynchronously the select boxes are getting the wrong results. It's almost like the 3 functions are stepping on each other and putting the CGI responses in the wrong selectbox. I know the CGI responses are correct. This works fine if I serially call each function from the others. Like calling the 2nd function from the first and the 3rd function from the second. The asynchronous nature of them running at the same time seems to cause the problem.
This is the general code for each javascript file that contains the getElements functions.
function getElementsA() {
strURL = "http://test.com/scriptA.cgi";
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
fillselectboxA(self.xmlHttpReq.responseText);
}
}
self.xmlHttpReq.send();
}
function fillselectboxA(str)
{
document.getElementById("selectBoxA").length=0;
var results = new Array();
results = str.split(/\n/);
var size = results.length;
var select = document.getElementById("selectBoxA");
for (x=0;x<size;x++)
{
var element = results[x];
select.options.add(new Option(element, x))
}
}
-------------------
function getElementsB() {
strURL = "http://test.com/scriptB.cgi";
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form- urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
fillselectboxB(self.xmlHttpReq.responseText);
}
}
self.xmlHttpReq.send();
}
function fillselectboxB(str)
{
document.getElementById("selectBoxB").length=0;
var results = new Array();
results = str.split(/\n/);
var size = results.length;
var select = document.getElementById("selectBoxB");
for (x=0;x<size;x++)
{
var element = results[x];
select.options.add(new Option(element, x))
}
}
------------------------
function getElementsC() {
strURL = "http://test.com/scriptC.cgi";
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
fillselectboxC(self.xmlHttpReq.responseText);
}
}
self.xmlHttpReq.send();
}
function fillselectboxC(str)
{
document.getElementById("selectBoxC").length=0;
var results = new Array();
results = str.split(/\n/);
var size = results.length;
var select = document.getElementById("selectBoxC");
for (x=0;x<size;x++)
{
var element = results[x];
select.options.add(new Option(element, x))
}
}
It's almost like the 3 functions are stepping on each other
That's exactly what's happening, you're overwriting the onreadystatechange handler set on getElementsA when you call getElementsB, and then again when you call getElementsC. That's because this and self are the global object in all three functions (assuming they're all similar to getElementsA).
You can circumvent that by changing your function calls to object instantiation:
function bodyOnload() {
new getElementsA();
new getElementsB();
new getElementsC();
}

Categories