Vanilla Javascript version of AJAX [duplicate] - javascript

This question already has answers here:
How can I make an AJAX call without jQuery?
(24 answers)
Closed 4 years ago.
How can I remove the need to download a full jquery library when all I want to use is AJAX. Is there a smaller file that focuses on AJAX or is there a Vanilla Javascript version of this code?
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: 'POST',
url: 'cookies.php',
success: function(data) {
alert(data);
}
});
});
});
</script>

You can use the fetch function.
Here is an example from the link:
fetch('http://example.com/movies.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});

You can try with XMLHttpRequest like below.
<!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.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("POST", "cookies.php", true);
xhttp.send();
}
</script>
</body>
</html>
Demo: https://www.w3schools.com/js/tryit.asp?filename=tryjs_ajax_first
Reference: https://www.w3schools.com/js/js_ajax_http_send.asp

you can use build in fetch module for example
fetch('http://yourapi.com/data')
.then(response => {
console.log(response)
});

Related

Serverside send information to vanilla HTML

Is it possible to send information from the serverside to the client side like you would with Pug or EJS but without a view engine?
Right now I am using XHTTP requests to access data but it would be a lot easier to not have to use it so much.
function getAllBears(id){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("allBear").innerHTML = this.responseText;
}
};
xhttp.open("GET", "allBears", true);
xhttp.send();
}
You can insert a script tag in HTML and stringify the variable you have on server side, then read the serialized global variable on window.
response.body = ('
<html>
<head>
...
</head>
<body>
<p>text...</p>
<script>
window.bar = ###
</script>
</body>
</html>
'.replace(###, JSON.stringify(bar))
Be careful that some patterns/chars should be replaced in the result of JSON.stringify, a much safer method is as follows:
function toJSONSafely (obj: any) {
return JSON.stringify(obj)
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029')
.replace(/<\/script>/g, '<\\/script>')
}
User your javascript inside the html code i.e inline javascript
as shown below
<html>
<head>
</head>
<body>
<p>use this code </p>
<script>
function getAllBears(id){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("allBear").innerHTML = this.responseText;
}
};
xhttp.open("GET", "allBears", true);
xhttp.send();
}
</script>
</body>
</html>

Sending a Request To a database(google sheets)

I have created a script within google sheets. It gives a result of a cell from my table in google sheets(kinda database). I want the result send to my html page, and i have tried so far with XMLHttprequest but with no success.
What have i done wrong?
Here is the Script
<script>
function load() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "https://script.google.com/macros/s/AKfycby5RzvUWSEOjerJpouxN72wpsgpsF8IWQo2AvjZUdRPcqskz28/exec", true);
xhttp.send();
}
</script>
<html>
<body>
<h1>Members:</h1>
<button type="button" onclick="load()">Request data</button>
<p id="demo"></p>
</body>
</html>
To read a spreadsheet from google:
download a script called Tabletop and add it to your HTML. (The readme is here)
In Google Docs go up to the File menu and pick Publish to the web. Then click Start publishing. A URL will appear, something like https://docs.google.com/spreadsheet/pub?hl=en_US&hl=en_US&key=0AmYzu_s7QHsmdDNZUzRlYldnWTZCLXdrMXlYQzVxSFE&output=html, that is the URL you will use.
Then call it with this:
<script type="text/javascript">
var public_spreadshseet_url = 'https://docs.google.com/spreadsheet/pub?YOUR_URL_HERE';
// YOUR_URL_HERE sample: hl=en_US&hl=en_US&key=0AmYzu_s7QHsmdDNZUzRlYldnWTZCLXdrMXlYQzVxSFE&output=html
// You get this URL from google docs after you publish the spreadsheet
function init()
{
Tabletop.init(
{
key: public_spreadshseet_url,
callback: showInfo,
simpleSheet: true
})
}
// This function gets called to give output
function showInfo(data)
{
alert("Successfully processed!")
console.log(data); <-- Here is the spreadsheet data
}
</script>
<html>
<body>
<h1>Members:</h1>
<button type="button" onclick="init()">Request data</button>
<p id="demo"></p>
</body>
</html>

Web Scraping Youtube URL on Genius with Request

