Hey guys I am using a executePostHttpRequest function that looks exactly like the code posted below. Currently when I run the function I get a server response with the appropriate data but I am not sure how I can work with the response data? how do I store it in to a variable to work with?
Javascript executePostHttpRequest
function executePostHttpRequest(url, toSend, async) {
console.log("====== POST request content ======");
console.log(toSend);
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
xmlhttp.open("POST", url, async);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.setRequestHeader("Content-length", toSend.length);
xmlhttp.send(toSend);
console.log("====== Sent POST request ======");
}
Here is what I am doing to execute it. Using Javascript
var searchCriteria = JSON.stringify({
displayName : search_term
});
console.log("Search: "+searchCriteria) //Search: {"name":"John, Doe"}
var response = executePostHttpRequest("/web/search", searchCriteria, true);
console.log(response) //undefined
So currently the console.log for response shows undefined. But if I take a look at the network tab on Chrome Dev Tools and look at the /web/search call I see a JSON string that came back that looks something like this.
[{"id":"1","email":"john.doe#dm.com","name":"John, Doe"}]
I'd like to be able to display the data from this response to a HTML page by doing something like this.
$("#id").html(response.id);
$("#name").html(response.name);
$("#email").html(response.email);
I tried taking another route and using Jquery POST instead by doing something like this.
var searchCriteria = JSON.stringify({
displayName : search_term
});
console.log("Search: "+searchCriteria) //Search: {"name":"John, Doe"}
$.post("/web/search", {
sendValue : searchCriteria
}, function(data) {
$.each(data, function(i, d) {
console.log(d.name);
});
}, 'json').error(function() {
alert("There was an error searching users! Please contact administrator.");
});
But for some reason when this runs I get the "There was an error" with no response from the server.
Could someone assist me with this? Thank you for taking your time to read it.
Your executePostHttpRequest function doesn't do anything with the data it's receiving. You would have to add an event listener to the XMLHttpRequest to get it:
function getPostData(url, toSend, async, method) {
// Create new request
var xhr = new XMLHttpRequest()
// Set parameters
xhr.open('POST', url, async)
// Add event listener
xhr.onreadystatechange = function () {
// Check if finished
if (xhr.readyState == 4 && xhr.status == 200) {
// Do something with data
method(xhr.responseText);
}
}
}
I've added the method parameter for you to add a function as parameter.
Here's an example of what you were trying to do:
function displayStuff(jsonString) {
// Parse JSON string
var data = JSON.parse(jsonString)
// Loop over data
for (var i = 0; i < data.length; i++) {
// Get element
var element = data[i]
// Do something with its attributes
console.log(element.id)
console.log(element.name)
}
}
getPostData('/web/search', searchCriteria, true, displayStuff)
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();
}
I have to use a XMLHttpRequest, but I don't know which data format is expected by the function request.send(). I searched for too long now.
I tried to pass a JSON object but it does not work:
var request = new XMLHttpRequest();
request.open("GET","fileApi");
var data = {
action: "read",
targetFile: "testFile"
};
request.addEventListener('load', function() {
if (request.status >= 200 && request.status < 300) {
$("#messageOutput").html(request.responseText);
} else {
console.warn(request.statusText, request.responseText);
}
});
request.send(data);
I get updateFile:155 XHR finished loading: GET "http://localhost/cut/public/fileApi".
But no data is received on the server. I made this simple check to approve this:
PHP (server side):
$action = filter_input(INPUT_GET, "action");
$targetFile = filter_input(INPUT_GET, "targetFile");
echo ("action = '$action' | targetFile = '$targetFile'");
exit();
Returns: action = '' | targetFile = ''
Unfortunatelly I can't use jQuery in my application, since the target is a C# Webbrowser (Internet Explorer) and it detects errors in the jQuery file and stops my scripts from working...
I don't know which data format is expected by the function request.send()
It can take a variety of formats. A string or a FormData object is most common. It will, in part, depend on what the server is expecting.
I tried to pass a JSON object
That's a JavaScript object, not a JSON object.
request.open("GET","fileApi");
You are making a GET request. GET requests should not have a request body, so you shouldn't pass any data to send() at all.
GET requests expect data to be encoded in the query string of the URL.
var data = {
action: "read",
targetFile: "testFile"
};
var searchParams = new URLSearchParams();
Object.keys(data).forEach((key) => searchParams.set(key, data[key]));
var url = "fileApi?" + searchParams;
console.log(url);
// and then…
// request.open("GET", url);
// request.send();
Warning: URLSearchParams is new and has limited browser support. Finding a library to generate a query string is left as a (simple) exercise to any reader who wants compatibility with older browsers.
I have a simple script that does a cross site request and gets data from a GitHub gist. The data from the Github API is returned as a JSON string. To allow further modification of the data, I want it as a JSON object.
// Create the XHR object.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
var tmpJSON = "";
var gistData = "";
var gistID = "5789756";
var gitAPI = "https://api.github.com/gists/"
var gistQuery = gitAPI + gistID;
function incrementGist() {
gistData = createCORSRequest('GET', gistQuery);
gistData.send();
tmpJSON = JSON.parse(gistData.response);
}
In the html page, I have
<p><input type="button" value="Increment" OnClick="incrementGist()"></p>
If I actually hit the button, the error I get is:
Uncaught SyntaxError: Unexpected end of input
But if I subsequently open the console and run this:
var crap = JSON.parse(gistData.response);
it works just fine. This happens in both Firefox and Chrome. I really don't see why the JSON.parse command fails inside a function call, but not in the console. An actual page is set up here
The problem is that you're trying to read the response before the server answered.
You must read the response in a callback. For example :
gistData = createCORSRequest('GET', gistQuery);
gistData.onreadystatechange = function() {
if (gistData.readyState === 4) {
if (gistData.status === 200) {
tmpJSON = JSON.parse(gistData.response);
... use tmpJSON...
... which should not be called so as it is not JSON...
... maybe tmpObject ?
}
}
}
gistData.send();
That's because you are not waiting the request to actually finish. I don't know your API but try waiting the server response then parse your JSON. you could try with a SetTimeout first to see that it is working but you nee to do something like in jQuery with its' success:function(...) callback
I'm creating a simple WebGL project and need a way to load in models. I decided to use OBJ format so I need a way to load it in. The file is (going to be) stored on the server and my question is: how does one in JS load in a text file and scan it line by line, token by token (like with streams in C++)? I'm new to JS, hence my question. The easier way, the better.
UPDATE: I used your solution, broofa, but I'm not sure if I did it right. I load the data from a file in forEach loop you wrote but outside of it (i.e. after all your code) the object I've been filling data with is "undefined". What am I doing wrong? Here's the code:
var materialFilename;
function loadOBJModel(filename)
{
// ...
var req = new XMLHttpRequest();
req.open('GET', filename);
req.responseType = 'text';
req.onreadystatechange = function()
{
if (req.readyState == 4)
{
var lines = req.responseText.split(/\n/g);
lines.forEach(function(line)
{
readLine(line);
});
}
}
req.send();
alert(materialFilename);
// ...
}
function readLine(line)
{
// ...
else if (tokens[0] == "mtllib")
{
materialFilename = tokens[1];
}
// ...
}
You can use XMLHttpRequest to fetch the file, assuming it's coming from the same domain as your main web page. If not, and you have control over the server hosting your file, you can enable CORS without too much trouble. E.g.
To scan line-by-line, you can use split(). E.g. Something like this ...
var req = new XMLHttpRequest();
req.open('GET', '/your/url/goes/here');
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
var lines = req.responseText.split(/\n/g);
lines.forEach(function(line, i) {
// 'line' is a line of your file, 'i' is the line number (starting at 0)
});
} else {
// (something went wrong with the request)
}
}
}
req.send();
If you can't simply load the data with XHR or CORS, you could always use the JSON-P method by wrapping it with a JavaScript function and dynamically attaching the script tag to your page.
You would have a server-side script that would accept a callback parameter, and return something like callback1234(/* file data here */);.
Once you have the data, parsing should be trivial, but you will have to write your own parsing functions. Nothing exists for that out of the box.