I have a data.json in my server directory. I am using the following code from w3school to show the data in the browser. W3school Snippet Link
<button type="button" onclick="loadDoc()">Change Content</button>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "/static/data.json", true);
xhttp.send();
}
</script>
</html>
When i click the button, I am able to see the data.json in my webpage. But when i change the data.json and click the button again (without refreshing the page), the updated data isn't shown in the browser.
Am i missing something here?
Well since you are using XMLHttpRequest, you need to make sure that every request is kind of unique, you can do something like:
var uniqueId = (new Date()).getTime()
xhttp.open("GET", "/static/data.json?debug=" + uniqueId, true);
If you were using jQuery ajax (http://api.jquery.com/jquery.ajax/), you just have to pass cache=false, like this:
$.ajax({
cache: false,
//other options...
});
xhttp.open("GET", "/static/data.json?something=RANDOMGUID", true);
Related
I am new to JavaScript. What I want to do is sending an ajax request and get the content of a JSON file and simply put it into a div. This is my code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<title>Ajax 1 - Text File</title>
</head>
<body>
<button id="button">Get Text File</button>
<br><br>
<div id="text"></div>
<script>
document.getElementById("button").addEventListener('click', loadText);
function loadText(){
var xhr = new XMLHttpRequest();
xhr.open('GET', 'users.json', true);
xhr.onload = function(){
if(this.status == 200){
document.getElementById('text').innerHTML = this.responseText;
}
else if (this.status == 404){
document.getElementById('text').innerHTML = 'not found';
}
}
xhr.send();
}
</script>
</body>
</html>
And this is users.json:
[
{
"id":1,
"name":"Rick",
"email":"rick#gmail.com"
},
{
"id":2,
"name":"Negan",
"email":"negan#gmail.com"
}
]
This works fine. But, when I manually updated users.json and change it and refresh the browser, the browser does not show the updated json. It still gives me the previous json file. How can I fix it?
It is possible that the browser is responding with a cached response.
Try appending 'timestamp' so that every time a new request would be made to the server to get updated contents.
document.getElementById("button").addEventListener('click', loadText);
function loadText() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'users.json?ts=' + Date.now(), true);
xhr.onload = function() {
if (this.status == 200) {
document.getElementById('text').innerHTML = this.responseText;
} else if (this.status == 404) {
document.getElementById('text').innerHTML = 'not found';
}
}
xhr.send();
}
<button id="button">Get Text File</button>
<br><br>
<div id="text"></div>
As you have included jQuery in your webpage, I would recommend to use jQuery version of ajax. To disallow the use of the cached results, set cache to false.
$.ajax({
url: 'myurl',
type: 'GET',
dataType: 'json',
data: jsonDataObject,
cache: false, // Appends _={timestamp} to the request query string
success: function(data) {
// data is a json object.
}
});
try check the disable cache checkbox on network panel of the dev tool.
it might be caused by the cache of your web server
You need to pass header
content_type="application/json"
Good day! I'm new to web development and still studying.
I'm trying to create a simple counter using javascript.
index.html
<script src="test.js"></script>
<h1>Count </h1>
<p id="count">0</p>
<button onclick ="mycounter()">Add Count</button>
test.js
var counter = 0;
function mycounter(){
counter = counter + 1;
document.getElementById('count').innerHTML = counter;}
Now this code works perfectly fine. Is it possible to transfer that button to another html file and everytime that button is clicked from the other file, the count display on my index is updated?
Any help would be much appreciated. Thank you.
If you want to transfer part of your html in to another file and use it in a separate file, that is called templating. The usual pattern is to load the contents of the "other" file via XHR and add it to the DOM.
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("buttonholder").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
Please tell me there is such a link. /add.php?id=2 How can I do it without reloading the page, but that the php file is executed.
use ajax
from:
https://www.w3schools.com/xml/ajax_intro.asp
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
You can do it with ajax.
http://api.jquery.com/jquery.ajax/
Javascript will execute that php file.
Ajax demo:
https://www.w3schools.com/xml/ajax_intro.asp
Don't overuse w3schools. I'm giving you this for demo purposes
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 ;(
}
I want to autoupdate page using PHP and Ajax. Right now I have this code on a page:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<i class="fa fa-heart-o"></i>
</body>
</html>
When the user clicks on the link it is redirected to another page called "Page-Like.php"
include("config.php");
//get vars
$idSubliminal=$_GET["idSubliminal"];
$idCategoria=$_GET["idCategoria"];
// mysql_query("insert into Rating .... (mysql insert query)
echo "<script>
location.href=\"AudioSubliminal.php?idSubliminal=$idSubliminal&idCategoria=$idCategoria\";
</script>";
What I want is to do this usig Ajax in order to not refresh the page. I know I'm missing the javascript code, but I would like to get some suggestions to complete this script.
Thanks!
All you need is a basic ajax request to achieve your functionality. check the sample request below.
function ajaxpr(){
var URLString="idSub=12&idCat=32";
ajax_request = $.ajax({
type: 'GET',
url: "Page-Like.php",
data: URLString,
dataType : 'html',
context: $(this),
success: function (msg)
{
//perform the required operation after success
});
}
add function onclick on tag . then define that function using :
$.ajax({
type: 'GET',
data: {idSub: "12", idCat: "32"},
url: "Page-Like.php",
dataType: 'JSON',
success: function (response, textStatus, jqXHR) {
//DEFINE FUNCTION HERE
}
});
This is using ajax function without refresh page.
You can use many methods to implement Ajax on you're code.
One of this is jQuery, other is mootools, etc.. Depends of wich library you know or want to learn.
Using ajax to load a page is easy. Follow this link http://www.w3schools.com/ajax/
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
// Change this to your desired DOM tag
document.body.innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "Page-Like.php?idSub=12&idCat=32", true);
xhttp.send();
}
Now it's just a matter of putting event listener to run loadDoc() function. If the link is dynamic, you can parse the parameter to the function.
However, I notice you have a js script inside your php which will redirect again to AudioSubliminal.php. If this is your desired flow then it's okay. If not, you can create another function
function loadAudioSubliminal(idSub, idCat) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
// Change this to your desired DOM tag
document.body.innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "AudioSubliminal.php?idSubliminal=" + idSub + "&idCategoria=" + idCat, true);
xhttp.send();
}
and modified loadDoc() to receive a parameter such that idSub and idCat can be passed again. for Example :
function loadDoc(idSub, idCat) {
var xhttp = new XMLHttpRequest();
if (xhttp.readyState == 4 && xhttp.status == 200) {
// Change this to your desired DOM tag
document.body.innerHTML = xhttp.responseText;
// run the function after finished loading Page-like.php
loadAudioSubliminal(idSub, idCat)
}
xhttp.open("GET", "Page-Like.php?idSub=" + idSub + "&idCat=" + idCat, true);
xhttp.send();
}