Basic AJAX script not working - javascript

I'm trying to load a file and display it in the div section of my web page, using AJAX. The console output shows that the XMLHttpRequest object is successfully created, but then nothing happens: the callback function is never called and the content of the URL is not fetched.
<body>
<div id="demo"><p>Some text</p></div>
<button type="button" onclick="loadDoc()">Request URL</button>
<script>
function loadDoc() {
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
console.log('object created'); // this message is printed
} else if (window.ActiveXObject) {
xhttp = new ActiveXObject("Mіcrosoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
console.log('inside callback function'); // this message is never printed
if(xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
xhttp.open("GET", "http://tools.ietf.org/rfc/rfc6120.txt", true);
xhttp.send(null);
};
}
console.log('end of script'); // this message is printed
</script>
</body>
I don't know much about HTTP requests and I'm assuming that AJAX can be used to load an url that is perfectly accessible to my web browser.
Is this assumption incorrect? If not, then what am I doing wrong?

Reorder your code
xhttp.onreadystatechange = function() {
console.log('inside callback function');
if(xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "http://tools.ietf.org/rfc/rfc6120.txt", true);
xhttp.send(null);
You must to send the request and the callback will be fired automatically. If you put that code inside the callback, you never achieve the request to the txt file

Related

Rapidapi Api request with XMLHttpRequest

this is my second post, I hope to be luckier than last time end get some reply. 🙂
I’m trying to make a Rapidapi api request working with javascript ”XMLHttpRequest”
I must say that the api works perfectly with ios siri shortcut.
this is the code provided from apirapit site on the "XMLHttpRequest" section:
var data = null;
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open("GET", "https://download-video-youtube1.p.rapidapi.com/mp3/medPORJ8KO0");
xhr.setRequestHeader("x-rapidapi-host", "download-video-youtube1.p.rapidapi.com");
xhr.setRequestHeader("x-rapidapi-key", "[my key here]");
xhr.send(data);
And this is my code:
<!DOCTYPE html>
<html>
<body>
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.withCredentials = true;
url='https://download-video-youtube1.p.rapidapi.com/mp3/xF5t2jOsCt8';
xhttp.onreadystatechange = function() {
if ((this.readyState == 4 && this.status == 200 )||(this.readyState === this.DONE)) {
document.getElementById("demo").innerHTML = "ciao" + this.responseText;
}
};
xhttp.open("GET", url);
xhttp.setRequestHeader("x-rapidapi-host", "download-video-youtube1.p.rapidapi.com");
xhttp.setRequestHeader("x-rapidapi-key", "[my key here]");
xhttp.send();
}
</script>
</body>
</html>
Just to testing I created a simply bank html page to have the JSON response beneath the button just after pressing it. The result is just the string “ciao” i set before the this.responseText. If I remove the apikey or modify it with a wrong value an JSON error message appear ( so like the case posted, as I intentionally removed it).
Otherwise as said noting but “ciao” string
Is there any syntax error? Is there a logical reason why it behave like this?
Thanks
Franco
Trying adding a data variable as null. That's what RapidAPI provides in their code snippet.
function loadDoc() {
const data = null
var xhttp = new XMLHttpRequest();
xhttp.withCredentials = true;
url='https://download-video-youtube1.p.rapidapi.com/mp3/xF5t2jOsCt8';
xhttp.onreadystatechange = function() {
if ((this.readyState == 4 && this.status == 200 )||(this.readyState === this.DONE)) {
document.getElementById("demo").innerHTML = "ciao" + this.responseText;
}
};
xhttp.open("GET", URL);
xhttp.setRequestHeader("x-rapidapi-host", "download-video-youtube1.p.rapidapi.com");
xhttp.setRequestHeader("x-rapidapi-key", "my key here");
xhttp.send(data);
}

Replace InnerHTML With Cookie Logging

I've got some javascript code for replacing innerHTML of a element when clicked. Now i've got the code for that and it does work great! But one small issue is that, I want the webserver to remember the change when innerHTML of an element was replaced. So the webserver remembers the change and doesn't return to its default state. Whether with database or in Cookie, sessionStorage, localStorage.
document.getElementById("replace1").innerHTML = localStorage.getItem("replace1");
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
localStorage.setItem("replace1",this.responseText);
}
};
xhttp.open("GET", "https://natevanghacks.com/replacements/yoinkexecutor2.html", true);
xhttp.send();
}
Try something like this in AJAX:
localStorage.setItem("replace1",this.responseText);
And after body onload:
document.getElementById("replace1").innerHTML = localStorage.getItem("replace1");
Edit:
function loadSavedData(){
var data=localStorage.getItem("replace1");
document.getElementById("replace1").innerHTML = data?data:'No Data found';
}
function deleteData(){
localStorage.removeItem("replace1");
}
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
localStorage.setItem("replace1",this.responseText);
document.getElementById("replace1").innerHTML =this.responseText;
console.log(this.responseText);
}
};
xhttp.open("GET", "filename.html", true); //put your filename here...
xhttp.send();
}
<button onclick="loadDoc()">Send request and load Data
</button>
<button onclick="loadSavedData()">load Saved Data
</button>
<button onclick="deleteData()">Delete saved Data
</button>
<br>
<div id="replace1">
</div>
Note: You should run this file on http:// or https:// protocols only

