Ajax with Javascript to send text to html - javascript

I am learning ajax with javascript where I have a html which has a button inside a div like below
home.html
<div id="test">
<h1>Welcome</h1>
<button type="button" onclick="loadDoc()">Show</button>
</div>
On clicking on the button I would like to update the with sample text lets say Hai ! Ajax here
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("test").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "ajax_info.txt", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send();
}
If I do with opening a text file which contains the text and send on http request it works but I do not want to load a file in my open() method instead just send text to my home.html and I tried like below does not seems working
xhttp.open("POST", "home.html", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("message=Hai Ajax Here");
How to do this ?
Thanks

Related

how can i update the div data with xml http request

On my JSP page, I need to get the data from the XML HTTP request,
here is my code,,
<body>
<div id="ptab">
<button onclick="next()"></button>
</div>
<script>
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","url",false);
xmlhttp.send(null);
document.getElementById("ptab").innerHTML=xmlhttp.responseText;
</script>
<script>
function next(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("ptab").innerHTML = this.responseText;
}
};
xhttp.open("GET", 'url?id=2', true);
xhttp.send();
}
</script>
</body>
when I click the button, it displays the data getting from the URL but it didn't update the URL with id '2'.
firstly, when the page loads, I have to display the data from the URL.
when I click the button, I need to display the data from URL?id='2'
how can I get this,
or any other approaches to fetch the response without refreshing the page

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

How to scrape and run script in browser with javascript?

I'm making my own website(https://khushit-shah.github.io/) with the help of github.dev.
Now on top of every repository, I wanted to show some content featuring the repository, which should be flexible and easily changeable. So, I created a file in repository named "repodesc.html". which contains the html to we shown!. Then using following code I am adding that html file for every repositories.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("{{ repository.id }}").innerHTML = this.responseText;
}
};
xhttp.open("GET", "https://raw.githubusercontent.com/khushit-shah/{{ repository.name }}/master/repodesc.html", true);
xhttp.send();
This adds the HTML in https://raw.githubusercontent.com/khushit-shah/Cursor.js/master/repodesc.html to my website(top of Cursor.js). But the script tag in the repodesc is not getting executed.
Code in repodesc.html
<h1 cursor-animate cursor-loop-reverse> Cursor.js </h1>
<script>
console.log("Is it working?");
js = "https://raw.githubusercontent.com/khushit-shah/Cursor.js/master/cursor-v.2.0.2.js";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
eval(this.responseText);
}
};
xhttp.open("GET", js, true);
xhttp.send();
</script>
I even tried repodesc.html
<h1 cursor-animate cursor-loop-reverse> Cursor.js </h1>
<script src="https://cdn.jsdelivr.net/gh/khushit-shah/Cursor.js#latest/cursor.v1.0.0.min.js" >
</script>
expected result : Cursor.js should be executed and the h1 tag should be animated with type writing effect!
actual result: the script in repodesc.html is not getting executed!

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

Categories

Resources