Javascript not including formdata in request - javascript

I'm writing an API. I can successfully send data to it in postman by including it in body > form data. However, this code does not send anything as form-data!
addGuild = function () {
req = new XMLHttpRequest();
req.open("GET", "https://gralyn.app/api/server/add/" + window.guild)
formdata = new FormData()
formdata.append('prefix', document.getElementById("install-prefix").value);
req.setRequestHeader("token", this.localStorage.getItem("token"))
req.onreadystatechange = function () {
if (this.readyState == 4) {
if (this.status == 200) {
alert("Success!")
} else {
console.log("ERROR: " + this.status)
openModal("error")
}
}
}
req.send(formdata)
}
The API does not receive a prefix as formdata! I am accessing the prefix in flask via request.form['prefix']

Figured it out, javascript wont allow form data in a GET request.

Related

Read response from HttpRequest in JavaScript

First, you can ignore that this is sending credentials in an unsafe manner. I'm supposed to handle that after.
My problem is with reading the 'response' or 'responseText' from a HttpRequest to an API. I can see in the console the request is succesful and the response I want is there, but I am not able to retrieve it. I must be missing something basic probably.
This is the response as I can see in the console:
Chrome console
I can see the "web.html" that I want to retrieve and also the status 200. But the console log is empty. This is how I am trying to do this.
const request = new XMLHttpRequest();
request.open('POST', 'https://someurl.net/api/user/login');
const form = document.getElementById('login')
form.addEventListener('submit', callbackFunction);
function callbackFunction(event) {
event.preventDefault();
request.setRequestHeader('Content-Type', 'application/json;charset=UTF-8')
request.send(JSON.stringify(formJson(event)));
console.log(request)
console.log("Status: " + request.status);
console.log("Response: " + request.response);
console.log("ResponseText: " + request.responseText);
};
function formJson(event) {
const credentialsDto = {};
const myFormData = new FormData(event.target);
console.log(myFormData);
myFormData.forEach((value, key) => (credentialsDto[key] = value));
return credentialsDto;
}
For some more details, this is calling my Api in .NET which returns 401 Unauthorized if the credentials are wrong, and 200 OK with a string as in Ok("web.html") if the credentials are correct.
Thank you.
I tried printing the request and trying with all its attributes I could think of. I can see the request is working and the server is sending the response I want, but I am clueless as how to retrieve it properly.
I also tried this thinking that the response might be asynchronous but it didn't work:
while (true)
{
if (request.readyState == 1)
{
console.log("Status: " + request.status);
console.log("Response: " + request.response);
console.log("ResponseText: " + request.responseText);
break;
}
}
The console is empty because the readyState property state 1 merely means that the connection with the server is established.
Furthermore, the XMLHttpRequest object you print to the console is updated immediately when the http-response file is received, which gives the false assumption that it can't be accessed.
This is more or less a boilerplate code-snippet for waiting for the http-response
const request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
Now let's tailor it with the code you submitted:
const request = new XMLHttpRequest();
const form = document.getElementById('login')
form.addEventListener('submit', callbackFunction);
function callbackFunction(e) {
event.preventDefault();
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log("Status: " + request.status);
console.log("Response: " + request.response);
console.log("ResponseText: " + request.responseText);
}
};
request.open('POST', 'https://someurl.net/api/user/login');
request.setRequestHeader('Content-Type', 'application/json;charset=UTF-8')
request.send(JSON.stringify(formJson(e)));
console.log(request)
};
function formJson(e) {
const credentialsDto = {};
const myFormData = new FormData(e.target);
console.log(myFormData);
myFormData.forEach((value, key) => (credentialsDto[key] = value));
return credentialsDto;
}
This should do it. Notice that event is deprecated and that you would continue using e instead.
Instead of depending on the onreadystatechange property, you could also choose for:
request.onload = function(e) {/*Your code*/};
An eventlistener which automatically looks for the succes denoting parameters and is a hack of a lot shorter.
I hope this helps.

How can a Json return be sent from a controller to the frontend in Asp.NET Core MVC application?

So, I have a JS script that sends a request to the server and that works fine. However, I want the frontend to recieve a response containing some information and read it on the frontend and execute a function.
uploadButton.addEventListener("click", () => {
var formData = new FormData();
var request = new XMLHttpRequest();
request.open("POST", "/Page/Upload");
request.send(formData);
if (request.response.result == "Success") {
console.log("Result is success")
window.location = request.response.url;
}
}
My controller looks like this.
[HttpPost("/page/upload")]
public IActionResult Upload()
{
*working parts pertaining to reading the request are omitted*
var redirectUrl = Request.Host + "/" + page.PageURL;
return Json(new { result = "Success", url = redirectUrl});
}
What I want is for my JS script to access the returned Json and its contents. How would I do this?
Try using the following code. It will subscribe the readystatechange event and run when API response has been received
uploadButton.addEventListener("click", () => {
var formData = new FormData();
var request = new XMLHttpRequest();
request.open("POST", "/Page/Upload");
request.send(formData);
request.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
var responseData = JSON.parse(this.responseText);
if (responseData.result == "Success") {
console.log("Result is success")
window.location = responseData.url;
}
}
});
});