Load clicked URLs from AJAX loaded page

I have the following code which fetches content from another page using AJAX:
<div id="content">
</div>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("content").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "/Home/", true);
xhttp.send();
}
</script>
It works! Sadly, when you click on an URL from that page, all of the already loaded code disapears. :(
So my question is:
How can I make the clicked URLs load inside my DIV (content)?
Cheers.

XHTTP request from REST API

I have this API
[HttpGet("data")]
public dynamic GetData(){
return context.DataTable.ToList();
}
I tried calling it on my Javascript using this snippet;
function getData(){
var xhttp = XMLHttpRequest();
xhttp.open("GET", "api/myclass/data", true);
xhttp.setRequestHeader("Content-type","application/json");
xhttp.send();
var resp = xhttp.responseText;
}
However, it only returns empty XMLHttpRequest.
I think what's wrong there is the URL. How I may able to call the API to my Javascript?
Since u have not cheked the response of ur answer, i susspect there is something wrong in ur backend. But, here is a sample of functional solution:
<!DOCTYPE html>
<html>
<body>
<h2>Using the XMLHttpRequest Object</h2>
<div id="demo">
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</div>
<script>
function loadXMLDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
console.log("Status is: "+this.status);
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "xmlhttp_info.txt", true);
xhttp.send();
}
</script>
</body>
</html>
You van find more info here. But in the line
xhttp.open("GET", "api/myclass/data", true);
The second parameter is the address of a file in ur server. r u sure u have wrotten the correct format? what is the extension of ur data file.
I guess, both backend and front end should be reconsidered. To do it:
Try to send a reuqest using postman to backend
in frontend check the status of response using my answer
To make sure make it async = false with
xhttp.open("GET", "api/myclass/data", false);
Therefore, there wouldn't be a delay as #Alex Kudryashev pointed
Solution:
You need to first find the result of line
console.log("Status is: "+this.status);
in ur browser's console.
If u get the responseText as empty it may come because u have sent an empty string from backend,(we are not sure because u have not tested ur backend with postman) but it is crucial to know the status of response.
The request may take time to receive the response so you have to wait. Something like this.
function getData(){
var xhttp = XMLHttpRequest();
xhttp.open("GET", "api/myclass/data", true); //the request is asynchronous
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.state == 200){ //**this** is xhttp
//data are received and ready to use
var resp = this.responseText;
//do whatever you want with resp but never try to **return** it from the function
}
}
xhttp.setRequestHeader("Content-type","application/json");
xhttp.send();
//var resp = xhttp.responseText; //too early ;(
}

Ajax call not successful

I am making a javascript function call on onclick of any checkbox like this:
function getPGCountList(pageNo) {
var url = "someJsp.jsp?" + pageNo;
alert(1);
if (window.XMLHttpRequest) {
alert(2);
xmlhttp = new XMLHttpRequest();
} else {
alert(3);
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
alert(4);
xmlhttp.onreadystatechange = function () {
alert(5);
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(6);
document.getElementById("searchForPage").innerHTML = xmlhttp.responseText;
}
};
alert(7);
xmlhttp.open("GET", url, true);
alert(8);
xmlhttp.send();
}
The alert output I am getting is at my hosted site:
1-2-4-7-5-8-5-5-5
But in my local system it is:
1-2-4-7-5-8-5-5-5-6
I need to execute alert 6 also to change the content.
I am not sure where is the problem?
Your code looks fine to me. Check the path to someJsp.jsp
It's obviously not returning a normal response from the ajax call otherwise it would enter your if block and fire alert 6.
Just a thought too, but if you alert xmlhttp.readyState and xmlhttp.status maybe it'll help you find your problem. IF they are undefined, or refer to an object that is undefined, then your new XMLHttp requests failed. IF they give you results, you can see what the responses mean

Categories

Resources