JSON send not being accepted by server API - javascript

I am trying to send a JSON object to a web api, but am having a bit of trouble. Its supposed to take value from an input, check the response first, and if the response is correct, send the data. Here is my JS code:
var form = document.getElementById("inputForm"), master = {}, xhr = new XMLHttpRequest(); //global variables used for checking different parts of the process
form.onsubmit = function (e) {
// stop the regular form submission
e.preventDefault();
// collect the form data while iterating over the inputs
var data = {};
for (var i = 0, ii = form.length; i < ii; ++i) {
var input = form[i];
if (input.name) {
data[input.name] = input.value;
}
master.data = data;
}
// construct an HTTP request
function get(url, callback) {
xhr.open("GET", url);
xhr.onreadystatechange = function() {
if(xhr.readyState === 4 && xhr.status === 200) {
var type = xhr.getResponseHeader("Content-Type");
if (type.indexOf("xml") !== -1 && xhr.responseXML)
callback(xhr.responseXML);
else if (type === "application/json")
callback(JSON.parse(xhr.responseText));
else
callback(xhr.responseText);
}
};
// send the collected data as JSON
console.log(JSON.stringify(master));
xhr.send(JSON.stringify(master));
}
get("http://example.com:12321/data");
};
However, when sending it, I get a HTTP 500 error in the console, and the output in the server itself says:
Processing request on /data
Caught error: <unspecified file>(1): expected object or array
And here is the result of the console.log:
{"data":{"val":"2"}}
I thought I was sending the data correctly, but it isnt recognizing it. The example they gave was of a .json file and that works fine, but my stringified JSON isnt working.
Any help would be greatly appreciated

Related

I can't get a response from the server

I followed some guides on how to send json objects to the server(written using node.js) and it doesn't work, I have no idea what is wrong. I know that my server works fine since I tested it on postman so it's my js code that's the problem, all the tutorials I see follow a similar XMLHttpRequest format.
this is my code
var ing = new Ingredient(name, date, qty, rp);
var url = "http://localhost:8081/addIngredient";
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
//Send the proper header information along with the request
// application/json is sending json format data
xhr.setRequestHeader("Content-type", "application/json");
// Create a state change callback
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// Print received data from server
result.innerHTML = this.responseText;
}
};
// Converting JSON data to string
var data = JSON.stringify(ing);
document.write(data);
// Sending data with the request
xhr.send(data);
I used document.write to check where the code stops working but everything passes (since the document.write prints something), I suspect that there is something wrong/missing from xhr.send(data) but I can't tell what. Finally, nothing gets printed from the callback.
It's better to use onload instead of onreadystatechange
xhr.onload = function() {
if (xhr.status == 200) {
console.log(`Response length = ${xhr.response.length}`);
// store xhr.response here somewhere
}
};

Trying to post to a .txt file fails but performing a get does work

My partner and I are trying to get a domain that I own, communicate with a ios app that is run on objective c to work via http. He is using the code that was provided by this link Sending an HTTP POST request on iOS.
He is able to do a GET to receive the data in my .txt page but when he performs a PUT to try and write to that file so that I can get that data it fails. We are both rather new to http so it is possible that we are missing something. A concern we have is that he doesn't have the privileges to write to this file. Any advice would help, thanks!
Here is the javascript I am using on my side. I added a header to my response to try and resolve the cors issue.
(function () {
window.onload = function () {
httpGetAsync("http://students.washington.edu/bharatis/distances.txt", processData)
//alert("hello inside onload");
document.getElementById("first").innerHTML = leader1;
document.getElementById("second").innerHTML = leader1;
document.getElementById("third").innerHTML = leader1;
//window.onbeforeunload = update;
}
function processData(responseText) {
//alert(responseText);
var txt = "";
var x = responseText.getElementsByTagName('Distance'); // Talk to alex about
for(i = 0; i < x.length; i++) {
txt += x[i].childNodes[0].nodeValue;
}
var result = parseDouble(txt);
alert(result);
}
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.setRequestHeader("Access-Control-Allow-Origin", "*");
xmlHttp.send("response message");
}
})();

Node.js Cannot read property of undefined using JSON data

