Javascript GET request after POST request - javascript

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

Related

Sending location to the database directly

I have a script that allows to get the position (latitude & longitude) and after that it gets inserted in the input!
<script>
function maPosition(position) {
var x = position.coords.latitude;
var y= position.coords.longitude;
document.getElementById("x").value=x;
document.getElementById("y").value=y;
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(maPosition);
}
</script>
this is the result looks like!!
I want to, when the user allows the permission to get his position, the script automatically send the position (x,y) to the database without putting the position in the input (because I couldn't the position without putting them in the input)!!!
this is my script in NodeJs :
<script>
function ajouter() {
var url = "http://127.0.0.1:3000/reclamations";
var data = { };
data.location="X = "+document.getElementById("x").value;
data.location+="Y = "+document.getElementById("y").value;
var json = JSON.stringify(data);
console.log(json);
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader('Content-type','application/json; charset=utf-8');
xhr.onload = function () {
var users = JSON.parse(xhr.responseText);
if (xhr.readyState == 4 && xhr.status == "200") {
alert(" added !");
}
else {
console.table(users);
}
}
xhr.send(json);
}
</script>
Your code is very close, I added a button to make it easier to run here.
const ajouter = position => {
const url = "http://127.0.0.1:3000/reclamations";
// data is an object
let data = {};
// there are two properties - x and y which represent latitude and longitude
data.x = position.coords.latitude;
data.y = position.coords.longitude;
const json = JSON.stringify(data);
console.log(json);
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
xhr.onload = function() {
const users = JSON.parse(xhr.responseText);
if (xhr.readyState == 4 && xhr.status == "200") {
alert(" added !");
} else {
console.table(users);
}
}
xhr.send(json);
}
// this will show an error to make it easier to debug
const error = e => console.log(e);
document.getElementById("go").addEventListener("click", evt => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(ajouter, error);
}
});
<button id="go">Go</button>
First off, I would create a reusable post function, so you can use Objects that automatically convert to FormData. Perhaps this will help:
function post(url, send, func, responseType ='json', context = null){
const x = new XMLHttpRequest;
if(typeof send === 'object' && send && !(send instanceof Array)){
const c = context || x;
x.open('POST', url); x.responseType = responseType;
x.onload = ()=>{
if(func)func.call(c, x.response);
}
x.onerror = e=>{
if(func)func.call(c, {xhrErrorEvent:e});
}
let d;
if(send instanceof FormData){
d = send;
}
else{
let s;
d = new FormData;
for(let k in send){
s = send[k];
if(typeof s === 'object' && s)s = JSON.stringify(s);
d.append(k, s);
}
}
x.send(d);
}
else{
throw new Error('send argument must be an Object');
}
return x;
}
function ajouter(){
navigator.geolocation.getCurrentPosition(position=>{
const pos = position.coords, data = {lat:pos.latitude, lng:pos.longitude, accuracy:pos.accuracy};
post('http://127.0.0.1:3000/reclamations', data, resp=>{
/* should echo json_encode($objOrAssocArray); in PHP - or send a JSON string back with node - resp will be JSON then - access like resp.property */
});
}, error=>{
throw new Error('error code:'+error.code+'; error message:'+error.message);
}, {enableHighAccuracy:true});
}

How to make a variable from json using XMLHttpRequest?

I would like to get an array with objects from json using XMLHttpRequest() and assign it to a variable.
If i log it in a console it shows the array.
function getData() {
let myJson = [];
var xhr = new XMLHttpRequest();
var url = 'https://www.reddit.com/r/funny.json';
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var jsonData = JSON.parse(xhr.responseText);
arr = jsonData.data.children;
for (let i = 0; i < arr.length; i++) {
let newObject = {};
newObject.title = arr[i].data.title;
newObject.upvotes = arr[i].data.ups;
newObject.score = arr[i].data.score;
newObject.num_comments = arr[i].data.num_comments;
newObject.created = arr[i].created_utc;
myJson.push(newObject);
}
}
};
xhr.open("GET", url, true);
xhr.send();
return myJson;
}
let data = getData();
console.log(data[0]);
But if I try to do anything with (console.log(data[0]);) it it returns undefined. What am I doing wrong? Thanks for any explanation! Cheers.
Just pass in the callback function instead of returning the value from an asynchronous XML HTTP request.
function getData(callback) {
var xhr = new XMLHttpRequest();
var url = 'https://www.reddit.com/r/funny.json';
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var jsonData = JSON.parse(xhr.responseText);
arr = jsonData.data.children;
let myJson = [];
for (let i = 0; i < arr.length; i++) {
let newObject = {};
newObject.title = arr[i].data.title;
newObject.upvotes = arr[i].data.ups;
newObject.score = arr[i].data.score;
newObject.num_comments = arr[i].data.num_comments;
newObject.created = arr[i].created_utc;
myJson.push(newObject);
}
// Invoke the callback now with your recieved JSON object
callback(myJson);
}
};
xhr.open("GET", url, true);
xhr.send();
}
getData(console.log);
Your return happens outside of the onreadystatechange. So you exit before you even have the data.
Pass in a callback function to call when you have the data, or have the asynchronous call return a JS Promise that resolves with the gotten data.

