I am new to javascript promises and I want to load the content of a file into a specific element but I get a 403 Forbidden error. Any idea how to get access to the LOCAL file that I am trying to load?
function openFile (page) {
$('#load').load(page);
}
function getFile (callback) {
let req = new XMLHttpRequest();
req.open('GET', "/includes/addons/load.html");
req.onload = function() {
if (req.status == 200) {
callback(this.responseText);
} else {
callback("Error: " + req.status);
}
}
req.send();
}
getFile(openFile);
<button onclick="getFile(openFile)" >LOAD</button>
<div id="load"></div>
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;
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.
Here is the code. I am fairly new to JavaScript and I'm learning more every day. This code is from an example from a textbook. Thank you for your responses. Another question I'd like to ask is how can I display the returned text in an unordered list? Would that be something to include in the html side of things or can it be done within the JavaScript file?
window.addEventListener("load",initAll,false);
var xhr = false;
function initAll() {
document.getElementById("makeTextRequest").addEventListener("click",getNewFile,false);
document.getElementById("makeXMLRequest").addEventListener("click",getNewFile,false);
}
function getNewFile(evt) {
makeRequest(this.href);
evt.preventDefault();
}
function makeRequest(url) {
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
}
}
}
if (xhr) {
xhr.addEventListener("readystatechange",showContents,false);
xhr.open("GET", url, true);
xhr.send(null);
}
else {
document.getElementById("updateArea").innerHTML = "Sorry, but I couldn't create an XMLHttpRequest";
}
}
function showContents() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
if (xhr.responseXML && xhr.responseXML.childNodes.length > 0) {
var outMsg = getText(xhr.responseXML.getElementsByTagName("choices")[0]);
}
else {
var outMsg = xhr.responseText;
}
}
else {
var outMsg = "There was a problem with the request " + xhr.status;
}
document.getElementById("updateArea").innerHTML = outMsg;
}
function getText(inVal) {
if (inVal.textContent) {
return inVal.textContent;
}
return inVal.text;
}
}
By the looks of it, you are making an AJAX request and are receiving XML.
In this case, I would:
Open up a new page with window.open()(returns a new Window object)
And then change the document.body.innerHTML of that new page to the XML you have
If you had a webpage that held the XML(maybe the server you are requesting to has one), you can just do:
window.open("page.xml");
I have one nominal.jsp page,which includes header.jsp.Here i am using Ajax for the first time, for the request in header.jsp,then for the second time Ajax request is called to the nominal.jsp,i am facing the conflict issue in the Ajax request. Because of this issue,my preferred drop-down list is not displayed. Sometimes when response is entered in the JavaScript, the drop-downs are displayed and if the response are not entered in the JavaScript, the drop-downs are not displayed. Tried my level best to resolve the issue, but could not resolve it. Please help me guys
thank u,
My header.jsp code:
<script>
headerDisplay();
function headerDisplay()
{ var url ='<%=request.getContextPath()%>/summary?operation=header';
transactionRequest(url);
}
function transactionRequest(url)
{
if (window.XMLHttpRequest)
{
req = new XMLHttpRequest();
req.onreadystatechange = transactionResponse;
try
{
req.open("POST", url, true); //was get
}
catch(e)
{
alert("Problem Communicating with Server\n"+e);
}
req.send(null);
}
else if (window.ActiveXObject)
{
// IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req)
{
req.onreadystatechange = transactionResponse;
req.open("POST", url, true);
req.send();
}
}
}
function transactionResponse()
{
if (req.readyState == 4) // Complete
{
if (req.status == 200) // OK response
{ var servletVal = req.responseText;
var myObject = eval('(' + servletVal + ')');
var userId = myObject.userId;
}}}......
</script>
And,this is my nono.jsp code:
<%#include file="/pages/common/header.jsp"%>
<script>
function displayNominal()
{
document.getElementById("ajaxLoading").style.display="block";
var url ='<%=request.getContextPath()%>'+'/nominalList';
postRequest(url);
}
function postRequest(url) {
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
req.onreadystatechange = nominalSelect;
try {
req.open("POST", url, true); //was get
} catch (e) {
alert("Problem Communicating with Server\n" + e);
}
req.send(null);
} else if (window.ActiveXObject) {
// IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = nominalSelect;
req.open("POST", url, true);
req.send();
}
}
}
function nominalSelect() {
if (req.readyState == 4) // Complete
{
if (req.status == 200) // OK response
{
var servletVal = req.responseText;
var myObject = eval('(' + servletVal + ')');
var userId = myObject.userId;
if (userId == null || userId == "") {
window.location = '/accounts1/?status=session';
}
}}..
</script>
<body class="bodystyle" onload="displayNominal()">
<% if("N".equals(roleDemoStatus))
{%>
<!-- /#demo Header -->
<div style="top: 0px; display: block;" id="header" class="fixed">
<div class="outer">
<h1 class="blog-title" style="text-align:center;margin-top:10px;"><span style="font-weight: normal; color:#777777; font-size: 30px;">accounts<font color="#5DA915">1</font>.co</span> Demo Only - <font color="red">Click Here</font> To Use For Free Forever</h1>
</div><!-- .outer -->
<div style="display: block;" class="shadow"></div>
</div>
<!-- /#Demo Header -->
<%} %>
</body>
Again thanks for advance.
Use a single callback and a try/catch block to enforce the request order:
function transactionResponse()
{
// Check whether this is the initial callback or a subsequent one
if (!!transactionResponse.state)
{
try
{
//POST data from the GET request
}
catch(e)
{
//Get data from the GET request
}
}
// Set state after the initial callback reference
else
{
transactionResponse.state = this;
}
}
References
Long Polling Experiment
There may be a small error in my code. please advice me.
I want to call a URL and display the value in div on pageload.I wrote this code from SO but the responseText doesnt write the value in the div element's innerhtml
Code
<script type="text/javascript" >
var req ;
// Browser compatibility check
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
var req = new XMLHttpRequest();
req.open("GET", "www.example.com/Default.aspx?usrname=john",true);
req.onreadystatechange = function () {
document.getElementById('divTxt').innerHTML = "My Status: " + req.responseText;
}
req.send(null);
</script>
<html>
<head/>
<body>
<div id="divTxt"></div></body>
</html>
The output I get is
My status :
PS: I want this to be done after pageload and The url returns a value "online" when called manually
EDIT
This is the code I referred : code
You cannot ajax a url from another domain unless it has implemented CORS
If you need to get data from somewhere which is not same origin you need to use JSONP
Also to debug, try calling the url from the locationbar to see if you receive valid data for your request
req.onreadystatechange = function () {
document.getElementById('divTxt').innerHTML = "My Status: " + req.responseText;
}
you have to check, if the request was successful:
if (req.readyState === 4) {
// what should be done with the result
}
finally, it has to look like this:
req.onreadystatechange = function () {
if (req.readyState === 4) {
document.getElementById('divTxt').innerHTML = "My Status: " + req.responseText;
}
}