How to stop number being converted to string in xmlHttpRequest? - javascript

How do I stop a number being converted to a string when adding an element to a JSON file on a server using xmlHttpRequest?
The following code updates my .json file with the element but the number (var importance) is a string by the time it arrives at the server... and I can't work out why.
This is where I format my input data and create the xmlHttpRequest.. (script.js):
btnSubmit.onclick = submitTask;
function submitTask() {
inputTask = document.querySelector('#task');
inputImportance = document.querySelector('#importance');
var task = inputTask.value;
var importance = Number(inputImportance.value);
console.log("User Input: ",task, importance);
//Setup XML HTTP Request
var xhr = new XMLHttpRequest();
xhr.open('POST', api_url_add +'/'+ task +'/'+ importance, true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
//Receive response from server.
xhr.onload = function() {
response = JSON.parse(xhr.response);
console.log(response);
}
xhr.send();
}
And this is the server side code (server.js):
// ADD task to the list (task, importance)
app.post('/add/:task/:importance?', addTask);
function addTask(request, response) {
var data = request.params;
console.log('Submitted to server:','\n', data);
var task = data.task;
var importance = Number(data.importance);
var reply;
if (!importance) {
var reply = {
msg: "Importance value is required."
}
} else {
var element = data;
tasks['taskList'].push(element);
fs.writeFile('tasks.json', JSON.stringify(tasks, null, 2), function(err){
console.log('all done')
})
response.send(reply);
}
}
Thanks for all of your help.

Related

I am trying to make a post request using javascript to my fast api app. But it is giving error INFO. 422 Unprocessable Entity

// variables for getting Original URL
const form2 = document.getElementById("form2");
const resultContainer2 = document.querySelector(".result__container2");
const longUrl = document.querySelector(".longurl");
//for decoding the url (Retrieving Original URL)
form2.addEventListener("submit", (e) => {
e.preventDefault();
var formData = new FormData();
formData.append("shortUrl", e.target.shortUrl.value);
formData.append("customCode", e.target.shortUrl.value);
let data = {}
for(let pair of formData.entries()) {
data[pair[0]] = pair[1]
}
console.log(data)
let xhr = new XMLHttpRequest();
xhr.open("POST", "/api/v2/original", true);
// Set the request header
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function() {
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
console.log("Done")
}
}
//Displaying the Original long URL
xhr.onload = function () {
const response = JSON.parse(this.responseText);
console.log(this.status);
console.log(response);
if(this.status ==200) {
resultContainer2.style.display = "flex";
longUrl.innerHTML = `ORIGINAL LONG URL :- <a href=${response.longUrl}>${response.longUrl}</a>`
}
else {
alert(`An error occurred, ${response.detail}`)
}
};
//using JSON for transfering data in between, as per task requirement (JSON Object to JSON string)
xhr.send(JSON.stringify(data));
})

URL.createObjectURL(blob);

I am creating a PDF and opening in a new browser. My issue is word 'blob:' is getting appended to the URL
blob:http://localhost:3000/a0b859c9-57a0-40b7-a60f-9d2a72ab3c14
and I would like to be 'http://localhost:3000/a0b859c9-57a0-40b7-a60f-9d2a72ab3c14'
Is there a way I could achieve this ? My code is below
const blob = new Blob([response.data], {type : 'application/pdf'});
var pdfFileUrl = URL.createObjectURL(blob);
window.open(pdfFileUrl);
URL.revokeObjectURL(pdfFileUrl);
update:
I tried below code as well. It also gives the same results.
''
const xhr = new XMLHttpRequest();
//Send the proper header information along with the request
// listen for `onload` event
xhr.onload = () => {
// process response
if (xhr.status == 200) {
// parse JSON data
// console.log( "Response Received")
// var pdfurl = URL.createObjectURL(xhr.response) ;
console.log(xhr.response)
window.open(URL.createObjectURL(xhr.response));
} else {
console.log(" In Error block")
console.error('Error!');
}
};
// create a `GET` request
xhr.open('POST', url);
xhr.responseType = 'blob'
xhr.setRequestHeader('Content-Type', 'application/json');
// send request
xhr.send(JSON.stringify(payload));''

passing vars from js to node