I'm trying to convert a js script to a node.js script. The JS script works fine, and managed to pull data from this URL and correctly use the information. However, when I try run it on Node.js, I get the error "Cannot read property of 'fixtures' undefined."I've added this package to pull the data, however I'm not sure why it's now throwing an error.
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
//Get Data
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status === 200) {
callback(null, xhr.response);
} else {
callback(status, xhr.response);
}
};
xhr.send();
};
//Use Data
getJSON('http://api.football-data.org/v1/teams/343/fixtures',
function(err, data) {
if (err !== null) {
console.log(" An error has occured.")
} else {
var latest;
for(x = 0; data.fixtures[x].status !== "TIMED"; x++) {
latest = data.fixtures[x].matchday - 1;
}
}};
The error is thrown at the line while(data.fixtures[x].status !== "TIMED"), and the error is
for(x = 0; data.fixtures[x].status !== "TIMED"; x++) {
^
TypeError: Cannot read property 'fixtures' of undefined
Please could you explain to me why JS can see the data and use it fine, but node.js sees the property to be undefined?
Many thanks.
EDIT: Removed legacy while loop that shouldn't have been there.
The reason you're getting that message is because the variable data in your callback is undefined. The reason it is so is that you are passing it that
callback(null, xhr.response); //<-- You should have used responseText
But even that will not solve the issue - it is text not json. So parse it
callback(null, JSON.parse(xhr.responseText));
The response property is part XMLHttpRequest Level 2, but xmlhttprequest only supports 1 at the moment:
Note: This library currently conforms to XMLHttpRequest 1.
For this reason xhr.response will be undefined.
Only xhr.responseText will be set, and this is a string so you would need to add the parsing of json yourself.
if (status === 200) {
try { // use a try block here in case the the response is not parseable
callback(null, JSON.parse(xhr.responseText));
} catch(e) {
callback(e)
}
} else {
callback(status, xhr.response);
}

XMLHttpRequest that is being Aborted

I'm looking over a bit of code that deals with XHR. It looks like the first XHR.send() is being done successfully and then the subsequent one is Aborted before it gets to it's .send()
Quick in dirty:
url = "http://192.168.1.1/cgi-bin/test.cgi";
data = "1235,123,21,1232,12321,432";
myXHR = new Array();
for(var i = 0; i < 2; i++) {
myXHR[i] = new XMLHttpRequest();
myXHR[i].open("POST", url, true);
myXHR[i].onerror = function() {
alert("Error occurred");
};
myXHR[i].onload = function() {
if(myXHR[i].status == 200) {
alert("Yay I worked");
var data = myXHR[i].responseText;
}
};
// do some setting up of XHR headers
myXHR[i].send(data);
myXHR[i] = null;
}
What could be happening that would cause Firebug to show Abort before the second .send() is done?
Try this:
url = "http://192.168.1.1/cgi-bin/test.cgi";
data = "1235,123,21,1232,12321,432";
var myXHR = [];
for(var i = 0; i < 2; i++) {
myXHR[i] = new XMLHttpRequest();
myXHR[i].open("POST", url, true);
myXHR[i].onerror = function() {
alert("Error occurred");
};
myXHR[i].onload = function() {
if(myXHR[i].status == 200) {
alert("Yay I worked");
var data = myXHR[i].responseText;
}
};
// do some setting up of XHR headers
myXHR[i].send(data);
myXHR[i] = null;
}
When I run this code I get TypeError: myXHR[i] is undefined (on the stock firefox 20 install on my mac... what version are you on)?
At any rate, I can see one issue with this (i.e. myXHR[i] will be undefined...) that might also apply to you, in particular with:
myXHR[i].onload = function() {
if(myXHR[i].status == 200) {
alert("Yay I worked");
var data = myXHR[i].responseText;
}
};
Because this is triggered asynchronously i will have been incremented to 2, which is of course going to be outside the bounds of the two element myXHR array. Have you tried closing over the value of i, like so:
myXHR[i].onload = (function(i) {
return function() {
if(myXHR[i].status == 200) {
alert("Yay I worked");
var data = myXHR[i].responseText;
}
}
})(i);
Because once I correctly save that i value in that function body this code will succeed for both calls.
I know this isn't the exact issue you're having, but I think it will be an issue regardless so you may as well give it a go right? It's not as though there have been a huge number of other answers unfortunately.
hope this helps..
Found out what was happening.
The XHR was being aborted because there was no return value from the webserver that the request was being sent to. The web server is a custom based one that we seem to be using the someone changed the code so that it wasn't sending a 200 Success OK even if the data sent to it had no data coming back.
All good now. Thanks for the help.

Sending Username and password to web service using json

Hi i would like to create a login page in html 5, but in order to login i need to send the username and password to a web service, the web service is already created and it will return a value 0 if flase and any other number if true. I can only use javascript and json. Can anyone help me out to understand json as i know almost nothing about it. How would i send the username and password using json and javascript?
var form;
form.onsubmit = function (e) {
// stop the regular form submission
e.preventDefault();
// collect the form data while iterating over the inputs
var data = {};
for (var i = 0, ii = form.length; i < ii; ++i) {
var input = form[i];
if (input.name) {
data[input.name] = input.value;
}
}
// construct an HTTP request
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action, true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
// send the collected data as JSON
xhr.send(JSON.stringify(data));
xhr.onloadend = function () {
// done
};
};

Categories

Resources