How do I pull a JSON file that is separate from a RESTFUL API's functions as an authenticated user via an API?

I need to simulate an authenticated user to pull a JSON file. I am using Last.fm's API, but there is currently no method to pull the specific data I want. If I just pull it as plain text in browser, it shows up. However, I want data that is specific to an authenticated user. So, if I login to Last.fm as me, then pull the data, the data is different than if I just pull the data from anywhere.
Basically, the data contained in this file is specific to the user, and as there is no function specifically set to access this file, I don't know how I'd do that....
My function that pulls the current data is listed below:
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
function getRadio() {
var trackUrls = new Array();
var resValue;
var station;
var radioStation;
var url;
var data;
var neatDisplay;
var resultsDisplay = document.getElementById('result');
var radioTypeInput = document.getElementsByName('radioType');
var queryInput = document.getElementById('query');
var query = queryInput.value;
for (var i = 0, length = radioTypeInput.length; i < length; i++) {
if (radioTypeInput[i].checked) {
station = radioTypeInput[i].value;
break;
}
}
if (station == 1) {
radioStation = "recommended";
} else if (station == 2) {
radioStation = "library";
} else if (station == 3) {
radioStation = "mix";
} else {
radioStation = "music";
};
if (radioStation != "music") {
url = "https://crossorigin.me/" + "http://www.last.fm/player/station/user/" + query + "/" + radioStation;
} else {
url = "https://crossorigin.me/" + "http://www.last.fm/player/station/music/" + query;
};
console.log(url);
request = createCORSRequest("get", url);
if (request) {
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
data = JSON.parse(request.responseText);
for (i = 0; i < data.playlist.length; i++) {
trackUrls[i] = data.playlist[i].playlinks[0].url;
}
neatDisplay = trackUrls.join("\n ");
resultsDisplay.innerHTML = neatDisplay;
console.log(neatDisplay.toString());
neatDisplay = neatDisplay.toString();
return neatDisplay.toString();
} else if (request.status == 503) {
resultsDisplay.innerHTML = "Connection Error. The application may be overloaded."
} else {}
};
request.onerror = function() {
document.getElementById("result").innerHTML = "Connection Error. The application may be overloaded. Try again later"
};
request.send();
}
}
Ultimately, this used to pull Spotify links in the resulting data, but now it pulls YouTube. So, the problem only occurs if just pulling the file, without authentication.

update function on ajaxObject