I have a button that when pressed I want it to send an array of objects (logs) from that js file to a node js file so I can then output a JSON file. I've tried AJAX with this tutorial and this one but I still don't understand how to pass a variable between js and node.
const done_but = document.getElementById("done");
var logs = []
var xhttp = new XMLHttpRequest();
document.getElementById('r2').checked = true;
done_but.onclick = function() {
const student = document.getElementById("student-drop").value;
const face = document.querySelector('input[name="faceses"]:checked').value;
const time = new Date();
logs.push([{
student: student,
face: face,
time: time.toUTCString()
}]);
xhttp.open("POST", "file:///(file path)/index.html");
xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
xhttp.send(logs);
console.log(logs);
};
I figured out that if you put your styles and local js into your HTML file you can write that to the screen then take any input from the local js. To give the server data you can
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://localhost:8000");
xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
xhttp.send(YourVar);
Here is my node code that takes the input and writes the screen.
var http = require('http');
var fs = require('fs');
http.createServer(function(req, res) {
fs.readFile('index.html', function(err, data) {
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.write(data);
res.end();
if (req.method === 'POST') {
let body = '';
req.on('data', chunk => {
body += chunk.toString(); // convert Buffer to string
});
req.on('end', () => {
console.log(body);
console.log("");
res.end('ok');
});
}
});
}).listen(8000);
Helpful links:How to send JSON dataHow to send dataHandling requests

Login using Javascript and REST

I made a REST service, which will return a String "hej" if the log in is true.
I have tested in Java with a rest client and it works fine, but pretty new to javascript and need some help.
I'm using this function
function UserAction() {
console.log(User());
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "http://localhost:8080/Footballmanagerrestservice/webresources/login");
xhttp.setRequestHeader("login", User());
xhttp.responseType = 'text';
xhttp.onreadystatechange = function () {
console.log('DONE', xhttp.readyState);
if (xhttp.readyState == 4) {;
// handle response
var response = xhttp.responseText;
console.log(response);
if (response == "hej") {
var url = "http://localhost:8080/FM3/spil2.jsp";
window.location.href = url;
}
}
};
// send the request *after* the callback is defined
xhttp.send();
return false;
}
function User() {
username = document.getElementById("username").toString();
username = document.getElementById("password").toString();
var UserAndPass = "?username=" + username + "&password=" + password;
return UserAndPass;
}
I show you the client i have i Java, maybe you can see why it's not working.
public static void main(String[] args) {
Client client = ClientBuilder.newClient();
String root="http://localhost:8080/Footballmanagerrestservice/webresources/";
String functionPath="login";
String parameters="?username=s153518&password=holger";
Response res = client.target(root+functionPath+parameters)
.request(MediaType.APPLICATION_JSON).get();
String svar = res.readEntity(String.class);
System.out.println(svar);
}
first part of the code looks ok, the following instead must be handled inside a function because is intrinsically asynchronous
var response = JSON.parse(xhttp.responseText);
console.log(response);
if (response.toString() == "hej") {
var url = "http://localhost:8080/FM3/spil2.jsp";
window.location.href = url
}
return false;
doc: https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/onreadystatechange
essentially you're trying to handle the response as a syncrhonous call, but it's not, the response it's not immediatly avaiable, for this reason you have to register a callback (from the doc must be attached to the field onreadystatechange) that will be triggered by javascript as soon as the server response is available.
try to change it like so:
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4) {
// handle response
var response = JSON.parse(xhttp.responseText);
console.log(response);
if (response.toString() == "hej") {
var url = "http://localhost:8080/FM3/spil2.jsp";
window.location.href = url
}
}
}
xhr.send();

handling csv response in backbonejs

I am posting some data to server through Backbone.js and server sends a csv file as response. As Backbone.js handles only json format can some body tell me how to handle this case, so that i would be able to download the csv file gracefully.
object = {};
object.c1 = formObj.c1
hash = {
success: function(model, response, options) {
},
error: function(model, response, options) {
return console.log(response);
}
};
model = new P.models.mine(object);
model.doSomething(object, hash);
It always comes to error part.
The ideal way to handle this would be to change your back end code to return JSON, or create another route that returns JSON. Since you are asking this question I'm assuming that isn't an option for you.
Basically you are going to have to parse the CSV on the client side:
https://stackoverflow.com/a/1293163/944006 - Should get you started.
If you are asking to download a csv file, then just pointing the browser at the location should prompt the user for download. You cannot prompt a file download through ajax(for good reason), but there are ways to tiptoe around this limitation:
https://stackoverflow.com/a/9970672/944006
You could also use plain javascript rather than Backbone.js. Believe me this is the best way.
Here is some code:
var xhr = new XMLHttpRequest();
xhr.open('POST', Urls.download, true);
xhr.responseType = 'blob';
xhr.setRequestHeader("Authorization", "Bearer " + access_token);
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
xhr.onload = function (e) {
if (this.status == 200) {
var blob = new Blob([this.response], { type: 'application/vnd.ms-excel' });
var downloadUrl = URL.createObjectURL(blob);
var a = document.createElement("a");
a.id = "a" + new Date().getTime();
a.setAttribute("data-bypass", "");
a.href = downloadUrl;
a.download = "list_" + new Date().getTime() + ".xlsx";
document.body.appendChild(a);
a.click();
} else {
alert('Unable to download excel.')
}
};
xhr.send(JSON.stringify(this.obj));

Categories

Resources