Like the title says: "Uncaught ReferenceError: make_basic_auth is not defined"
I have a sensor that is connected to the app via bluethooth. The app sends the data to the cloud service. I got a link from the cloud service that contains the data in a json format and I have to GET the data from it.
make_basic_auth is a function to authentificate my GET request.
Im new and I dont have a clue what I did wrong.
<html>
<head>
<title>Test</title>
<script src="jquery-3.2.1.min.js"></script>
<script src="Base64Toolkit.js"></script>
</head>
<body>
<button onclick="myFunctionPost()">Post</button>
<div id="result" style="color:red"></div>
<script>
function make_base_auth(user, password) {
var tok = user + ':' + pass;
var hash = Base64.encode(tok);
return "Basic " + hash;
}
var auth = make_basic_auth('myUSERNAME','myPASSWORD');
var url = 'myURL';
// RAW
xml = new XMLHttpRequest();
xml.setRequestHeader('Authorization', auth);
xml.open('GET',url)
// ExtJS
Ext.Ajax.request({
url : url,
method : 'GET',
headers : { Authorization : auth }
});
// jQuery
$.ajax({
url : url,
method : 'GET',
beforeSend : function(req) {
req.setRequestHeader('Authorization', auth);
}
});
function myFunctionPost() {
var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.withCredentials = true;
xhr.send();
});
};
getJSON('myURL').then(function(data) {
alert('Your Json result is: ' + data.result); //you can comment this, i used it to debug
result.innerText = data.result; //display the result in an HTML element
}, function(status) { //error detection....
alert('Something went wrong.');
});
}
</script>
</body>
</html>
Typo:
make_base_auth <- defined
make_basic_auth <- used
Related
I am a newbie in programming.
I have a sensor that is connected to the app via bluethooth. The app sends the data to the cloud service. I got a link from the cloud service that contains the data in a json format. Now I want this data to be displayed on my Website, but its cross domain and whatever I do it says 401 (Unauthorized).
<html>
<head>
<title>Sensor</title>
<script src="jquery-3.2.1.min.js"></script>
</head>
<body>
<h1>Sensor</h1>
<button onclick="myFunctionPost()">Start</button>
<div id="result" style="color:red"></div>
<script>
function myFunctionPost() {
var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
}; getJSON('https://thetablewheremydatais$format=json').then(function(data) {
alert('Your Json result is: ' + data.result); //you can comment this, i used it to debug
result.innerText = data.result; //display the result in an HTML element
}, function(status) { //error detection....
alert('Something went wrong.');
});
}
</script>
</body>
</html>
Have you tried this line of code before you call the server with xhr.send()
xhr.withCredentials = true;
I'm trying to call a view in Elgg via AJAX, but nothing works after >>HERE<<
$('.glyphicon-zoom-in').click(function(event) {
$( '.full-image-view' ).css( "color", "red" ).append('<div>Hope this works</div>');
// >>HERE<<
var Ajax = require('elgg/Ajax');
var ajax = new Ajax();
ajax.view('albums/inline_full_image_view', {
data: {
guid: 123 // querystring
},
}).done(function (output, statusText, jqXHR) {
if (jqXHR.AjaxData.status == -1) {
return;
}
$('.full-image-view').append(output);
});
});
Output : Hope this works
What could I be getting wrong?
Thank you all in advance.
UPDATE
inline_full_image_view.php
<?php
echo 'Hello World';
Elgg uses requirejs. Try this:
requirejs(["elgg/Ajax"], function(Ajax) {
var ajax = new Ajax();
//rest of your code!!
});
Otherwise, using native JS.
var xhr = new XMLHttpRequest();
xhr.open('GET', encodeURI('albums/inline_full_image_view'));
xhr.onload = function() {
if (xhr.status === 200) {
alert('User\'s name is ' + xhr.responseText);
}
else {
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();
Im trying to parse a Json response from a rest server using JavaScript and display the data.
The rest server works fine its just that i cant parse the data. I have looked at dozens of examples and from my understanding the code looks fine.
This is my first attempt at learning Ajax and if i fix this i can continue with my project.
This is the response
{"id":"1","author":"Bill Burke","title":"RESTful Java with JAX-RS","year":"2009"}
This is the server
#Path("/books") // JAX-RS annotation
public class BookResource {
#GET // JAX-RS annotation
#Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.TEXT_XML })
#Path("/{bookId}")
public Book getBook(#PathParam("bookId") String id) {
return BookDao.instance.getBook(Integer.parseInt(id));
}
}
This is the client
<!DOCTYPE html>
<html>
<head>
<title>Form to create a new resource</title>
<script type="text/javascript">
function getHTTPObject() {
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
xhr = false;
}
}
}
return xhr;
}
function grabFile(file) {
var request = getHTTPObject();
if (request) {
request.onreadystatechange = function() {
parseJ(request);
};
request.open("GET", file, true);
request.send(null);
}
}
function parseJ(request) {
if (request.readyState == 4) {
if (request.status == 200 || request.status == 304) {
var obj = JSON.parse(request.responseText);
document.getElementById("details").innerHTML = obj.id + " " + obj.author + " "
+ obj.title + " " + obj.year;
}
}
}
</script>
</head>
<body>
<a
href="http://localhost:8080/Distributed_REST_booksServer/rest/books/1"
onclick="grabFile(this.href); return false;">Book 1</a>
<br>
<div id="details"></div>
</body>
</html>
html console error
html console error after modification
Your server is returning XML, try to force it as JSON and maybe add an accept header to the request from the client.
I want to send email from Chrome extension where user has to enter the email address of the reciepent in the extenion popup window, and the link of the current opened tab will be sent to the entered email address, but I am stuck in the authentication part, it asks for the password of my email as shown in the.
After I enter, it reloads the same page instead of sending the mail. Please help me out where I am getting wrong.
The code is for popup.js page.
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('button').addEventListener('click', getCurrentTabAndUrl);
});
function getCurrentTabAndUrl() {
chrome.tabs.getSelected(null, function(tab) {
var tabId = tab.id;
var tabTitle=tab.title;
var tabUrl = tab.url;
if (tabUrl=="chrome://newtab/") {
document.getElementById("data").innerHTML="Looks like you opened a new tab, please open a web page and click again to Share.";
}else {
document.getElementById("data").innerHTML="subject="+tabTitle+'<br/>'+tabUrl;
var to=document.getElementById("to").value;
sendMessage('me',to,tabTitle,tabUrl);
}
});
}
function sendMessage(userId,to,subject,email) {
authUser();
var base64EncodedEmail = btoa(email);
var request = gapi.client.gmail.users.messages.send({
'userId': userId,
'message': {
'raw': base64EncodedEmail,
"headers":[
{"To":to},
{"Subject":subject}
]
}
});
request.execute();
}
function authUser(){
chrome.identity.getAuthToken(
{'interactive': true},
function(token){
// load Google's javascript client libraries
var url="https://www.googleapis.com/gmail/v1/users/me/messages/send?access_token="+token;
var request = new XMLHttpRequest();
request.onreadystatechange = function(){
if(request.readyState !== 4||request.status !== 200) {
return;
}
var response=JSON.parse(request.responseText);
console.log(response);
};
request.open('POST', url,true);
request.send();
request.setRequestHeader('Authorization','Bearer ' + token);
});
}
After invoking authUser(), which calls an asynchronous API chrome.identity.getAuthToken, you're immediately sending the email so it fails as the token hasn't yet been acquired.
Move that part into a callback which will be executed after getAuthToken completes:
function sendMessage(userId, to, subject, email) {
authUser(function() {
var base64EncodedEmail = btoa(email);
var request = gapi.client.gmail.users.messages.send({
'userId': userId,
'message': {
'raw': base64EncodedEmail,
'headers': [
{'To': to},
{'Subject': subject}
]
}
});
request.execute();
});
}
function authUser(callback) {
chrome.identity.getAuthToken({'interactive': true}, function(token) {
// load Google's javascript client libraries
var url = "https://www.googleapis.com/gmail/v1/users/me/messages/send?access_token=" + token;
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState !== 4 || request.status !== 200) {
return;
}
var response = JSON.parse(request.responseText);
console.log(response);
callback();
}
;
request.open('POST', url, true);
request.send();
request.setRequestHeader('Authorization', 'Bearer ' + token);
});
}
I want to use readability parser API but when I am making call to this API I am getting blank/no response.
When I tried with some other url the same code is giving proper response.
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8;">
<head>
<script language="javascript">
var getJSON = function(url, successHandler, errorHandler) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
alert("-------" + url);
//xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
alert("===========" + status);
if (status == 200) {
successHandler && successHandler(xhr.response);
} else {
errorHandler && errorHandler(status);
}
};
xhr.send();
};
function getReading() {
var url1 = "https://www.readability.com/api/content/v1/parser?url=";
var testurl = "http://www.saptechnical.com/Tutorials/WebDynproABAP/ALV/page1.htm";
var urltoken = "&token=tokenkeyhere";
var finalurl = url1 + testurl + urltoken;
alert(finalurl);
getJSON(finalurl, function(data) {
alert(data.domain);
});
}
</script>
</head>
<body>
<input type="button" value="go" onClick="getReading()" />
</html>
I got answer and code is working now..
I used getJSON method to make a call to API.
function getInfo() {
var url = $("#txtSubmitlink").val();
$.getJSON("https://www.readability.com/api/content/v1/parser?url="+ url +"&token=tokenkeyhere&callback=?",
function (data) {
$("#dvContent").html(data.content);
$("#imgLeadImage").attr('src', data.lead_image_url);
});
}
Thanks everyone-