When a button is clicked on the webpage a table of data is displayed. I want to scrape that data but I can't find where it comes from in the website source code.
This is the tag for the button:
<button type="submit" onclick="divChangeStateOn('load-raw-0062294377Amazon.com'); getRaw('0062294377', 'Amazon.com', 'lr-0062294377Amazon.com',this);"style="margin-bottom: 4px; width: 120px; text-align: left;" name="load-raw"><img src='images/workstation.png'/> raw data</button>
I believe that the getRaw function is where the data comes from (I'm not positive about this) so I looked at the javascript code for the getRaw function
function getRaw(asin, store, res, caller)
{ document.getElementById(res).innerHTML = '<p align="center" valign="top"><img align="center" src="phpmy_loading.gif"></p>';
var poststr = "raw=" + encodeURI(asin) +
"&site=" + encodeURI(store);
var updateResults = new ajaxObject(res, 'extra.php', caller);
updateResults.update(poststr);
}
I have been having a hard time finding any documentation about ajaxObject and can't find any information about the update function. What is ajaxObject.update doing and is it possible for me to access the data that appears when the button is clicked?
function divChangeStateOn(divID)
{ var divElem = document.getElementById(divID);
divElem.style.display = 'block';
}
EDIT: The link to the source code view-source:http://www.ranktracer.com/account_workstation.php it might be password protected but I was just using the demo version
EDIT 2:
I am basically trying to write a script that replicates the Ajax http request. This where I am at, it doesn't work and I am especially concerned about where data = uri
x = time.time()
print x
timestamp = datetime.fromtimestamp(x/1000.0)
print timestamp
uri = "raw=0062294377&site=Amazon.com&timestamp="+str(timestamp);
url = "lr-0062294377Amazon.com"
length = str(len(uri))
headers = {'X-Requested-With': 'XMLHttpRequest',
"Content-type": "application/x-www-form-urlencoded",
"Content-length": length,
"Connection" : "close"}
s = Session()
r = s.post(url= url, data= uri, headers= headers)
The entire code for ajaxObject is present in the link you provided. Please let us know what help you are expecting here?
function ajaxObject(layer, url, caller) {
if (caller) {
disableButton(caller, 'disable');
}
var that = this;
var updating = false;
this.callback = function() {}
var LayerID = document.getElementById(layer);
this.update = function(passData) {
if (updating == true) {
return false;
}
updating = true;
var AJAX = null;
if (window.XMLHttpRequest) {
AJAX = new XMLHttpRequest();
} else {
AJAX = new ActiveXObject("Microsoft.XMLHTTP");
}
if (AJAX == null) {
alert("Your browser doesn't support AJAX.");
return false
} else {
AJAX.onreadystatechange = function() {
if (AJAX.readyState == 4 || AJAX.readyState == "complete") {
if (caller) {
disableButton(caller, 'enable');
}
LayerID.innerHTML = AJAX.responseText;
delete AJAX;
updating = false;
that.callback();
}
}
var timestamp = new Date();
var uri = passData + '&timestamp=' + (timestamp * 1);
AJAX.open("POST", url, true);
AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
AJAX.setRequestHeader("Content-length", uri.length);
AJAX.setRequestHeader("Connection", "close");
AJAX.send(uri);
return true;
}
}
}

Calling data from JSON file using AJAX

I am trying to load some data from my JSON file using AJAX. The file is called external-file.json. Here is the code, it includes other parts that haven't got to do with the data loading.The part I'm not sure of begins in the getViaAjax funtion. I can't seem to find my error.
function flip(){
if(vlib_front.style.transform){
el.children[1].style.transform = "";
el.children[0].style.transform = "";
} else {
el.children[1].style.transform = "perspective(600px) rotateY(-180deg)";
el.children[0].style.transform = "perspective(600px) rotateY(0deg)";
}
}
var vlib_front = document.getElementById('front');
var el = document.getElementById('flip3D');
el.addEventListener('click', flip);
var word = null; var explanation = null;
var i=0;
function updateDiv(id, content) {
document.getElementById(id).innerHTML = content;
document.getElementById(id).innerHTML = content;
}
updateDiv('the-h',word[i]);
updateDiv('the-p',explanation[i])
function counter (index, step){
if (word[index+step] !== undefined) {
index+=step;
i=index;
updateDiv('the-h',word[index]);
updateDiv('the-p',explanation[index]);
}
}
var decos = document.getElementById('deco');
decos.addEventListener('click', function() {
counter(i,-1);
}, false);
var incos = document.getElementById('inco');
incos.addEventListener('click', function() {
counter(i,+1);
}, false);
function getViaAjax("external-file.json", callback) { // url being the url to external File holding the json
var r = new XMLHttpRequest();
r.open("GET", "external-file.json", true);
r.onload = function() {
if(this.status < 400 && this.status > 199) {
if(typeof callback === "function")
callback(JSON.parse(this.response));
} else {
console.log("err");// server reached but gave shitty status code}
};
}
r.onerror = function(err) {console.log("error Ajax.get "+url);console.log(err);}
r.send();
}
function yourLoadingFunction(jsonData) {
word = jsonData.words;
explanation = jsonData.explanation;
updateDiv('the-h',word[i]);
updateDiv('the-p',explanation[i])
// then call whatever it is to trigger the update within the page
}
getViaAjax("external-file.json", yourLoadingFunction)
As #light said, this:
function getViaAjax("external-file.json", callback) { // url being the url to external File holding the json
var r = new XMLHttpRequest();
r.open("GET", "external-file.json", true);
Should be:
function getViaAjax(url, callback) { // url being the url to external File holding the json
var r = new XMLHttpRequest();
r.open("GET", url, true);
I built up a quick sample that I can share that might help you isolate your issue. Stand this up in a local http-server of your choice and you should see JSON.parse(xhr.response) return a javascript array containing two objects.
There are two files
data.json
index.html
data.json
[{
"id":1,
"value":"foo"
},
{
"id":2,
"value":"bar"
}]
index.html
<html>
<head>
</head>
<body onload="so.getJsonStuffs()">
<h1>so.json-with-ajax</h1>
<script type="application/javascript">
var so = (function(){
function loadData(data){
var list = document.createElement("ul");
list.id = "data-list";
data.forEach(function(element){
var item = document.createElement("li");
var content = document.createTextNode(JSON.stringify(element));
item.appendChild(content);
list.appendChild(item);
});
document.body.appendChild(list);
}
var load = function()
{
console.log("Initializing xhr");
var xhr = new XMLHttpRequest();
xhr.onload = function(e){
console.log("response has returned");
if(xhr.status > 200
&& xhr.status < 400) {
var payload = JSON.parse(xhr.response);
console.log(payload);
loadData(payload);
}
}
var uri = "data.json";
console.log("opening resource request");
xhr.open("GET", uri, true);
xhr.send();
}
return {
getJsonStuffs : load
}
})();
</script>
</body>
</html>
Running will log two Javascript objects to the Dev Tools console as well as add a ul to the DOM containing a list item for every object inside the data.json array

Categories