Get JSON from Web Service Using JavaScript - javascript

I get this error when I click the button in HTML to use my JavaScript.
myapp.azurewebsites.net/:1 Uncaught SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
JS:
function ajaxFunction() {
console.log("ajaxFunction()");
var ajaxRequest;
try {
ajaxRequest = new XMLHttpRequest();
} catch(e) {
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
alert("Broken");
return false;
}
}
}
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
var form = document.getElementById("myform");
var titleParagraph = document.getElementById("home_title");
titleParagraph.innerHTML = ajaxRequest.responseText;
form.style.display = "none";
}
}
var value1 = document.getElementById("field1").value;
var value2 = document.getElementById("field2").value;
var url = "https://webapp.azurewebsites.net/users/" + value1 + "/" + value2;
console.log(url);
// Call sign in web service
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
var jsonResponse = JSON.parse(ajaxRequest.responseText);
console.log("RESPONSE:");
console.log(jsonResponse);
}
This JSON is what I get when I go to https://webapp.azurewebsites.net/users/value1/value2
[{"ID":1,"UserName":"username","FirstName":"first","LastName":"last","email":"example#example.com"}]

ajaxRequest.open("GET", url, false);
Third parameter says if the request is asynchronous or not. So by looking at your code it should be synchronous.

Related

Javascript GET request after POST request

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

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});
}

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;
}
}
}

Trouble with having global JavaScript variables updated

I am trying to get a XML document sorted and decided to go for the "sort via XSLT" approach.
However, I am having trouble updating my two global variables that should contain the content of the XML and XSLT files and I can't really figure out why.
Up until now I never had this kind of problem and global variables used to work... I also didn't declare them inside the functions, but used the global name instead and also tried using window.variable, but to no avail.
Does anyone have an idea why the code doesn't update the global variable?
best regards,
daZza
<script type="text/javascript">
var xml = "";
var xsl = "";
function callSort()
{
loadSortXML();
loadSortXSLT();
sortXML();
}
function loadSortXML()
{
var xmlHttp = null;
var xmlData;
var xmlFile = "data/LessonsLearned.xml";
if (typeof XMLHttpRequest != 'undefined')
{
xmlHttp = new XMLHttpRequest();
}
if (!xmlHttp)
{
try
{
xmlHttp = new ActiveXObject("Msxm12.XMLHTTP");
}
catch(e)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP")
}
catch(e)
{
xmlHttp = null;
}
}
}
if (xmlHttp)
{
var url = xmlFile;
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4)
{
xml = xmlHttp.responseXML;
}
}
xmlHttp.send();
}
}
function loadSortXSLT()
{
var xmlHttp = null;
var xmlData;
var xmlFile = "data/xslt.xml";
if (typeof XMLHttpRequest != 'undefined')
{
xmlHttp = new XMLHttpRequest();
}
if (!xmlHttp)
{
try
{
xmlHttp = new ActiveXObject("Msxm12.XMLHTTP");
}
catch(e)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP")
}
catch(e)
{
xmlHttp = null;
}
}
}
if (xmlHttp)
{
var url = xmlFile;
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4)
{
xsl = xmlHttp.responseXML;
}
}
xmlHttp.send();
}
}
function sortXML()
{
console.log("XML " + xml);
console.log("XSL "+ xsl);
var parser = new DOMParser();
var domToBeTransformed = parser.parseFromString(xml, "text/xml");
var xslt = parser.parseFromString(xsl, "text/xml");
var processor = new XSLTProcessor();
processor.importStylesheet(xslt);
var newDocument = processor.transformToDocument(domToBeTransformed);
var serializer = new XMLSerializer();
var newDocumentXml = serializer.serializeToString(newDocument);
alert(newDocumentXml);
}
</script>

xmlHttp.responseText does not return data from json webservice

I am trying to retrieve data from json webservice.
if (xmlHttp.status == 200 || xmlHttp.status == 0)
{
var result = xmlHttp.responseText;
json = eval("(" + result + ")");
}
i"m getting nothing for the var result. When i replace the webservice with a text file which contains json object, then i can retrieve the json object as responseText. Please help
First things first... never ever, ever, ever use eval*. eval = evil.
How to use GET with AJAX...
try {
http = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e1) {
try {
http = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
this.xmlhttp = null;
}
}
var url = "/uri/of/web-service?val1=Laura&val2=Linney" + Math.random();
var params = "val1=Laura&val2=Linney";
http.open("GET", url, true);
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
// we have a response and this is where we do something with it
json = JSON.parse(http.responseText);
}
}
http.send();
How to use POST with AJAX...
try {
http = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e1) {
try {
http = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
this.xmlhttp = null;
}
}
var url = "/uri/of/web-service";
var params = "val1=Laura&val2=Linney";
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
// we have a response and this is where we do something with it
json = JSON.parse(http.responseText);
}
}
http.send(params);

Categories