Returning original post data if request fails

I know I could just do this with a global, but I'd like to be object oriented if I can. If my request response returns a false for that 'ok' value, I'd like to log the data that was originally posted. Is that data accessible by a listener function on the request object?
Thanks!
function reqListener () {
var data = this.responseText;
var jsonResponse = JSON.parse(data);
if (jsonResponse['ok'] == false) {
//Here I want to log the data that I originally posted
console.log(__TheFormDataThatWasPassedtoSend__);
}
}
var xhr = new XMLHttpRequest();
xhr.addEventListener("load",reqListener);
xhr.open('POST',urltopostto, true);
// Set up a handler for when the request finishes.
xhr.onload = function () {
if (xhr.status === 200) {
// File(s) uploaded.
console.log('Uploaded');
} else {
alert('An error occurred!');
}
};
xhr.send(formData);
So the problem you have is needing to use data known when you create the eventListener when the eventListener actually fires. Below is your code to do this with formData
function reqListener (formData) {
var data = this.responseText;
var jsonResponse = JSON.parse(data);
if (jsonResponse['ok'] == false) {
console.log(formData);
}
}
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", function() { reqListener.call(this,formData) });
xhr.open('POST',urltopostto, true);
// Set up a handler for when the request finishes.
xhr.onload = function () {
if (xhr.status === 200) {
// File(s) uploaded.
console.log('Uploaded');
} else {
alert('An error occurred!');
}
};
xhr.send(formData);

Return WebMethod Response & Use If Statement To Alert User Based On Response

I'm trying to include an if statement that analyzes the webmethod response which is either true or false. I just want to alert the user the post was successful if the response is true or the post was not successful if the response is false.
I can get the response using xhttp.responseText but I can't figure out how to build that into an if statement inside my javascript below:
//JavaScript that Posts to WebMethod
<script>
function createNewComment() {
var xhttp = new XMLHttpRequest();
var url = "http://localhost:57766/PALWebService.asmx/insertComment"
var a = document.getElementsByName("existingguid")[0].value;
var b = document.getElementsByName("newcomment")[0].value;
var c = 'existingguid=' + a + '&newcomment=' + b;
xhttp.open("POST", url, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
}
};
xhttp.send(c);
}
</script>
I figured it out. After checking that readyState was 4 and status was 200 I simply nested another if statement to check the responseText from the XMLHttpRequest and it was true I called another function and if it was false I notified user the post failed on the webmethod. It may not be perfect, but it works for what I need.
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
if (xhttp.responseText = true) {
addComment(b, today, userName);
}
else {
document.getElementsByName("newcomment")[0].value = '';
$("#commentLabel").html("Your comment was not saved in the database. Please try again or contact system admin.");
}
}
};

Returning data from AJAX callback by javascript

Firstly, I want to confirm that this question is not duplicated with other similar questions on stackoverflow, because my question is only based on javascript, NO jquery.
I wrote website https://www.emojionline.org. Because this site is small, I don't want to use JQuery. I tried to test with Jquery to solve this problem is ok, but I only want javascript without jquery.
My question is problem that return value from ajax callback function. I wrote as follows:
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'emoji.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
};
xobj.send(null);
}
function returnJSON(){
var jn = '';
loadJSON(function(response){
jn = JSON.parse(response);
});
return jn;
}
var json = returnJSON();
However, the json is null when I use console.log to write? What is this problem? Please help me solve it!
Synchronous request example:
function loadJSON(url) {
var request = new XMLHttpRequest();
request.overrideMimeType("application/json");
request.open('GET', url, false);
request.send();
if (request.readyState === 4 && request.status === 200)
return request.responseText;
}
// An example using ipify api (An IP Address API)
var json = loadJSON('https://api.ipify.org?format=json');
console.log(json);
Or asynchronous request example, using the Promise API and error event handler:
function loadJSON(url) {
return new Promise(function (resolve, reject) {
var request = new XMLHttpRequest();
request.overrideMimeType("application/json");
request.open('GET', url, true);
request.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status === 200) {
resolve({status: this.status, body: JSON.parse(this.responseText)});
} else {
reject({status: this.status, body: this.responseText});
}
}
};
request.send();
});
}
// An example using ipify api (An IP Address API)
loadJSON('https://api.ipify.org?format=json')
.then(function (response) {
console.log(response);
})
.catch(function (errorResponse) {
console.log(errorResponse);
});
xobj.open(method, url, async, user, password);
xobj.send(null);
reference: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/open

Categories