I am using request along with cheerio to try to grab the link to a song on genius.com. The URL should be a YouTube link. The problem is that I simply cannot get the 'a' element to return its href attribute. This is my code (cheerio and request are loaded farther up in the script).
request('https://genius.com/Eminem-the-monster-lyrics' , function (error, response, body) {
if (!error && response.statusCode == 200) {
var $ = cheerio.load(body);
var url = $('a' , 'div.song_media_controls-provider-icon').attr('href');
}
console.log(url);
});
I apologize if its a stupid problem or a stupid post. I'm still learning with all of this. Thank you to anyone for help.
// jQuery cross domain ajax
$.get("https://genius.com/Eminem-the-monster-lyrics").done(function (data) {
console.log(data);
});
// using XMLHttpRequest
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "https://genius.com/Eminem-the-monster-lyrics", true);
xhttp.send();
<!DOCTYPE html>
<html lang="en">
<head>
<title>NK Chaudhary</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div id="demo">Add here genius.com</div>
</body>
</html>

ajax call to mapped URL

I am trying to make an AJAX call to a localhost URL that I am hosting via java. The URL currently only holds a String.
But when I try to call it from my javascript, I don't get any return value. The code/URL doesn't even work.
Javascript code(For website):
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if(true){
alert('hello!');
document.getElementById('newgame').innerHTML = xhr.responseText;
}
};
xhr.open('GET', 'localhost:8080/highscore', true);
xhr.send(null);`
JAVA class code(currently running):
#RestController
public class Server {
#RequestMapping("/highscore")
public String highScore() {
return "test";
}
}
Why you don't using jQuery instead, as below
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
req_url = "http://localhost:8080/highscore";
$.ajax({
type:"post",
url:req_url,
success:function(data){
alert('hello!');
document.getElementById('newgame').innerHTML = data;
}
});
});
</script>
</head>
<body>
</body>
</html>
Replace localhost:8080/highscore by http://localhost:8080/highscore

change p content with text file one

I'm coding my first website, now I'm trying to change a p content with the content of some text files, which contains long descriptions of what my site is about, actually I've tried many ways, like httprequest(), FileReader() and jquery get, but actually I haven't managed it,because I was running it locally and probably because of the wrong file position, so i created a new small code in witch I tried jquery get, I ran it on "web server for chrome" but it doesn't work.
this is the code:
<!DOCTYPE html>
<html>
<body>
<div><h2 id="demo">Lets change this text</h2></div>
<button type="button" onclick="loadDoc()">Change Content</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<script>
function loadDoc() {
$.get("hello.txt",function(data){
getElementById('demo').innerText= data;
});
}
</script>
</body>
</html>
when I load it, the p and the button are displayed, but when I click the button nothing happens; the .html and the .txt files are in the same folder.
I'have been stuck on it for many days, please help, and don't mark it as duplicate.
any help is appreciate.
You could try this out
<script>
function loadDoc() {
$.get("hello.txt",function(data){
document.getElementById('demo').innerHTML= data;
});
}
</script>
HTML:
<div><h2 id="demo">Lets schange this text</h2></div>
<button type="button" onclick="loadDoc()">Change Content</button>
<button type="button" onclick="loadDocWithHttp()">Change Content from Http request</button>
Using AJAX:
function loadDocWithHttp() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "hello.txt", true);
xhttp.send();
}
Try this
function loadDoc() {
$.ajax({
url : "hello.txt",
dataType: "text",
success : function (result) {
$("#demo").html(result);
}
});
}
First of all do one change in your script as mentioned below
function loadDoc() {
$.get("hello.txt",function(data){
$('#demo').html(data);
});
}
For that button you have to bind click with delegation method on()
$(document).on('click','<your_button_selector>', function(){
alert("hello") // replace and put your code here
});
Good Luck..!!
Instead of
getElementById('demo').innerText= data;
change to below line.
document.getElementById('demo').innerText= data;
Try this :
function loadDoc() {
$.get("hello.txt",function(data){
document.getElementById('demo').text= data;
});
}
or
function loadDoc() {
$.get("hello.txt",function(data){
document.getElementById('demo').innerHTML= data;
});
}
You can use jQuery Ajax function. The error attribute will be helpful to get the exception:
$.ajax({
url: "./seeds/hello.txt",
async: false,
success: function (data){
pageExecute.fileContents = data;
},
error: function (e){
//error print
}
});
1.can u browse http://url/hello.txt in your browner?
2.open the developer tools, does any errors show?
3.getElementById have to be used under document Object

Categories